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
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
use std::borrow::Cow;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;

use anyhow::Result;
use chrono::Utc;
use surrealdb_kvs::TransactionType;
#[cfg(any(feature = "kv-surrealkv", feature = "kv-rocksdb"))]
use temp_dir::TempDir;
use tokio::time::{sleep, timeout};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use web_time::Instant;

use super::builder::{Building, IndexKey};
use super::state::{build_owner_expired, report_status_from_phase};
use super::*;
use crate::catalog::providers::{
	CatalogProvider, DatabaseProvider, NamespaceProvider, TableProvider,
};
use crate::catalog::{DatabaseId, Index, IndexDefinition, IndexId, NamespaceId, Record};
use crate::dbs::Session;
use crate::err::Error;
use crate::idx::IndexKeyBase;
use crate::idx::index::IndexOperation;
use crate::key::reclaim::{Expunge, ReclaimKind};
use crate::key::schema::{
	DocKeyPrefix, DocLookupKey, DocLookupPrefix, DocPendingKey, DocPendingPrefix, EntryPrefix,
	IdxRoot, IndexCountKey, IndexCountPrefix, ReclaimKey, ReclaimPrefix, RecordPrefix,
};
use crate::key::{KVKey, KVKeyDecode, KVSubspace, KVValue, Key};
use crate::kvs::index::CleanUncommittedBuild;
use crate::kvs::index::admission::CachedAdmission;
use crate::kvs::testing::{
	NonRetryableErrorSite, RetryableConflictGuard, RetryableConflictSite,
	inject_non_retryable_error, inject_retryable_conflict, inject_retryable_conflicts,
	retryable_conflict_count,
};
use crate::kvs::tx::{
	CachedIndexBuildReservationKey, CachedIndexBuildReservationLookup, IndexBuildReservationRelease,
};
use crate::kvs::{Datastore, DatastoreError, is_retryable_transaction_conflict, storage_error};
use crate::val::{RecordId, RecordIdKey, RecordIdentity, TableName, Value};

const REPEATED_RETRY_CONFLICTS: usize = 1000;

async fn new_index_test_ds() -> Result<(Arc<Datastore>, Session)> {
	// These tests adopt, resume and observe index builds directly, and assert on
	// when the datastore's own state is released. A background scheduler running
	// `resume_stalled_index_builds` would claim the same builds.
	let ds = Datastore::builder().without_maintenance_tasks().build_with_path("memory").await?;
	let session = Session::owner().with_ns("test").with_db("test");
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.ensure_ns_db(None, "test", "test").await?;
	tx.commit().await?;
	Ok((ds, session))
}

#[cfg(feature = "kv-mem")]
async fn new_distributed_index_test_ds() -> Result<(Arc<Datastore>, Datastore, Session)> {
	let (ds_a, session) = new_index_test_ds().await?;
	let ds_b = ds_a.fork_for_test_with_node_id(uuid::Uuid::new_v4());
	// Both simulated compute nodes must be visible in durable node
	// membership so reservation liveness checks treat their tickets as
	// owned by active writers.
	ds_a.insert_node().await?;
	ds_b.insert_node().await?;
	Ok((ds_a, ds_b, session))
}

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

async fn execute_cancelled_transaction(ds: &Datastore, session: &Session, sql: &str) -> Result<()> {
	let results = ds.execute(sql, session, None).await?;
	let error = results.into_iter().find_map(|result| result.result.err());
	assert!(
		error
			.expect("transaction should be reported as cancelled")
			.to_string()
			.contains("cancelled transaction")
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
fn is_retryable_statement_conflict(err: &anyhow::Error) -> bool {
	is_retryable_transaction_conflict(err)
		|| err.to_string().starts_with("Transaction conflict:")
		|| err.downcast_ref::<surrealdb_types::Error>().is_some_and(|err| {
			matches!(
				err.details(),
				surrealdb_types::ErrorDetails::Query(Some(
					surrealdb_types::QueryError::TransactionConflict
				))
			)
		})
}

#[cfg(feature = "kv-mem")]
async fn execute_all_retrying_conflicts(
	ds: &Datastore,
	session: &Session,
	sql: &str,
) -> Result<()> {
	// The paused-build tests intentionally hold the builder in a retry loop.
	// User writes can observe statement-level transaction conflicts while
	// the durable admission state is being advanced, so retry here to keep
	// the assertions focused on whether queued writes are eventually replayed.
	timeout(Duration::from_secs(10), async {
		loop {
			match execute_all(ds, session, sql).await {
				Ok(()) => return Ok(()),
				Err(err) if is_retryable_statement_conflict(&err) => {
					sleep(Duration::from_millis(10)).await;
				}
				Err(err) => return Err(err),
			}
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out retrying statement during index build"))?
}

#[cfg(feature = "kv-mem")]
async fn execute_cancelled_transaction_retrying_conflicts(
	ds: &Datastore,
	session: &Session,
	sql: &str,
) -> Result<()> {
	timeout(Duration::from_secs(10), async {
		loop {
			match execute_cancelled_transaction(ds, session, sql).await {
				Ok(()) => return Ok(()),
				Err(err) if is_retryable_statement_conflict(&err) => {
					sleep(Duration::from_millis(10)).await;
				}
				Err(err) => return Err(err),
			}
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out retrying cancelled statement during index build"))?
}

#[cfg(feature = "kv-mem")]
async fn execute_error_text_retrying_conflicts(
	ds: &Datastore,
	session: &Session,
	sql: &str,
) -> Result<String> {
	timeout(Duration::from_secs(10), async {
		loop {
			let results = ds.execute(sql, session, None).await?;
			let error = results
				.into_iter()
				.find_map(|result| result.result.err())
				.expect("transaction should report an error")
				.to_string();
			if error.starts_with("Transaction conflict:") {
				sleep(Duration::from_millis(10)).await;
				continue;
			}
			return Ok(error);
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out retrying errored statement during index build"))?
}

async fn wait_for_index_ready(
	ds: &Datastore,
	session: &Session,
	table: &str,
	index: &str,
) -> Result<()> {
	let sql = format!("INFO FOR INDEX {index} ON {table}");
	timeout(Duration::from_secs(10), async {
		loop {
			let mut results = ds.execute(&sql, session, None).await?;
			let value = results.remove(0).result?;
			let json = value.into_json_value();
			let status = json
				.pointer("/building/status")
				.and_then(|status| status.as_str())
				.unwrap_or_default();
			match status {
				"ready" => return Ok(()),
				"error" => anyhow::bail!("index build entered error state: {json}"),
				_ => sleep(Duration::from_millis(20)).await,
			}
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out waiting for concurrent index build"))?
}

async fn index_building_json(
	ds: &Datastore,
	session: &Session,
	table: &str,
	index: &str,
) -> Result<serde_json::Value> {
	let sql = format!("INFO FOR INDEX {index} ON {table}");
	let mut results = ds.execute(&sql, session, None).await?;
	let value = results.remove(0).result?;
	let json = value.into_json_value();
	json.get("building")
		.cloned()
		.ok_or_else(|| anyhow::anyhow!("index info did not include building status: {json}"))
}

async fn index_building_status(
	ds: &Datastore,
	session: &Session,
	table: &str,
	index: &str,
) -> Result<String> {
	let building = index_building_json(ds, session, table, index).await?;
	building
		.get("status")
		.and_then(|status| status.as_str())
		.map(str::to_owned)
		.ok_or_else(|| anyhow::anyhow!("index info did not include building.status: {building}"))
}

async fn durable_build_state(ds: &Datastore, ikb: &IndexKeyBase) -> Result<IndexBuildState> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let state = catch!(tx, tx.get_key(&ikb.new_bs_key(), None).await)
		.ok_or_else(|| anyhow::anyhow!("durable build state should exist"))?;
	tx.cancel().await?;
	Ok(state)
}

/// Read the build state and its generation's writer-ticket counter from one
/// snapshot.
///
/// The `Building` -> `Closing` fence advances the counter in the same
/// transaction as the phase write, so a caller that has to tell a writer
/// admission from that fence must observe both keys at the same version.
async fn durable_build_state_with_ticket_counter(
	ds: &Datastore,
	ikb: &IndexKeyBase,
) -> Result<(IndexBuildState, Option<BuildTicket>)> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let state = catch!(tx, tx.get_key(&ikb.new_bs_key(), None).await)
		.ok_or_else(|| anyhow::anyhow!("durable build state should exist"))?;
	let counter = catch!(tx, tx.get_key(&ikb.new_bt_key(state.generation), None).await);
	tx.cancel().await?;
	Ok((state, counter))
}

async fn set_durable_build_state(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	state: IndexBuildState,
) -> Result<()> {
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(&ikb.new_bs_key(), &state).await?;
	tx.commit().await
}

fn durable_build_state_for_phase(
	phase: IndexBuildPhase,
	generation: BuildGeneration,
	owner: Option<Uuid>,
) -> IndexBuildState {
	let now = Utc::now();
	IndexBuildState {
		generation,
		phase,
		owner,
		next_ticket: 0,
		initial_complete: true,
		updated_at: now,
		owner_heartbeat_at: owner.map(|_| now),
		error: None,
		report_status: Some(report_status_from_phase(phase)),
		initial: Some(1),
		updated: Some(0),
		pending: Some(0),
		initial_cursor: None,
	}
}

async fn durable_build_state_exists(ds: &Datastore, ikb: &IndexKeyBase) -> Result<bool> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let state: Option<IndexBuildState> = catch!(tx, tx.get_key(&ikb.new_bs_key(), None).await);
	tx.cancel().await?;
	Ok(state.is_some())
}

async fn new_building_for_index(
	ds: &Datastore,
	session: &Session,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: Arc<IndexDefinition>,
) -> Result<Building> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let table_def = catch!(tx, tx.get_tb(ns, db, table, None).await).expect("table should exist");
	let mut ctx = ds.setup_ctx()?;
	let tx = Arc::new(tx);
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let build = Building::new(
		&ctx,
		ds.transaction_factory().clone(),
		ds.setup_options(session),
		table_def.table_id,
		Arc::clone(&ix),
		Arc::new(IndexKey::new(ns, db, table, ix.index_id)),
	)?;
	tx.cancel().await?;
	Ok(build)
}

#[cfg(feature = "kv-mem")]
async fn start_index_build_paused(
	ds: &Datastore,
	session: &Session,
	sql: &str,
) -> Result<RetryableConflictGuard> {
	let site = RetryableConflictSite::ConcurrentIndexInitialCleanup;
	let node_id = ds.id();
	let guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);
	execute_all(ds, session, sql).await?;
	// Wait until the builder has reached the injected conflict site before
	// returning. At that point durable state is Building and second-node
	// writes must go through the admission queue.
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;
	Ok(guard)
}

#[cfg(feature = "kv-mem")]
struct PausedRemoveBuild {
	ds: Arc<Datastore>,
	session: Session,
	guard: RetryableConflictGuard,
	ns: NamespaceId,
	db: DatabaseId,
	table: TableName,
	ix: Arc<IndexDefinition>,
	builder: IndexBuilding,
}

#[cfg(feature = "kv-mem")]
async fn start_paused_remove_build() -> Result<PausedRemoveBuild> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let builder = local_builder_for_key(&ds, ns, db, &table, ix.index_id)
		.await?
		.expect("local builder should be running");

	Ok(PausedRemoveBuild {
		ds,
		session,
		guard,
		ns,
		db,
		table,
		ix,
		builder,
	})
}

#[cfg(feature = "kv-mem")]
async fn assert_cancelled_remove_keeps_local_builder(sql: &str) -> Result<()> {
	let PausedRemoveBuild {
		ds,
		session,
		guard,
		ns,
		db,
		table,
		ix,
		builder,
	} = start_paused_remove_build().await?;

	execute_cancelled_transaction_retrying_conflicts(&ds, &session, sql).await?;
	sleep(Duration::from_millis(200)).await;

	assert!(
		!builder.is_finished(),
		"cancelled cascading remove must not abort the still-valid local builder"
	);
	assert!(
		local_builder_for_key(&ds, ns, db, &table, ix.index_id).await?.is_some(),
		"cancelled cascading remove must keep the builder map entry"
	);

	drop(guard);
	wait_for_index_ready(&ds, &session, "user", "test").await?;
	Ok(())
}

/// Resume a parked build, optionally deleting its durable state first, and
/// report what it committed: the number of index-data keys, and whether `!bs`
/// came back.
///
/// No retirement runs here and no abort flag is raised, so the only thing that
/// can stop the build is the state deletion itself. That is the point: the
/// process-local abort would otherwise stop the task first and the fence would
/// never be exercised.
#[cfg(feature = "kv-mem")]
async fn resume_paused_build_and_count(delete_build_state: bool) -> Result<(usize, bool)> {
	let PausedRemoveBuild {
		ds,
		session: _session,
		guard,
		ns,
		db,
		table,
		ix,
		builder,
	} = start_paused_remove_build().await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	assert!(
		durable_build_state_exists(&ds, &ikb).await?,
		"the parked build must have durable state for either arm to mean anything"
	);
	if delete_build_state {
		let txn = ds.transaction(TransactionType::Write).await?;
		catch!(txn, txn.del_key(&ikb.new_bs_key()).await);
		txn.commit().await?;
		assert!(
			!builder.is_finished(),
			"the builder must still be live when the state is deleted, or the window \
			 under test was not reproduced"
		);
	}
	// Wait on the task rather than on the builder map entry: no retirement ran
	// here, so nothing retires that entry — what settles is the task itself.
	drop(guard);
	timeout(Duration::from_secs(30), builder.wait_finished())
		.await
		.map_err(|_| anyhow::anyhow!("the resumed build task did not finish"))?;
	Ok((
		index_prefix_key_count(&ds, ns, db, &table, ix.index_id).await?,
		durable_build_state_exists(&ds, &ikb).await?,
	))
}

/// Deleting `!bs` is what stops a build, and this is the test that says so.
///
/// Every retirement path relies on it: the schema transaction deletes `!bs`
/// beside the catalog entry, and from that point a builder cannot commit index
/// data because each of its write transactions reads and compare-and-swaps that
/// key before the batch's other writes. Aborting the process-local task is a
/// courtesy on top, and it is deliberately not used here — it would stop the
/// task before the fence was ever reached, which is why the removal tests
/// cannot stand in for this one.
///
/// Three call sites enforce it for a build in progress —
/// `maintain_build_ownership`, `update_build_state_in_tx` and
/// `update_owned_build_state_inner` — and a build's path through a batch
/// crosses all three, so relaxing any one of them alone does not open the
/// window. Anything that makes a missing `!bs` survivable at *every* one of
/// them fails the fenced arm below. Compaction runs after `Online` and is
/// fenced separately, by the locked read in
/// `compaction_write_still_owns_index`; see
/// `compaction_write_fence_conflicts_with_a_retirement_that_commits_after_it`.
///
/// Two arms, because that is what makes it mean anything: the control resumes
/// the same harness untouched and asserts it *does* commit, so a sabotaged
/// fence fails the test instead of quietly satisfying it.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn deleting_build_state_stops_a_running_builder_committing() -> Result<()> {
	let (control_keys, _) = resume_paused_build_and_count(false).await?;
	assert!(
		control_keys > 0,
		"the control arm must commit index data, or the fenced arm proves nothing"
	);

	let (fenced_keys, state_back) = resume_paused_build_and_count(true).await?;
	assert_eq!(
		fenced_keys, 0,
		"a build whose durable state was deleted must not commit index data \
		 (control committed {control_keys})"
	);
	assert!(!state_back, "a stopped build must not recreate the durable state it was stopped by");
	Ok(())
}

#[cfg(feature = "kv-mem")]
async fn assert_committed_remove_aborts_local_builder(sql: &str) -> Result<()> {
	let PausedRemoveBuild {
		ds,
		session,
		guard,
		ns,
		db,
		table,
		ix,
		builder,
	} = start_paused_remove_build().await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	seed_durable_queue_generation(&ds, &ikb, 99).await?;
	assert_eq!(durable_queue_all_generations_count(&ds, &ikb).await?, 3);

	execute_all_retrying_conflicts(&ds, &session, sql).await?;
	wait_for_no_local_builder(&ds, ns, db, &table, ix.index_id).await?;
	// The removal's own transaction deleted the build state and every queue,
	// so nothing is left before the paused builder is even released.
	assert_no_index_build_artifacts(&ds, ns, db, &table, ix.index_id).await?;
	// Releasing it is the fence test. The builder resumes into a batch that
	// reads `!bs` first, finds it gone, and stops without committing. Waiting
	// for the task is what makes the second assertion mean "it ran and wrote
	// nothing" rather than "it had not run yet".
	drop(guard);
	wait_for_finished_builder(&builder).await?;
	assert_no_index_build_artifacts(&ds, ns, db, &table, ix.index_id).await?;
	Ok(())
}

async fn query_array_len(ds: &Datastore, session: &Session, sql: &str) -> Result<usize> {
	let mut results = ds.execute(sql, session, None).await?;
	let value = results.remove(0).result?;
	let surrealdb_types::Value::Array(rows) = value else {
		anyhow::bail!("query returned non-array value: {value:?}");
	};
	Ok(rows.len())
}

async fn expect_indexed_query_len(
	ds: &Datastore,
	session: &Session,
	sql: &str,
	expected: usize,
) -> Result<()> {
	let len = query_array_len(ds, session, sql).await?;
	assert_eq!(len, expected, "unexpected row count for query: {sql}");
	Ok(())
}

async fn get_table_index(
	ds: &Datastore,
	table: &str,
	index: &str,
) -> Result<(NamespaceId, DatabaseId, TableName, Arc<IndexDefinition>)> {
	let table = TableName::from(table);
	let tx = ds.transaction(TransactionType::Read).await?;
	let ns = catch!(tx, tx.get_ns_by_name("test", None).await).expect("namespace should exist");
	let db =
		catch!(tx, tx.get_db_by_name("test", "test", None).await).expect("database should exist");
	let ix = catch!(tx, tx.expect_tb_index(ns.namespace_id, db.database_id, &table, index).await);
	tx.cancel().await?;
	Ok((ns.namespace_id, db.database_id, table, ix))
}

async fn get_table_ids(
	ds: &Datastore,
	table: &str,
) -> Result<(NamespaceId, DatabaseId, TableName)> {
	let table = TableName::from(table);
	let tx = ds.transaction(TransactionType::Read).await?;
	let ns = catch!(tx, tx.get_ns_by_name("test", None).await).expect("namespace should exist");
	let db =
		catch!(tx, tx.get_db_by_name("test", "test", None).await).expect("database should exist");
	catch!(tx, tx.get_tb(ns.namespace_id, db.database_id, &table, None).await)
		.expect("table should exist");
	tx.cancel().await?;
	Ok((ns.namespace_id, db.database_id, table))
}

async fn local_builder_for_key(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: IndexId,
) -> Result<Option<IndexBuilding>> {
	let ctx = ds.setup_ctx()?;
	let Some(index_builder) = ctx.get_index_builder() else {
		return Ok(None);
	};
	let key = Arc::new(IndexKey::new(ns, db, table, ix));
	Ok(index_builder.indexes.read().await.get(&key).cloned())
}

/// Wait for a builder task to exit.
///
/// A committed retirement returns without waiting for the task: it is fenced by
/// the `!bs` delete rather than by a close-time drain, so its map entry is gone
/// while the task itself is still winding down. A test that asserts on what the
/// task did has to wait for it here.
async fn wait_for_finished_builder(building: &IndexBuilding) -> Result<()> {
	timeout(Duration::from_secs(10), async {
		loop {
			if building.is_finished() {
				return Ok(());
			}
			sleep(Duration::from_millis(10)).await;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out waiting for the index builder task to exit"))?
}

async fn wait_for_no_local_builder(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: IndexId,
) -> Result<()> {
	timeout(Duration::from_secs(10), async {
		loop {
			if local_builder_for_key(ds, ns, db, table, ix).await?.is_none() {
				return Ok(());
			}
			sleep(Duration::from_millis(10)).await;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out waiting for local index builder abort"))?
}

fn previous_index_id(ix: IndexId) -> IndexId {
	assert!(ix.0 > 0, "test expected a previous allocated index id before {ix:?}");
	IndexId(ix.0 - 1)
}

async fn assert_no_index_build_artifacts(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: IndexId,
) -> Result<()> {
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix);
	assert!(!durable_build_state_exists(ds, &ikb).await?);
	assert_eq!(durable_queue_all_generations_count(ds, &ikb).await?, 0);
	assert_eq!(
		durable_ticket_counter_count(ds, &ikb).await?,
		0,
		"a retired or rolled-back build must not strand its generation ticket counter"
	);
	assert_eq!(index_prefix_key_count(ds, ns, db, table, ix).await?, 0);
	assert!(local_builder_for_key(ds, ns, db, table, ix).await?.is_none());
	Ok(())
}

async fn index_reclaim_modes(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	tb: &TableName,
	ix: IndexId,
) -> Result<Vec<Expunge>> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let entries = catch!(tx, tx.getr_raw(ReclaimPrefix {}.range()?, None).await);
	tx.cancel().await?;
	Ok(entries
		.into_iter()
		.filter_map(|(key, _)| {
			let reclaim = ReclaimKey::decode_key(&key).ok()?;
			(reclaim.kind == ReclaimKind::Index
				&& reclaim.ns == ns
				&& reclaim.db == db
				&& reclaim.tb.as_ref() == tb
				&& reclaim.ix == ix)
				.then_some(reclaim.expunge)
		})
		.collect())
}

async fn index_prefix_key_count(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: IndexId,
) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let key = IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(table),
		ix,
	};
	let keys: Vec<(Vec<u8>, Vec<u8>)> = catch!(tx, tx.get_prefix_key(&key, None).await);
	tx.cancel().await?;
	Ok(keys.len())
}

async fn seed_durable_queue_generation(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	generation: BuildGeneration,
) -> Result<()> {
	let tx = ds.transaction(TransactionType::Write).await?;
	let id = RecordIdKey::from(format!("stale-{generation}"));
	let ticket = generation;
	let mutation_seq = 0;
	tx.set_key(
		&ikb.new_bg_key(generation, ticket, mutation_seq),
		&Appending {
			old_values: None,
			new_values: None,
			id: id.clone(),
			count_cond_match: None,
		},
	)
	.await?;
	tx.set_key(
		&ikb.new_bp_key(generation, &id),
		&PrimaryAppendingTicket {
			ticket,
			mutation_seq,
		},
	)
	.await?;
	tx.set_key(
		&ikb.new_br_key(generation, ticket),
		&IndexBuildReservation {
			node: ds.id(),
			expires_at: Utc::now() + chrono::Duration::seconds(BUILD_RESERVATION_TTL_SECS),
		},
	)
	.await?;
	tx.commit().await?;
	Ok(())
}

async fn seed_uncommitted_index_build_artifacts(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: IndexId,
) -> Result<()> {
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&durable_build_state_for_phase(IndexBuildPhase::Building, 1, Some(ds.id())),
	)
	.await?;
	let id = RecordIdKey::from("orphan".to_owned());
	let ticket = 1;
	let mutation_seq = 0;
	tx.set_key(
		&ikb.new_bg_key(1, ticket, mutation_seq),
		&Appending {
			old_values: None,
			new_values: None,
			id: id.clone(),
			count_cond_match: None,
		},
	)
	.await?;
	tx.set_key(
		&ikb.new_bp_key(1, &id),
		&PrimaryAppendingTicket {
			ticket,
			mutation_seq,
		},
	)
	.await?;
	tx.set_key(
		&ikb.new_br_key(1, ticket),
		&IndexBuildReservation {
			node: ds.id(),
			expires_at: Utc::now() + chrono::Duration::seconds(BUILD_RESERVATION_TTL_SECS),
		},
	)
	.await?;
	let index_data_key = IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(table),
		ix,
	}
	.encode_bound()?;
	let mut idx_key = index_data_key.into_vec();
	idx_key.extend_from_slice(b"orphan");
	tx.set(Key::from(idx_key), b"orphan".to_vec()).await?;
	tx.commit().await?;
	Ok(())
}

async fn durable_queue_generation_count(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	generation: BuildGeneration,
) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let bg = catch!(tx, tx.keys(ikb.new_bg_range(generation)?, u32::MAX, 0, None).await);
	let bp = catch!(tx, tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await);
	let br = catch!(tx, tx.keys(ikb.new_br_range(generation)?, u32::MAX, 0, None).await);
	tx.cancel().await?;
	Ok(bg.len() + bp.len() + br.len())
}

/// Count the ticket counters left behind across every generation of an index.
async fn durable_ticket_counter_count(ds: &Datastore, ikb: &IndexKeyBase) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let bt = catch!(tx, tx.keys(ikb.new_bt_all_generations_range()?, u32::MAX, 0, None).await);
	tx.cancel().await?;
	Ok(bt.len())
}

async fn durable_queue_all_generations_count(ds: &Datastore, ikb: &IndexKeyBase) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let bg = catch!(tx, tx.keys(ikb.new_bg_all_generations_range()?, u32::MAX, 0, None).await);
	let bp = catch!(tx, tx.keys(ikb.new_bp_all_generations_range()?, u32::MAX, 0, None).await);
	let br = catch!(tx, tx.keys(ikb.new_br_all_generations_range()?, u32::MAX, 0, None).await);
	tx.cancel().await?;
	Ok(bg.len() + bp.len() + br.len())
}

#[cfg(feature = "kv-mem")]
async fn expect_statement_error(ds: &Datastore, session: &Session, sql: &str) -> Result<()> {
	let mut results = ds.execute(sql, session, None).await?;
	let result = results.remove(0).result;
	if result.is_ok() {
		anyhow::bail!("statement unexpectedly succeeded: {sql}");
	}
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_import_replay_preserves_existing_index_without_rebuild() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, old_ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, old_ix.index_id);
	let before = durable_build_state(&ds, &ikb).await?;

	execute_all(&ds, &session, "OPTION IMPORT; DEFINE INDEX test ON user FIELDS email;").await?;

	let (_, _, _, current_ix) = get_table_index(&ds, "user", "test").await?;
	let after = durable_build_state(&ds, &ikb).await?;
	assert_eq!(current_ix.index_id, old_ix.index_id);
	assert_eq!(after.generation, before.generation);
	assert_eq!(after.phase, IndexBuildPhase::Online);
	assert_eq!(index_building_status(&ds, &session, "user", "test").await?, "ready");
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT * FROM user WITH INDEX test WHERE email = 'one@example.com'",
		1,
	)
	.await?;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_import_replay_updates_comment_without_rebuild() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email COMMENT 'old comment';
			",
	)
	.await?;
	let (ns, db, table, old_ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, old_ix.index_id);
	let before = durable_build_state(&ds, &ikb).await?;

	execute_all(
		&ds,
		&session,
		"OPTION IMPORT; DEFINE INDEX test ON user FIELDS email COMMENT 'new comment';",
	)
	.await?;

	let (_, _, _, current_ix) = get_table_index(&ds, "user", "test").await?;
	let after = durable_build_state(&ds, &ikb).await?;
	assert_eq!(current_ix.index_id, old_ix.index_id);
	assert_eq!(current_ix.comment.as_deref(), Some("new comment"));
	assert_eq!(after.generation, before.generation);
	assert_eq!(after.phase, IndexBuildPhase::Online);
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT * FROM user WITH INDEX test WHERE email = 'one@example.com'",
		1,
	)
	.await?;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_import_changed_definition_rebuilds_with_fresh_index_id() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', account = 'apple' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, old_ix) = get_table_index(&ds, "user", "test").await?;
	let old_ikb = IndexKeyBase::new(ns, db, table.clone(), old_ix.index_id);
	let before = durable_build_state(&ds, &old_ikb).await?;

	execute_all(&ds, &session, "OPTION IMPORT; DEFINE INDEX test ON user FIELDS account;").await?;

	let (_, _, _, current_ix) = get_table_index(&ds, "user", "test").await?;
	let current_ikb = IndexKeyBase::new(ns, db, table.clone(), current_ix.index_id);
	let after = durable_build_state(&ds, &current_ikb).await?;
	assert_ne!(current_ix.index_id, old_ix.index_id);
	assert_eq!(after.generation, 1);
	assert_eq!(after.phase, IndexBuildPhase::Online);
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT * FROM user WITH INDEX test WHERE account = 'apple'",
		1,
	)
	.await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let old_lookup = catch!(tx, tx.get_tb_index_by_id(ns, db, &table, old_ix.index_id, None).await);
	tx.cancel().await?;
	assert!(old_lookup.is_none(), "old index id lookup should be retired");
	assert_eq!(before.phase, IndexBuildPhase::Online);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn remove_index_cancel_preserves_durable_ready_state() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	assert_eq!(index_building_status(&ds, &session, "user", "test").await?, "ready");

	execute_cancelled_transaction(&ds, &session, "BEGIN; REMOVE INDEX test ON user; CANCEL;")
		.await?;

	assert_eq!(index_building_status(&ds, &session, "user", "test").await?, "ready");
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT * FROM user WITH INDEX test WHERE email = 'one@example.com'",
		1,
	)
	.await?;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn remove_index_committed_deletes_durable_queue_keys() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'one@example.com' RETURN NONE;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	seed_durable_queue_generation(&ds, &ikb, 1).await?;
	assert!(durable_build_state_exists(&ds, &ikb).await?);
	assert_eq!(durable_queue_all_generations_count(&ds, &ikb).await?, 3);

	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	assert!(!durable_build_state_exists(&ds, &ikb).await?);
	assert_eq!(durable_queue_all_generations_count(&ds, &ikb).await?, 0);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_index_cancel_keeps_local_builder_running() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'one@example.com' RETURN NONE;
				CREATE user:two SET email = 'two@example.com' RETURN NONE;
				",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let builder = local_builder_for_key(&ds, ns, db, &table, ix.index_id)
		.await?
		.expect("local builder should be running");

	execute_cancelled_transaction_retrying_conflicts(
		&ds,
		&session,
		"BEGIN; REMOVE INDEX test ON user; CANCEL;",
	)
	.await?;
	sleep(Duration::from_millis(200)).await;

	assert!(
		!builder.is_finished(),
		"cancelled REMOVE INDEX must not abort the still-valid local builder"
	);
	assert!(
		local_builder_for_key(&ds, ns, db, &table, ix.index_id).await?.is_some(),
		"cancelled REMOVE INDEX must keep the builder map entry"
	);

	drop(guard);
	wait_for_index_ready(&ds, &session, "user", "test").await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_index_commit_aborts_local_builder_after_commit() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'one@example.com' RETURN NONE;
				CREATE user:two SET email = 'two@example.com' RETURN NONE;
				",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let builder = local_builder_for_key(&ds, ns, db, &table, ix.index_id)
		.await?
		.expect("local builder should be running");

	execute_all_retrying_conflicts(&ds, &session, "REMOVE INDEX test ON user").await?;
	wait_for_no_local_builder(&ds, ns, db, &table, ix.index_id).await?;
	assert_no_index_build_artifacts(&ds, ns, db, &table, ix.index_id).await?;
	// The released builder must not be able to bring any of it back: its next
	// batch reads the `!bs` the removal deleted and stops there.
	drop(guard);
	wait_for_finished_builder(&builder).await?;
	assert_no_index_build_artifacts(&ds, ns, db, &table, ix.index_id).await?;
	// Scoped to this index's own entries: dropping the table's last doc-ID
	// consumer also queues the table's shared doc-ID prefixes, which this
	// assertion is not about. One entry, committed with the catalog removal,
	// owns the data prefix; the retirement queues nothing after it.
	assert_eq!(
		index_reclaim_modes(&ds, ns, db, &table, ix.index_id).await?.len(),
		1,
		"retirement must queue exactly the schema tombstone for the index data"
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_table_cancel_keeps_local_builder_running() -> Result<()> {
	assert_cancelled_remove_keeps_local_builder("BEGIN; REMOVE TABLE user; CANCEL;").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_database_cancel_keeps_local_builder_running() -> Result<()> {
	assert_cancelled_remove_keeps_local_builder("BEGIN; REMOVE DATABASE test; CANCEL;").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_namespace_cancel_keeps_local_builder_running() -> Result<()> {
	assert_cancelled_remove_keeps_local_builder("BEGIN; REMOVE NAMESPACE test; CANCEL;").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_table_commit_aborts_local_builder_after_commit() -> Result<()> {
	assert_committed_remove_aborts_local_builder("REMOVE TABLE user").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_database_commit_aborts_local_builder_after_commit() -> Result<()> {
	assert_committed_remove_aborts_local_builder("REMOVE DATABASE test").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_namespace_commit_aborts_local_builder_after_commit() -> Result<()> {
	assert_committed_remove_aborts_local_builder("REMOVE NAMESPACE test").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_table_expunge_aborts_local_builder_after_commit() -> Result<()> {
	assert_committed_remove_aborts_local_builder("REMOVE TABLE AND EXPUNGE user").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_database_expunge_aborts_local_builder_after_commit() -> Result<()> {
	assert_committed_remove_aborts_local_builder("REMOVE DATABASE AND EXPUNGE test").await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_namespace_expunge_aborts_local_builder_after_commit() -> Result<()> {
	assert_committed_remove_aborts_local_builder("REMOVE NAMESPACE AND EXPUNGE test").await
}

/// `EXPUNGE` must reach the build-state keys a cascading removal retires, not
/// only the data prefixes it queues. Each statement retires them through a
/// different level of the cascade, so each is exercised: an `EXPUNGE` that a
/// level drops leaves a historical `!bs` a versioned read can still resolve.
#[cfg(feature = "kv-surrealkv")]
async fn assert_removal_expunges_historical_build_state(sql: &str) -> Result<()> {
	let dir = TempDir::new()?;
	let path = format!("surrealkv://{}?versioned=true&retention=1h", dir.path().to_string_lossy());
	let ds = Datastore::builder().without_maintenance_tasks().build_with_path(&path).await?;
	let session = Session::owner().with_ns("test").with_db("test");
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.ensure_ns_db(None, "test", "test").await?;
	tx.commit().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// A build that has reached `Online` still holds a committed `!bs`, which
	// is the version the removal has to expunge.
	let tx = ds.transaction(TransactionType::Read).await?;
	assert!(tx.get_key(&ikb.new_bs_key(), None).await?.is_some());
	let before_removal: u64 = std::time::SystemTime::now()
		.duration_since(std::time::UNIX_EPOCH)?
		.as_nanos()
		.try_into()?;
	assert!(tx.get_key(&ikb.new_bs_key(), Some(before_removal)).await?.is_some());
	tx.cancel().await?;

	execute_all(&ds, &session, sql).await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let historical = tx.get_key(&ikb.new_bs_key(), Some(before_removal)).await?;
	tx.cancel().await?;
	assert!(
		historical.is_none(),
		"`{sql}` must expunge the historical durable build state it retires"
	);
	Ok(())
}

#[cfg(feature = "kv-surrealkv")]
#[tokio::test]
async fn remove_table_expunge_removes_historical_durable_build_state() -> Result<()> {
	assert_removal_expunges_historical_build_state("REMOVE TABLE AND EXPUNGE user").await
}

#[cfg(feature = "kv-surrealkv")]
#[tokio::test]
async fn remove_database_expunge_removes_historical_durable_build_state() -> Result<()> {
	assert_removal_expunges_historical_build_state("REMOVE DATABASE AND EXPUNGE test").await
}

#[cfg(feature = "kv-surrealkv")]
#[tokio::test]
async fn remove_namespace_expunge_removes_historical_durable_build_state() -> Result<()> {
	assert_removal_expunges_historical_build_state("REMOVE NAMESPACE AND EXPUNGE test").await
}

#[cfg(feature = "kv-surrealkv")]
#[tokio::test]
async fn expunge_removes_historical_durable_build_state() -> Result<()> {
	let dir = TempDir::new()?;
	let path = format!("surrealkv://{}?versioned=true&retention=1h", dir.path().to_string_lossy());
	let ds = Datastore::builder().without_maintenance_tasks().build_with_path(&path).await?;
	let ns = NamespaceId(1);
	let db = DatabaseId(2);
	let table = TableName::from("user");
	let ix = IndexId(3);
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix);

	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&durable_build_state_for_phase(IndexBuildPhase::Building, 1, Some(ds.id())),
	)
	.await?;
	tx.commit().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	assert!(tx.get_key(&ikb.new_bs_key(), None).await?.is_some());
	let before_expunge = std::time::SystemTime::now()
		.duration_since(std::time::UNIX_EPOCH)?
		.as_nanos()
		.try_into()?;
	assert!(tx.get_key(&ikb.new_bs_key(), Some(before_expunge)).await?.is_some());
	tx.cancel().await?;

	let tx = ds.transaction(TransactionType::Write).await?;
	retire_durable_index(&tx, ns, db, &table, ix, true).await?;
	tx.commit().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	assert!(
		tx.get_key(&ikb.new_bs_key(), Some(before_expunge)).await?.is_none(),
		"EXPUNGE must remove historical durable build-state versions"
	);
	tx.cancel().await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn same_transaction_define_concurrent_index_write_uses_fresh_fence_snapshot() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'old@example.com' RETURN NONE;
				",
	)
	.await?;

	let site = RetryableConflictSite::ConcurrentIndexInitialCleanup;
	let node_id = ds.id();
	let guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);
	execute_all(
		&ds,
		&session,
		"
				BEGIN;
				DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
				UPDATE user:one SET email = 'new@example.com' RETURN NONE;
				COMMIT;
				",
	)
	.await?;
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;
	drop(guard);
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'new@example.com'",
		1,
	)
	.await?;
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'old@example.com'",
		0,
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn same_transaction_overwrite_concurrent_index_write_uses_fresh_fence_snapshot() -> Result<()>
{
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'old@example.com', account = 'old-account' RETURN NONE;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;

	let site = RetryableConflictSite::ConcurrentIndexInitialCleanup;
	let node_id = ds.id();
	let guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);
	execute_all(
		&ds,
		&session,
		"
				BEGIN;
				DEFINE INDEX OVERWRITE test ON user FIELDS account CONCURRENTLY;
				UPDATE user:one SET account = 'new-account' RETURN NONE;
				COMMIT;
				",
	)
	.await?;
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;
	drop(guard);
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE account = 'new-account'",
		1,
	)
	.await?;
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE account = 'old-account'",
		0,
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn define_index_overwrite_aborts_retired_local_builder_after_commit() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'one@example.com', account = 'apple' RETURN NONE;
				CREATE user:two SET email = 'two@example.com', account = 'banana' RETURN NONE;
				",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let (ns, db, table, old_ix) = get_table_index(&ds, "user", "test").await?;
	let old_builder = local_builder_for_key(&ds, ns, db, &table, old_ix.index_id)
		.await?
		.expect("retired local builder should be running");

	execute_all_retrying_conflicts(
		&ds,
		&session,
		"DEFINE INDEX OVERWRITE test ON user FIELDS account CONCURRENTLY",
	)
	.await?;
	wait_for_no_local_builder(&ds, ns, db, &table, old_ix.index_id).await?;
	assert_no_index_build_artifacts(&ds, ns, db, &table, old_ix.index_id).await?;
	drop(guard);
	// The replacement's own build shares the injected conflict site, so the
	// retired builder is released alongside it. It must still write nothing.
	wait_for_finished_builder(&old_builder).await?;
	assert_no_index_build_artifacts(&ds, ns, db, &table, old_ix.index_id).await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	let (_, _, _, new_ix) = get_table_index(&ds, "user", "test").await?;
	assert_ne!(new_ix.index_id, old_ix.index_id);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_overwrite_cancel_preserves_previous_index() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', account = 'apple' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (_, _, _, old_ix) = get_table_index(&ds, "user", "test").await?;

	execute_cancelled_transaction(
		&ds,
		&session,
		"BEGIN; DEFINE INDEX OVERWRITE test ON user FIELDS account; CANCEL;",
	)
	.await?;

	let (_, _, _, current_ix) = get_table_index(&ds, "user", "test").await?;
	assert_eq!(current_ix.index_id, old_ix.index_id);
	assert_eq!(index_building_status(&ds, &session, "user", "test").await?, "ready");
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT * FROM user WITH INDEX test WHERE email = 'one@example.com'",
		1,
	)
	.await?;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_concurrent_cancel_cleans_uncommitted_build_artifacts() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;

	execute_cancelled_transaction(
		&ds,
		&session,
		"BEGIN; DEFINE INDEX test ON user FIELDS email CONCURRENTLY; CANCEL;",
	)
	.await?;

	execute_all(&ds, &session, "DEFINE INDEX test ON user FIELDS email CONCURRENTLY").await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;
	let (ns, db, table, current_ix) = get_table_index(&ds, "user", "test").await?;
	let cancelled_ix = previous_index_id(current_ix.index_id);
	assert_no_index_build_artifacts(&ds, ns, db, &table, cancelled_ix).await?;
	Ok(())
}

/// The rollback cleanup deletes an uncommitted build's durable state from its
/// own transaction, so it must not return until the builder task has stopped
/// writing: a builder write ordered after that delete re-creates state for a
/// build the catalog never referenced, and nothing collects it.
///
/// `define_index_concurrent_cancel_cleans_uncommitted_build_artifacts` covers
/// the same guarantee end to end but only fails when the race lands. Here the
/// builder is held at an injected conflict site, so a signal-only abort leaves
/// it demonstrably unfinished at the point the deletes would run.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_index_and_wait_returns_only_after_the_builder_task_exits() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;

	let _guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let building = local_builder_for_key(&ds, ns, db, &table, ix.index_id)
		.await?
		.expect("local builder should be running");
	assert!(!building.is_finished(), "the paused builder should still be running");

	ds.index_builder()
		.remove_index_and_wait(ns, db, &table, ix.index_id, build_abort_deadline(Instant::now()))
		.await;

	assert!(
		building.is_finished(),
		"remove_index_and_wait returned while the builder task was still writing"
	);
	assert!(
		local_builder_for_key(&ds, ns, db, &table, ix.index_id).await?.is_none(),
		"the aborted builder must be gone from the local task map"
	);
	Ok(())
}

/// The wait budget belongs to the whole transaction-close drain, so a cleanup
/// that runs after the budget is spent must not wait again: N indexes in one
/// rolled-back schema transaction cost one budget, not N.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn remove_index_and_wait_stops_waiting_once_the_drain_budget_is_spent() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			",
	)
	.await?;

	let _guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let building = local_builder_for_key(&ds, ns, db, &table, ix.index_id)
		.await?
		.expect("local builder should be running");

	// A deadline in the past stands for an earlier cleanup in the same drain
	// having consumed the budget.
	let started = Instant::now();
	ds.index_builder().remove_index_and_wait(ns, db, &table, ix.index_id, Instant::now()).await;
	assert!(
		started.elapsed() < Duration::from_secs(2),
		"a spent budget must not buy another wait (took {:?})",
		started.elapsed()
	);
	assert!(
		building.aborted.load(Ordering::Relaxed),
		"the builder must still be signalled to abort when the wait is skipped"
	);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_blocking_cancel_cleans_uncommitted_build_artifacts() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;

	execute_cancelled_transaction(
		&ds,
		&session,
		"BEGIN; DEFINE INDEX test ON user FIELDS email; CANCEL;",
	)
	.await?;

	execute_all(&ds, &session, "DEFINE INDEX test ON user FIELDS email").await?;
	let (ns, db, table, current_ix) = get_table_index(&ds, "user", "test").await?;
	let cancelled_ix = previous_index_id(current_ix.index_id);
	assert_no_index_build_artifacts(&ds, ns, db, &table, cancelled_ix).await?;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_overwrite_cancel_cleans_new_build_artifacts() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', account = 'apple' RETURN NONE;
			CREATE user:two SET email = 'two@example.com', account = 'banana' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, old_ix) = get_table_index(&ds, "user", "test").await?;

	execute_cancelled_transaction(
		&ds,
		&session,
		"BEGIN; DEFINE INDEX OVERWRITE test ON user FIELDS account CONCURRENTLY; CANCEL;",
	)
	.await?;
	let (_, _, _, preserved_ix) = get_table_index(&ds, "user", "test").await?;
	assert_eq!(preserved_ix.index_id, old_ix.index_id);

	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE test ON user FIELDS account CONCURRENTLY")
		.await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;
	let (_, _, _, current_ix) = get_table_index(&ds, "user", "test").await?;
	let cancelled_ix = previous_index_id(current_ix.index_id);
	assert_ne!(cancelled_ix, old_ix.index_id);
	assert_no_index_build_artifacts(&ds, ns, db, &table, cancelled_ix).await?;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn define_index_overwrite_commits_new_id_and_retires_old_lookup() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', account = 'apple' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, old_ix) = get_table_index(&ds, "user", "test").await?;
	let old_ikb = IndexKeyBase::new(ns, db, table.clone(), old_ix.index_id);
	seed_durable_queue_generation(&ds, &old_ikb, 1).await?;
	assert!(durable_build_state_exists(&ds, &old_ikb).await?);
	assert_eq!(durable_queue_all_generations_count(&ds, &old_ikb).await?, 3);

	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE test ON user FIELDS account").await?;

	let (_, _, _, current_ix) = get_table_index(&ds, "user", "test").await?;
	assert_ne!(current_ix.index_id, old_ix.index_id);
	expect_indexed_query_len(
		&ds,
		&session,
		"SELECT * FROM user WITH INDEX test WHERE account = 'apple'",
		1,
	)
	.await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let old_lookup = catch!(tx, tx.get_tb_index_by_id(ns, db, &table, old_ix.index_id, None).await);
	let current_lookup =
		catch!(tx, tx.get_tb_index_by_id(ns, db, &table, current_ix.index_id, None).await);
	tx.cancel().await?;
	assert!(old_lookup.is_none(), "old index id lookup should be retired");
	assert!(current_lookup.is_some(), "current index id lookup should remain");
	assert!(
		!durable_build_state_exists(&ds, &old_ikb).await?,
		"old durable build state should be retired"
	);
	assert!(
		durable_build_state_exists(&ds, &IndexKeyBase::new(ns, db, table, current_ix.index_id))
			.await?,
		"current durable build state should remain"
	);
	assert_eq!(
		durable_queue_all_generations_count(&ds, &old_ikb).await?,
		0,
		"old durable queue keys should be retired"
	);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn missing_durable_state_filters_retired_cached_index_definitions() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', account = 'apple', name = 'one', age = 1 RETURN NONE;
			DEFINE INDEX online ON user FIELDS email;
			DEFINE INDEX building ON user FIELDS account;
			DEFINE INDEX legacy ON user FIELDS name;
			DEFINE INDEX stale ON user FIELDS age;
			",
	)
	.await?;
	let (ns, db, table, online_ix) = get_table_index(&ds, "user", "online").await?;
	let (_, _, _, building_ix) = get_table_index(&ds, "user", "building").await?;
	let (_, _, _, legacy_ix) = get_table_index(&ds, "user", "legacy").await?;
	let (_, _, _, stale_ix) = get_table_index(&ds, "user", "stale").await?;
	let online_ikb = IndexKeyBase::new(ns, db, table.clone(), online_ix.index_id);
	let building_ikb = IndexKeyBase::new(ns, db, table.clone(), building_ix.index_id);
	let legacy_ikb = IndexKeyBase::new(ns, db, table.clone(), legacy_ix.index_id);

	// Exercise every branch in one cached catalog slice: durable online stays
	// visible, durable building is hidden, missing current state is legacy-ready,
	// and missing retired state is filtered.
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&online_ikb.new_bs_key(),
		&durable_build_state_for_phase(IndexBuildPhase::Online, 1, None),
	)
	.await?;
	tx.set_key(
		&building_ikb.new_bs_key(),
		&durable_build_state_for_phase(IndexBuildPhase::Building, 1, Some(ds.id())),
	)
	.await?;
	tx.del_key(&legacy_ikb.new_bs_key()).await?;
	tx.commit().await?;

	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE stale ON user FIELDS score").await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let indexes: Arc<[IndexDefinition]> = Arc::from(vec![
		online_ix.as_ref().clone(),
		building_ix.as_ref().clone(),
		legacy_ix.as_ref().clone(),
		stale_ix.as_ref().clone(),
	]);
	let filtered = filter_online_indexes(&tx, ns, db, indexes).await?;
	tx.cancel().await?;
	let names: Vec<_> = filtered.iter().map(|ix| ix.name.as_str()).collect();
	assert_eq!(
		names,
		vec!["online", "legacy"],
		"only durable-online and catalog-reachable legacy indexes should remain"
	);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn filter_online_indexes_batches_durable_state_reads() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', account = 'apple', name = 'one' RETURN NONE;
			DEFINE INDEX one ON user FIELDS email;
			DEFINE INDEX two ON user FIELDS account;
			DEFINE INDEX three ON user FIELDS name;
			",
	)
	.await?;
	let (ns, db, table, one_ix) = get_table_index(&ds, "user", "one").await?;
	let (_, _, _, two_ix) = get_table_index(&ds, "user", "two").await?;
	let (_, _, _, three_ix) = get_table_index(&ds, "user", "three").await?;

	let tx = ds.transaction(TransactionType::Write).await?;
	for ix in [&one_ix, &two_ix, &three_ix] {
		let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
		tx.set_key(
			&ikb.new_bs_key(),
			&durable_build_state_for_phase(IndexBuildPhase::Online, 1, None),
		)
		.await?;
	}
	tx.commit().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let indexes: Arc<[IndexDefinition]> = Arc::from(vec![
		one_ix.as_ref().clone(),
		two_ix.as_ref().clone(),
		three_ix.as_ref().clone(),
	]);
	let filtered = filter_online_indexes(&tx, ns, db, indexes).await?;
	let metrics = tx.metrics_snapshot_for_test();
	tx.cancel().await?;
	assert_eq!(filtered.len(), 3);
	assert_eq!(metrics.ops_get, 1, "durable build states should be read with one batched get");
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn consume_skips_retired_cached_index_definition() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', account = 'apple' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (_, _, table, old_ix) = get_table_index(&ds, "user", "test").await?;

	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE test ON user FIELDS account").await?;

	let tx = Arc::new(ds.transaction(TransactionType::Write).await?);
	let db_def = tx.get_db_by_name("test", "test", None).await?.expect("database should exist");
	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let rid = RecordId {
		table,
		key: RecordIdKey::from("two".to_owned()),
	};
	let result = ctx
		.get_index_builder()
		.expect("index builder should be present")
		.consume(
			db_def.as_ref(),
			&ctx,
			&old_ix,
			IndexMutation {
				old_values: None,
				new_values: None,
				rid: &rid,
				count_cond_match: None,
			},
		)
		.await?;
	tx.cancel().await?;

	assert!(matches!(result, ConsumeResult::Retired));
	Ok(())
}

/// The same blind spot as the cached-admission recheck, on the path a bulk
/// write takes for its *first* record.
///
/// First-use admission also has to tell a legacy index with no `!bs` apart from
/// one the catalog has retired, and asking the write's own transaction cannot
/// do it: that transaction read the definition before the removal and answers
/// from its cache. Getting it wrong here is the worse direction — the write
/// would index normally into a retired index's prefix, leaving entries under an
/// id the catalog no longer names.
#[tokio::test(flavor = "multi_thread")]
async fn consume_skips_an_index_retired_after_the_write_began() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;

	// The write's transaction, opened and its catalog cache warmed before the
	// removal commits.
	let tx = Arc::new(ds.transaction(TransactionType::Write).await?);
	let db_def = tx.get_db_by_name("test", "test", None).await?.expect("database should exist");
	assert!(
		tx.get_tb_index(ns, db, &table, ix.name.as_str(), None).await?.is_some(),
		"the write's transaction must have the definition cached for this to mean anything"
	);

	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let rid = RecordId {
		table,
		key: RecordIdKey::from("two".to_owned()),
	};
	let result = ctx
		.get_index_builder()
		.expect("index builder should be present")
		.consume(
			db_def.as_ref(),
			&ctx,
			&ix,
			IndexMutation {
				old_values: None,
				new_values: Some(vec![Value::from("two@example.com")]),
				rid: &rid,
				count_cond_match: None,
			},
		)
		.await?;
	tx.cancel().await?;

	assert!(
		matches!(result, ConsumeResult::Retired),
		"a write must not index into an index retired after it began"
	);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn compaction_write_fence_rejects_committed_index_removal() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let generation = durable_build_state(&ds, &ikb).await?.generation;

	let tx = ds.transaction(TransactionType::Read).await?;
	let table_def = catch!(tx, tx.get_tb(ns, db, &table, None).await).expect("table should exist");
	let mut ctx = ds.setup_ctx()?;
	let tx = Arc::new(tx);
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let build = Building::new(
		&ctx,
		ds.transaction_factory().clone(),
		ds.setup_options(&session),
		table_def.table_id,
		Arc::clone(&ix),
		Arc::new(IndexKey::new(ns, db, &table, ix.index_id)),
	)?;
	build.build_generation.store(generation, Ordering::Release);
	tx.cancel().await?;

	let tx = ds.transaction(TransactionType::Write).await?;
	assert!(build.compaction_write_still_owns_index(&tx, generation).await?);
	tx.cancel().await?;

	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	let tx = ds.transaction(TransactionType::Write).await?;
	assert!(
		!build.compaction_write_still_owns_index(&tx, generation).await?,
		"retired indexes must not accept post-online builder compaction writes"
	);
	tx.cancel().await?;
	Ok(())
}

/// Passing the compaction fence has to bind at commit, not just at the check.
///
/// Compaction runs after `Online`, so it has no ownership heartbeat to
/// compare-and-swap the way a build batch does — its guard is a read. A
/// retirement that commits between that read and the apply's commit has to
/// take the apply with it; otherwise the compaction writes index data under a
/// prefix the catalog no longer names, and only the queued reclaim would sweep
/// it, if it had not already finished.
#[cfg(feature = "kv-rocksdb")]
#[tokio::test(flavor = "multi_thread")]
async fn compaction_write_fence_conflicts_with_a_retirement_that_commits_after_it() -> Result<()> {
	let dir = TempDir::new()?;
	let ds = Datastore::builder()
		.without_maintenance_tasks()
		.build_with_path(&format!("rocksdb://{}", dir.path().to_string_lossy()))
		.await?;
	let session = Session::owner().with_ns("test").with_db("test");
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.ensure_ns_db(None, "test", "test").await?;
	tx.commit().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let state = durable_build_state(&ds, &ikb).await?;

	let tx = ds.transaction(TransactionType::Write).await?;
	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::new(ds.transaction(TransactionType::Read).await?));
	let ctx = ctx.freeze();
	let table_def = ds
		.transaction(TransactionType::Read)
		.await?
		.get_tb(ns, db, &table, None)
		.await?
		.expect("table should exist");
	let build = Building::new(
		&ctx,
		ds.transaction_factory().clone(),
		ds.setup_options(&session),
		table_def.table_id,
		Arc::clone(&ix),
		Arc::new(IndexKey::new(ns, db, &table, ix.index_id)),
	)?;

	// The compaction transaction passes its guard while the index is live.
	assert!(build.compaction_write_still_owns_index(&tx, state.generation).await?);

	// The retirement commits in between, as it may on any node.
	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	// The apply this guard was standing in for. It writes index data, not the
	// guarded key: a write to `!bs` itself would conflict on the write alone
	// and prove nothing about whether the guard's read is tracked.
	let mut entry = IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(&table),
		ix: ix.index_id,
	}
	.range()?
	.start()
	.to_vec();
	entry.push(0x01);
	tx.set(Key::from(entry), vec![0x01]).await?;
	let err = tx.commit().await.expect_err("the retirement must take the compaction with it");
	assert!(is_retryable_transaction_conflict(&err), "expected a retryable conflict, got: {err}");
	let _ = tx.cancel().await;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn compaction_write_fence_rejects_previous_rebuild_generation() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let generation = durable_build_state(&ds, &ikb).await?.generation;

	let tx = ds.transaction(TransactionType::Read).await?;
	let table_def = catch!(tx, tx.get_tb(ns, db, &table, None).await).expect("table should exist");
	let mut ctx = ds.setup_ctx()?;
	let tx = Arc::new(tx);
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let build = Building::new(
		&ctx,
		ds.transaction_factory().clone(),
		ds.setup_options(&session),
		table_def.table_id,
		Arc::clone(&ix),
		Arc::new(IndexKey::new(ns, db, &table, ix.index_id)),
	)?;
	build.build_generation.store(generation, Ordering::Release);
	tx.cancel().await?;

	let tx = ds.transaction(TransactionType::Write).await?;
	assert!(build.compaction_write_still_owns_index(&tx, generation).await?);
	tx.cancel().await?;

	execute_all(&ds, &session, "REBUILD INDEX test ON user").await?;

	let (_, _, _, rebuilt_ix) = get_table_index(&ds, "user", "test").await?;
	assert_eq!(rebuilt_ix.index_id, ix.index_id);
	assert_eq!(rebuilt_ix.name, ix.name);

	let rebuilt_state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(rebuilt_state.generation, generation.saturating_add(1));
	assert_eq!(rebuilt_state.phase, IndexBuildPhase::Online);

	let tx = ds.transaction(TransactionType::Write).await?;
	assert!(
		!build.compaction_write_still_owns_index(&tx, generation).await?,
		"previous build generations must not accept post-online compaction writes after rebuild"
	);
	assert!(
		build.compaction_write_still_owns_index(&tx, rebuilt_state.generation).await?,
		"current online generation should still accept post-online compaction writes"
	);
	tx.cancel().await?;
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn fresh_build_cleans_stale_durable_queue_generations() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'one@example.com' RETURN NONE;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	for generation in 1..=3 {
		seed_durable_queue_generation(&ds, &ikb, generation).await?;
	}
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 3,
			phase: IndexBuildPhase::Error,
			owner: None,
			next_ticket: 4,
			initial_complete: false,
			updated_at: Utc::now(),
			owner_heartbeat_at: None,
			error: Some("previous build failed".to_string()),
			report_status: Some(IndexBuildReportStatus::Error),
			initial: None,
			updated: None,
			pending: None,
			initial_cursor: None,
		},
	)
	.await?;
	tx.commit().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let table_def = tx.get_tb(ns, db, &table, None).await?.expect("table should exist");
	let mut ctx = ds.setup_ctx()?;
	let tx = Arc::new(tx);
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let build = Building::new(
		&ctx,
		ds.transaction_factory().clone(),
		ds.setup_options(&session),
		table_def.table_id,
		Arc::clone(&ix),
		Arc::new(IndexKey::new(ns, db, &table, ix.index_id)),
	)?;
	let acquired = build.acquire_build_state().await?.expect("fresh build should start");
	tx.cancel().await?;

	assert_eq!(acquired.generation, 4);
	for generation in 1..=3 {
		assert_eq!(durable_queue_generation_count(&ds, &ikb, generation).await?, 0);
	}
	Ok(())
}

async fn count_query_value(ds: &Datastore, session: &Session, sql: &str) -> Result<i64> {
	let mut results = ds.execute(sql, session, None).await?;
	let value = results.remove(0).result?;
	let surrealdb_types::Value::Array(rows) = value else {
		anyhow::bail!("count query returned non-array value: {value:?}");
	};
	let Some(surrealdb_types::Value::Object(row)) = rows.first() else {
		anyhow::bail!("count query returned no object row: {rows:?}");
	};
	let Some(surrealdb_types::Value::Number(count)) = row.get("count") else {
		anyhow::bail!("count query returned no numeric count field: {row:?}");
	};
	count.to_int().ok_or_else(|| anyhow::anyhow!("count value is not an integer"))
}

async fn count_index_value(ds: &Datastore, session: &Session) -> Result<i64> {
	count_query_value(ds, session, "SELECT count() FROM user GROUP ALL").await
}

/// Number of undrained count-index delta entries for one index.
#[cfg(feature = "kv-mem")]
async fn count_index_delta_keys(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: IndexId,
) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let rng = IndexCountPrefix {
		ns,
		db,
		tb: Cow::Borrowed(table),
		ix,
	}
	.range()?;
	let keys = catch!(tx, tx.keys(rng, u32::MAX, 0, None).await);
	tx.cancel().await?;
	Ok(keys.len())
}

/// Put this index's durable build state into `Building` under an owner that is
/// not this node, so the compaction task sees a build in flight elsewhere in
/// the cluster. `heartbeat_age` back-dates the owner's heartbeat.
#[cfg(feature = "kv-mem")]
async fn claim_build_for_a_remote_owner(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	heartbeat_age: chrono::Duration,
) -> Result<()> {
	let mut state = durable_build_state(ds, ikb).await?;
	state.phase = IndexBuildPhase::Building;
	state.owner = Some(Uuid::now_v7());
	state.owner_heartbeat_at = Some(Utc::now() - heartbeat_age);
	set_durable_build_state(ds, ikb, state).await
}

/// Number of HNSW pending entries queued for one index.
#[cfg(feature = "kv-mem")]
async fn count_hnsw_pendings(ds: &Datastore, ikb: &IndexKeyBase) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let count = catch!(tx, tx.count(ikb.new_hr_range()?, None).await);
	tx.cancel().await?;
	Ok(count)
}

async fn wait_for_retry_conflict(
	site: RetryableConflictSite,
	node_id: uuid::Uuid,
	initial_count: usize,
) -> Result<()> {
	timeout(Duration::from_secs(10), async {
		loop {
			if retryable_conflict_count(site, node_id) < initial_count {
				return Ok(());
			}
			sleep(Duration::from_millis(10)).await;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out waiting for injected retry conflict"))?
}

async fn wait_for_retry_conflict_count_to_stabilize(
	site: RetryableConflictSite,
	node_id: uuid::Uuid,
) -> Result<usize> {
	timeout(Duration::from_secs(10), async {
		let mut previous = retryable_conflict_count(site, node_id);
		loop {
			sleep(Duration::from_millis(250)).await;
			let current = retryable_conflict_count(site, node_id);
			if current == previous {
				return Ok(current);
			}
			previous = current;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out waiting for retry conflict count to stabilize"))?
}

#[tokio::test(flavor = "multi_thread")]
async fn count_index_duplicate_initial_build_does_not_overcount() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:1 RETURN NONE;
			CREATE user:2 RETURN NONE;
			",
	)
	.await?;

	let table_name = TableName::from("user");
	let (ns_id, db_id, table_id, index) = {
		let tx = ds.transaction(TransactionType::Write).await?;
		let ns = tx.get_ns_by_name("test", None).await?.expect("namespace should exist");
		let db = tx.get_db_by_name("test", "test", None).await?.expect("database should exist");
		let table = tx
			.get_tb(ns.namespace_id, db.database_id, &table_name, None)
			.await?
			.expect("table should exist");
		let index = IndexDefinition {
			index_id: IndexId(1),
			name: "test".into(),
			table_name: table_name.clone(),
			cols: Vec::new(),
			index: Index::Count(None),
			count_cond: None,
			comment: None,
			prepare_remove: false,
			format_version: 1,
		};
		tx.put_tb_index(ns.namespace_id, db.database_id, &table_name, &index).await?;
		tx.commit().await?;
		(ns.namespace_id, db.database_id, table.table_id, Arc::new(index))
	};

	let index_key = Arc::new(IndexKey::new(ns_id, db_id, &table_name, index.index_id));
	let opt = ds.setup_options(&session);
	let mut ctx = ds.setup_ctx()?;
	let read_tx = Arc::new(ds.transaction(TransactionType::Read).await?);
	ctx.set_transaction(Arc::clone(&read_tx));
	let ctx = ctx.freeze();
	let build_a = Building::new(
		&ctx,
		ds.transaction_factory().clone(),
		opt.clone(),
		table_id,
		Arc::clone(&index),
		Arc::clone(&index_key),
	)?;
	let build_b =
		Building::new(&ctx, ds.transaction_factory().clone(), opt, table_id, index, index_key)?;
	read_tx.cancel().await?;

	let (a, b) = tokio::join!(build_a.run(), build_b.run());
	a?;
	b?;

	assert_eq!(count_index_value(&ds, &session).await?, 2);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn count_index_initial_scan_preserves_where_count_baseline() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET status = 'active' RETURN NONE;
			CREATE user:two SET status = 'active' RETURN NONE;
			CREATE user:three SET status = 'inactive' RETURN NONE;
			DEFINE INDEX test ON user COUNT WHERE status = 'active' CONCURRENTLY;
			",
	)
	.await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	assert_eq!(
		count_query_value(
			&ds,
			&session,
			"SELECT count() FROM user WHERE status = 'active' GROUP ALL"
		)
		.await?,
		2
	);
	execute_all_retrying_conflicts(
		&ds,
		&session,
		"CREATE user:four SET status = 'active' RETURN NONE",
	)
	.await?;
	assert_eq!(
		count_query_value(
			&ds,
			&session,
			"SELECT count() FROM user WHERE status = 'active' GROUP ALL"
		)
		.await?,
		3
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn count_index_delete_before_scan_preserves_plain_count_baseline() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one RETURN NONE;
			",
	)
	.await?;

	let guard =
		start_index_build_paused(&ds, &session, "DEFINE INDEX test ON user COUNT CONCURRENTLY")
			.await?;
	execute_all_retrying_conflicts(&ds, &session, "DELETE user:one RETURN NONE").await?;
	drop(guard);
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	execute_all_retrying_conflicts(&ds, &session, "CREATE user:two RETURN NONE").await?;
	assert_eq!(count_index_value(&ds, &session).await?, 1);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn count_index_delete_before_scan_preserves_where_count_baseline() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET status = 'active' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user COUNT WHERE status = 'active' CONCURRENTLY",
	)
	.await?;
	execute_all_retrying_conflicts(&ds, &session, "DELETE user:one RETURN NONE").await?;
	drop(guard);
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	execute_all_retrying_conflicts(
		&ds,
		&session,
		"CREATE user:two SET status = 'active' RETURN NONE",
	)
	.await?;
	assert_eq!(
		count_query_value(
			&ds,
			&session,
			"SELECT count() FROM user WHERE status = 'active' GROUP ALL"
		)
		.await?,
		1
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn count_index_updates_before_scan_preserve_where_count_baseline() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET status = 'active' RETURN NONE;
			CREATE user:two SET status = 'inactive' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX test ON user COUNT WHERE status = 'active' CONCURRENTLY",
	)
	.await?;
	execute_all_retrying_conflicts(
		&ds,
		&session,
		"
			UPDATE user:one SET status = 'inactive' RETURN NONE;
			UPDATE user:two SET status = 'active' RETURN NONE;
			",
	)
	.await?;
	drop(guard);
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	assert_eq!(
		count_query_value(
			&ds,
			&session,
			"SELECT count() FROM user WHERE status = 'active' GROUP ALL"
		)
		.await?,
		1
	);
	execute_all_retrying_conflicts(
		&ds,
		&session,
		"CREATE user:three SET status = 'active' RETURN NONE",
	)
	.await?;
	assert_eq!(
		count_query_value(
			&ds,
			&session,
			"SELECT count() FROM user WHERE status = 'active' GROUP ALL"
		)
		.await?,
		2
	);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn takeover_preserves_durable_progress_counts() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let cases = [(IndexBuildPhase::Building, 2, 42, 7), (IndexBuildPhase::Closing, 3, 84, 11)];

	for (phase, generation, initial, updated) in cases {
		let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
		let tx = ds.transaction(TransactionType::Write).await?;
		tx.set_key(
			&ikb.new_bs_key(),
			&IndexBuildState {
				generation,
				phase,
				owner: Some(uuid::Uuid::new_v4()),
				next_ticket: 0,
				initial_complete: true,
				updated_at: expired,
				owner_heartbeat_at: Some(expired),
				error: None,
				report_status: Some(IndexBuildReportStatus::Indexing),
				initial: Some(initial),
				updated: Some(updated),
				pending: Some(5),
				initial_cursor: None,
			},
		)
		.await?;
		tx.commit().await?;

		let build = new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?;
		let acquired = build
			.acquire_build_state()
			.await?
			.expect("expired build state should be available for takeover");
		build.run_acquired(acquired).await?;

		let state = durable_build_state(&ds, &ikb).await?;
		assert_eq!(state.phase, IndexBuildPhase::Online);
		assert_eq!(state.initial, Some(initial));
		assert_eq!(state.updated, Some(updated));
		assert_eq!(state.pending, Some(0));

		let building = index_building_json(&ds, &session, "user", "test").await?;
		assert_eq!(building.get("status").and_then(|status| status.as_str()), Some("ready"));
		assert_eq!(building.get("initial").and_then(|initial| initial.as_u64()), Some(initial));
		assert_eq!(building.get("updated").and_then(|updated| updated.as_u64()), Some(updated));
	}

	Ok(())
}

/// A takeover of a `Building` generation whose owner committed at least one
/// initial-scan batch resumes the scan right after the persisted checkpoint
/// instead of wiping the partial index data and rescanning from the start.
#[tokio::test(flavor = "multi_thread")]
async fn takeover_resumes_initial_scan_from_checkpoint() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:a SET email = 'a@example.com' RETURN NONE;
			CREATE user:b SET email = 'b@example.com' RETURN NONE;
			CREATE user:c SET email = 'c@example.com' RETURN NONE;
			CREATE user:d SET email = 'd@example.com' RETURN NONE;
			CREATE user:e SET email = 'e@example.com' RETURN NONE;
			CREATE user:f SET email = 'f@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Simulate an owner that crashed mid-scan: wipe the index data the
	// blocking build produced (the crashed generation never reached these
	// records) and strand a `Building` generation whose durable checkpoint
	// says the scan committed through `user:c`.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_prefix_key(&IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(&table),
		ix: ix.index_id,
	})
	.await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: Some(42),
			updated: None,
			pending: None,
			initial_cursor: Some(RecordIdKey::from("c".to_string())),
		},
	)
	.await?;
	tx.commit().await?;

	let build = new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("expired build state should be available for takeover");
	build.run_acquired(acquired).await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	// Resumed counters continue from the persisted value instead of being
	// reset by a wipe-and-rescan: 42 checkpointed + `user:d..f` scanned.
	assert_eq!(state.initial, Some(45));
	assert_eq!(state.initial_cursor, None);

	// Only the records after the checkpoint were indexed. A wipe-and-rescan
	// would have re-indexed all six records.
	assert_eq!(
		index_prefix_key_count(&ds, ns, db, &table, ix.index_id).await?,
		3,
		"only user:d..f should be indexed after a resumed scan"
	);

	Ok(())
}

/// A COUNT-index takeover resumes the baseline scan from the checkpoint: the
/// primary-appending catch-up cursor continues from the same position, so
/// records at or before the checkpoint are not baselined a second time.
#[tokio::test(flavor = "multi_thread")]
async fn takeover_resumes_count_initial_scan_from_checkpoint() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:a RETURN NONE;
			CREATE user:b RETURN NONE;
			CREATE user:c RETURN NONE;
			CREATE user:d RETURN NONE;
			CREATE user:e RETURN NONE;
			CREATE user:f RETURN NONE;
			DEFINE INDEX test ON user COUNT;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Same crash simulation as above, for a COUNT index: no index data
	// survives for the stranded generation, and the checkpoint says the
	// baseline scan committed through `user:c`.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_prefix_key(&IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(&table),
		ix: ix.index_id,
	})
	.await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: Some(4),
			updated: None,
			pending: None,
			initial_cursor: Some(RecordIdKey::from("c".to_string())),
		},
	)
	.await?;
	tx.commit().await?;

	let build = new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("expired build state should be available for takeover");
	build.run_acquired(acquired).await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	// 4 checkpointed + `user:d..f` scanned; a wipe-and-rescan would report 6.
	assert_eq!(state.initial, Some(7));
	assert_eq!(state.initial_cursor, None);
	// The index-backed count only includes the post-checkpoint baseline.
	assert_eq!(count_index_value(&ds, &session).await?, 3);

	Ok(())
}

/// A COUNT build that dies right after the tail-pass transaction commits must
/// already be durably `initial_complete`: the tail baselines `!bp` old states
/// without deleting the markers, so a takeover that re-entered the tail pass
/// would count the same records twice before publishing `Online`.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn count_tail_crash_after_commit_does_not_double_count_on_takeover() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one RETURN NONE;
			CREATE user:two RETURN NONE;
			CREATE user:three RETURN NONE;
			CREATE user:four RETURN NONE;
			CREATE user:five RETURN NONE;
			CREATE user:six RETURN NONE;
			DEFINE INDEX test ON user COUNT;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Strand a `Building` generation with an expired owner and no checkpoint,
	// wiping the data of the completed blocking build, so the takeover below
	// runs a full initial scan including the tail pass.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_prefix_key(&IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(&table),
		ix: ix.index_id,
	})
	.await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: None,
			updated: None,
			pending: None,
			initial_cursor: None,
		},
	)
	.await?;
	tx.commit().await?;

	// Queue a delete for the record that sorts last (`two`), so its `!bp` old
	// state is only reachable by the tail pass (`through = None`), not by any
	// batch-scoped catch-up committed with a checkpoint.
	execute_all_retrying_conflicts(&ds, &session, "DELETE user:two RETURN NONE").await?;

	// First takeover: run the full scan and kill the builder right after the
	// tail-pass transaction commits.
	let _release_guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexCountTailCommitted,
		ds.id(),
	);
	let build = new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("expired build state should be available for takeover");
	let err = build
		.run_acquired(acquired)
		.await
		.expect_err("builder should die at the injected crash site");
	assert!(
		err.to_string().contains("injected non-retryable error"),
		"unexpected builder error: {err}"
	);

	// The tail-pass transaction committed, so the scan must already be
	// durably complete: 5 live records + the queued old state of `user:two`.
	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Building);
	assert!(state.initial_complete, "tail commit must complete the scan atomically");
	assert_eq!(state.initial, Some(6));
	assert_eq!(state.initial_cursor, None);

	// Expire the dead builder's heartbeat so a second takeover can proceed.
	let tx = ds.transaction(TransactionType::Write).await?;
	let mut state = tx
		.get_key(&ikb.new_bs_key(), None)
		.await?
		.ok_or_else(|| anyhow::anyhow!("durable build state should exist"))?;
	state.updated_at = expired;
	state.owner_heartbeat_at = Some(expired);
	tx.set_key(&ikb.new_bs_key(), &state).await?;
	tx.commit().await?;

	// Second takeover: the scan is complete, so it only replays the queued
	// delete and publishes `Online` without re-running the tail pass.
	let build = new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("expired build state should be available for takeover");
	build.run_acquired(acquired).await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	// Baseline 6 (5 live + deleted `user:two` old state) minus the replayed
	// delete: a double-counted tail would report 6 here instead.
	assert_eq!(count_index_value(&ds, &session).await?, 5);

	Ok(())
}

/// An abort observed mid-batch must not commit that batch: the checkpoint
/// would otherwise cover records that were never indexed, and a takeover
/// would resume past them, leaving silent gaps in the index. The abort
/// timing is racy by nature, so the assertion is timing-invariant: however
/// far the durable state says the scan got, the index must contain exactly
/// the records up to that point.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn abort_mid_scan_never_checkpoints_unindexed_records() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE |user:1..=1000| SET email = 'user@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Strand a resumable generation: no index data, checkpoint at `user:1`,
	// so the takeover scans `user:2..1000` without a cleanup phase.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_prefix_key(&IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(&table),
		ix: ix.index_id,
	})
	.await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: Some(1),
			updated: None,
			pending: None,
			initial_cursor: Some(RecordIdKey::from(1i64)),
		},
	)
	.await?;
	tx.commit().await?;

	let building =
		Arc::new(new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?);
	let acquired = building
		.acquire_build_state()
		.await?
		.expect("expired build state should be available for takeover");
	// Abort concurrently with the scan; any landing point must be safe.
	let aborter = Arc::clone(&building);
	tokio::spawn(async move {
		sleep(Duration::from_millis(3)).await;
		aborter.abort();
	});
	building.run_acquired(acquired).await?;

	// However far the durable state says the scan got, exactly that many
	// records must be indexed. `user:1` is covered by the seeded checkpoint
	// but carries no index key, hence the `- 1`.
	let state = durable_build_state(&ds, &ikb).await?;
	let expected = if state.initial_complete {
		999
	} else {
		match &state.initial_cursor {
			Some(RecordIdKey::Number(n)) => usize::try_from(n - 1).unwrap(),
			other => panic!("unexpected checkpoint cursor after abort: {other:?}"),
		}
	};
	assert_eq!(
		index_prefix_key_count(&ds, ns, db, &table, ix.index_id).await?,
		expected,
		"durable checkpoint must cover exactly the indexed records (state: {state:?})"
	);

	Ok(())
}

/// Direct coverage for the COUNT tail-pass abort re-check: an abort observed
/// during the tail pass must cancel the transaction rather than commit the
/// completion marker over baselines the truncated pass never wrote. The
/// abort timing is racy by nature, so the assertion is timing-invariant:
/// while the scan is durably incomplete the committed baseline (signed sum
/// of the count-delta entries) must be zero, and once the completion marker
/// exists the sum must equal the number of still-queued deletes — every
/// replayed delete decrements the sum and consumes its `!bg` entry in the
/// same transaction, so a partial tail under a completion marker breaks the
/// equality at any replay progress.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn abort_during_count_tail_pass_never_commits_partial_baselines() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE |user:1..=3000| RETURN NONE;
			DEFINE INDEX test ON user COUNT;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Strand a resumable generation whose checkpoint claims `user:1..=500`
	// were scanned, with no surviving index data.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_prefix_key(&IdxRoot {
		ns,
		db,
		tb: Cow::Borrowed(&table),
		ix: ix.index_id,
	})
	.await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: Some(500),
			updated: None,
			pending: None,
			initial_cursor: Some(RecordIdKey::from(500i64)),
		},
	)
	.await?;
	tx.commit().await?;

	// Queue deletes for every record past the checkpoint while the build is
	// in `Building`. No live record remains after `user:500`, so their `!bp`
	// old states are reachable only by the tail pass (`through = None`).
	execute_all_retrying_conflicts(&ds, &session, "DELETE user:501..=3000 RETURN NONE").await?;

	let building =
		Arc::new(new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?);
	let acquired = building
		.acquire_build_state()
		.await?
		.expect("expired build state should be available for takeover");
	// Abort concurrently: the empty live scan reaches the tail pass almost
	// immediately, so this usually lands mid-tail; any landing point must
	// satisfy the invariant below.
	let aborter = Arc::clone(&building);
	tokio::spawn(async move {
		sleep(Duration::from_millis(4)).await;
		aborter.abort();
	});
	building.run_acquired(acquired).await?;

	// Ground truth: committed baseline = signed sum of count-delta entries;
	// outstanding replay work = queued `!bg` mutations still present.
	let tx = ds.transaction(TransactionType::Read).await?;
	let rng = IndexCountPrefix {
		ns,
		db,
		tb: Cow::Borrowed(&table),
		ix: ix.index_id,
	}
	.range()?;
	let keys = catch!(tx, tx.keys(rng, u32::MAX, 0, None).await);
	let mut sum: i64 = 0;
	for key in &keys {
		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
		};
	}
	let pending = catch!(tx, tx.keys(ikb.new_bg_range(2)?, u32::MAX, 0, None).await).len();
	tx.cancel().await?;

	let state = durable_build_state(&ds, &ikb).await?;
	if state.initial_complete {
		// The completion marker commits atomically with the full tail, so
		// the baseline sum tracks the unreplayed queue exactly.
		assert_eq!(
			sum,
			i64::try_from(pending).unwrap(),
			"completion marker committed over a partial tail (state: {state:?})"
		);
	} else {
		// The aborted tail pass must not have committed anything.
		assert_eq!(sum, 0, "partial tail baselines committed (state: {state:?})");
		assert_eq!(pending, 2500, "queued deletes must be untouched (state: {state:?})");
	}

	Ok(())
}

/// The periodic resume scan adopts a `CONCURRENTLY` build that a crashed owner
/// left stranded (expired lease, `Building` phase) and drives it to `Online`,
/// and is a no-op once the index is healthy again.
#[tokio::test(flavor = "multi_thread")]
async fn resume_scan_adopts_stalled_concurrent_build() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Simulate an ungraceful crash mid-build: a `Building` generation whose owner
	// lease has expired and whose initial scan never completed.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: Some(0),
			updated: None,
			pending: None,
			initial_cursor: None,
		},
	)
	.await?;
	tx.commit().await?;

	// The scan should adopt exactly this build.
	let resumed = ds
		.resume_stalled_index_builds(
			Duration::from_secs(30),
			tokio_util::sync::CancellationToken::new(),
		)
		.await?;
	assert_eq!(resumed, 1, "scan should adopt the stalled build");

	// The adopted build runs asynchronously; wait for it to reach `Online`.
	let deadline = Instant::now() + Duration::from_secs(30);
	loop {
		let state = durable_build_state(&ds, &ikb).await?;
		if state.phase == IndexBuildPhase::Online {
			break;
		}
		assert!(
			Instant::now() < deadline,
			"resumed build did not complete; phase={:?}",
			state.phase
		);
		sleep(Duration::from_millis(100)).await;
	}
	let building = index_building_json(&ds, &session, "user", "test").await?;
	assert_eq!(building.get("status").and_then(|status| status.as_str()), Some("ready"));

	// With the index healthy again, a second scan must be a no-op.
	let resumed_again = ds
		.resume_stalled_index_builds(
			Duration::from_secs(30),
			tokio_util::sync::CancellationToken::new(),
		)
		.await?;
	assert_eq!(resumed_again, 0, "healthy index must not be re-adopted");

	Ok(())
}

/// End-to-end check of the *periodic* path: an interval-driven loop calling
/// `resume_stalled_index_builds` (exactly what the engine's maintenance
/// scheduler runs) must, on its own, adopt a stalled `CONCURRENTLY` build and drive it to
/// `Online` — no manual `REBUILD`/`REMOVE`. This pins the behaviour in CI
/// independently of a live server harness.
#[tokio::test(flavor = "multi_thread")]
async fn periodic_task_resumes_stalled_build() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Strand a `Building` generation with an expired owner lease, as an
	// ungraceful crash mid-build would leave it.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: Some(0),
			updated: None,
			pending: None,
			initial_cursor: None,
		},
	)
	.await?;
	tx.commit().await?;

	// Spawn the periodic resume loop, mirroring the engine's maintenance
	// scheduler: a timer that calls `resume_stalled_index_builds` until cancelled.
	let canceller = tokio_util::sync::CancellationToken::new();
	let task = {
		let ds = Arc::clone(&ds);
		let canceller = canceller.clone();
		tokio::spawn(async move {
			let tick = Duration::from_millis(200);
			let mut interval = tokio::time::interval(tick);
			loop {
				tokio::select! {
					biased;
					_ = canceller.cancelled() => break,
					_ = interval.tick() => {
						let _ = ds.resume_stalled_index_builds(tick, canceller.clone()).await;
					}
				}
			}
		})
	};

	// The loop should adopt the stalled build and drive it to `Online` on its own.
	let deadline = Instant::now() + Duration::from_secs(30);
	loop {
		if durable_build_state(&ds, &ikb).await?.phase == IndexBuildPhase::Online {
			break;
		}
		assert!(
			Instant::now() < deadline,
			"the periodic resume task did not adopt and complete the stalled build"
		);
		sleep(Duration::from_millis(100)).await;
	}
	canceller.cancel();
	let _ = task.await;

	let building = index_building_json(&ds, &session, "user", "test").await?;
	assert_eq!(building.get("status").and_then(|status| status.as_str()), Some("ready"));

	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_writer_admission_does_not_extend_builder_lease() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:seed SET email = 'seed@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds_a, "user", "test").await?;
	let generation = 2;
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let stale_state = IndexBuildState {
		generation,
		phase: IndexBuildPhase::Building,
		owner: Some(uuid::Uuid::new_v4()),
		next_ticket: 0,
		initial_complete: false,
		updated_at: expired,
		owner_heartbeat_at: Some(expired),
		error: None,
		report_status: Some(IndexBuildReportStatus::Indexing),
		initial: None,
		updated: None,
		pending: None,
		initial_cursor: None,
	};
	let tx = ds_a.transaction(TransactionType::Write).await?;
	tx.set_key(&ikb.new_bs_key(), &stale_state).await?;
	tx.commit().await?;

	for record in ["one", "two", "three"] {
		execute_all(
			&ds_b,
			&session,
			&format!("CREATE user:{record} SET email = '{record}@example.com' RETURN NONE"),
		)
		.await?;
	}

	let tx = ds_a.transaction(TransactionType::Read).await?;
	let admitted_state: IndexBuildState =
		tx.get_key(&ikb.new_bs_key(), None).await?.expect("build state should exist");
	tx.cancel().await?;
	assert_eq!(admitted_state.next_ticket, 3);
	assert_eq!(admitted_state.owner_heartbeat_at, Some(expired));
	assert!(
		admitted_state.updated_at > expired,
		"writer admission should update durable state metadata"
	);
	assert!(
		build_owner_expired(&admitted_state, Utc::now()),
		"writer admission must not refresh builder lease"
	);

	let tx = ds_a.transaction(TransactionType::Read).await?;
	let table_def = tx.get_tb(ns, db, &table, None).await?.expect("table should exist");
	let mut ctx = ds_a.setup_ctx()?;
	let tx = Arc::new(tx);
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let build = Building::new(
		&ctx,
		ds_a.transaction_factory().clone(),
		ds_a.setup_options(&session),
		table_def.table_id,
		Arc::clone(&ix),
		Arc::new(IndexKey::new(ns, db, &table, ix.index_id)),
	)?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("expired builder lease should be available for takeover");
	tx.cancel().await?;

	assert_eq!(acquired.generation, generation);
	assert_eq!(acquired.phase, IndexBuildPhase::Building);
	assert!(!acquired.initial_complete);

	let tx = ds_a.transaction(TransactionType::Read).await?;
	let taken_over: IndexBuildState =
		tx.get_key(&ikb.new_bs_key(), None).await?.expect("build state should exist");
	tx.cancel().await?;
	assert_eq!(taken_over.owner, Some(build.owner));
	assert!(taken_over.owner_heartbeat_at.is_some());
	assert!(!build_owner_expired(&taken_over, Utc::now()));
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn writer_admission_batches_reservations_per_user_transaction() -> Result<()> {
	// A single user transaction that performs many indexed mutations against
	// the same index must allocate exactly one durable `!br` reservation —
	// one ticket per (user-txn, index) — and write a distinct `!bg` entry
	// per mutation. The earlier protocol allocated one `!br` per mutation,
	// which the per-user-txn reservation cache eliminates.
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:seed SET email = 'seed@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let generation = 2;
	let building = IndexBuildState {
		generation,
		phase: IndexBuildPhase::Building,
		owner: Some(ds.id()),
		next_ticket: 0,
		initial_complete: false,
		updated_at: Utc::now(),
		owner_heartbeat_at: Some(Utc::now()),
		error: None,
		report_status: Some(IndexBuildReportStatus::Indexing),
		initial: None,
		updated: None,
		pending: None,
		initial_cursor: None,
	};
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(&ikb.new_bs_key(), &building).await?;
	// Give the generation its ticket counter, so admission takes the same path
	// production does. Without it the fabricated state looks like a generation
	// predating the counter and the whole test runs on the legacy fallback.
	tx.set_key(&ikb.new_bt_key(generation), &0u64).await?;
	tx.commit().await?;

	// Single user transaction that inserts five records — all go through
	// admission. The reservation cache should make the second through fifth
	// inserts skip the !br write and reuse the cached ticket.
	execute_all(
		&ds,
		&session,
		"
			BEGIN;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			CREATE user:three SET email = 'three@example.com' RETURN NONE;
			CREATE user:four SET email = 'four@example.com' RETURN NONE;
			CREATE user:five SET email = 'five@example.com' RETURN NONE;
			COMMIT;
			",
	)
	.await?;

	// Exactly one ticket should have been allocated by the whole user
	// transaction's batch.
	assert_eq!(
		durable_ticket_counter(&ds, &ikb, generation).await?,
		Some(1),
		"a single user transaction must consume exactly one durable ticket regardless of mutation count"
	);

	// Five `!bg` entries, one per mutation, all sharing the same `(generation, ticket)`.
	let tx = ds.transaction(TransactionType::Read).await?;
	let bg_keys = tx.keys(ikb.new_bg_range(generation)?, u32::MAX, 0, None).await?;
	let bp_keys = tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?;
	let br_keys = tx.keys(ikb.new_br_range(generation)?, u32::MAX, 0, None).await?;
	tx.cancel().await?;
	assert_eq!(
		bg_keys.len(),
		5,
		"each indexed mutation should produce one `!bg` entry; got {} for 5 mutations",
		bg_keys.len()
	);
	assert_eq!(
		bp_keys.len(),
		5,
		"first-time-per-record admission during initial scan should produce one `!bp` per record; got {} for 5 records",
		bp_keys.len()
	);
	assert!(
		br_keys.is_empty(),
		"the user transaction's close-time release should have removed the `!br`; found {} stranded reservation keys",
		br_keys.len()
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn writer_admission_cancelled_batch_clears_durable_queue() -> Result<()> {
	// If a user transaction's batched mutations roll back, no `!bg` may
	// survive and the single `!br` allocated for the batch must be released
	// from the close path.
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let generation = 2;
	let building = IndexBuildState {
		generation,
		phase: IndexBuildPhase::Building,
		owner: Some(ds.id()),
		next_ticket: 0,
		initial_complete: false,
		updated_at: Utc::now(),
		owner_heartbeat_at: Some(Utc::now()),
		error: None,
		report_status: Some(IndexBuildReportStatus::Indexing),
		initial: None,
		updated: None,
		pending: None,
		initial_cursor: None,
	};
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(&ikb.new_bs_key(), &building).await?;
	// Give the generation its ticket counter, so admission takes the same path
	// production does rather than the legacy `next_ticket` fallback.
	tx.set_key(&ikb.new_bt_key(generation), &0u64).await?;
	tx.commit().await?;

	// Single user transaction that issues three indexed mutations then
	// cancels. The reservation is still allocated (the !br commit is in its
	// own short transaction), but the cancel path must release it.
	execute_cancelled_transaction(
		&ds,
		&session,
		"
			BEGIN;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			CREATE user:three SET email = 'three@example.com' RETURN NONE;
			CANCEL;
			",
	)
	.await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let bg_keys = tx.keys(ikb.new_bg_range(generation)?, u32::MAX, 0, None).await?;
	let bp_keys = tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?;
	let br_keys = tx.keys(ikb.new_br_range(generation)?, u32::MAX, 0, None).await?;
	tx.cancel().await?;
	assert_eq!(
		durable_ticket_counter(&ds, &ikb, generation).await?,
		Some(1),
		"cancelled batch still consumes one durable ticket"
	);
	assert!(
		bg_keys.is_empty(),
		"cancelled user transaction must not leave any `!bg` entries; found {}",
		bg_keys.len()
	);
	assert!(
		bp_keys.is_empty(),
		"cancelled user transaction must not leave any `!bp` entries; found {}",
		bp_keys.len()
	);
	assert!(
		br_keys.is_empty(),
		"cancel path must release the durable reservation; found {} stranded `!br` keys",
		br_keys.len()
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn cached_index_build_reservation_remove_clears_entry() -> Result<()> {
	// `consume()` drops the cached reservation after the first-use fence
	// returns `IndexNormally`, so subsequent mutations re-enter reservation
	// and rediscover the online state instead of writing orphan `!bg` against
	// a released ticket. Verify the underlying mechanic: insert, lookup hits
	// with an incrementing `mutation_seq`, remove, lookup misses.
	let (ds, _) = new_index_test_ds().await?;
	let tx = ds.transaction(TransactionType::Write).await?;
	let key = CachedIndexBuildReservationKey {
		ns: NamespaceId(1),
		db: DatabaseId(1),
		tb: TableName::from("user"),
		ix: IndexId(1),
	};

	assert!(
		tx.lookup_cached_index_build_reservation(&key).await?.is_none(),
		"empty cache should miss"
	);

	let first = tx.insert_cached_index_build_reservation(key.clone(), 1, 7, false).await;
	match first {
		CachedIndexBuildReservationLookup::FirstUse {
			generation,
			ticket,
			mutation_seq,
			initial_complete,
		} => {
			assert_eq!(generation, 1);
			assert_eq!(ticket, 7);
			assert_eq!(mutation_seq, 0);
			assert!(!initial_complete);
		}
		CachedIndexBuildReservationLookup::Reused {
			..
		} => panic!("first admission must return FirstUse, not Reused"),
	}

	let reused = tx
		.lookup_cached_index_build_reservation(&key)
		.await?
		.expect("cache should hit after insert");
	match reused {
		CachedIndexBuildReservationLookup::Reused {
			generation,
			ticket,
			mutation_seq,
			initial_complete,
		} => {
			assert_eq!(generation, 1);
			assert_eq!(ticket, 7);
			assert_eq!(mutation_seq, 1, "second mutation should consume seq 1");
			assert!(!initial_complete);
		}
		CachedIndexBuildReservationLookup::FirstUse {
			..
		} => panic!("subsequent admission must return Reused, not FirstUse"),
	}

	tx.remove_cached_index_build_reservation(&key).await;
	assert!(
		tx.lookup_cached_index_build_reservation(&key).await?.is_none(),
		"cache should miss after removal so subsequent mutations re-enter reservation"
	);

	tx.cancel().await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn cached_index_build_reservation_lookup_errors_on_seq_overflow() -> Result<()> {
	// Saturating-add would silently overwrite `!bg(gen, ticket, u32::MAX)`
	// after `mutation_seq` clamps; the cache must instead surface an error
	// so the user transaction is aborted before any data loss occurs.
	let (ds, _) = new_index_test_ds().await?;
	let tx = ds.transaction(TransactionType::Write).await?;
	let key = CachedIndexBuildReservationKey {
		ns: NamespaceId(1),
		db: DatabaseId(1),
		tb: TableName::from("user"),
		ix: IndexId(1),
	};

	tx.seed_cached_index_build_reservation_for_test(key.clone(), 1, 0, false, u32::MAX).await;
	let err = tx
		.lookup_cached_index_build_reservation(&key)
		.await
		.expect_err("lookup at u32::MAX must surface an overflow error");
	let downcast = err
		.downcast_ref::<DatastoreError>()
		.expect("error should be the typed IndexingBuildingCancelled");
	assert!(
		matches!(downcast, DatastoreError::IndexingBuildingCancelled { .. }),
		"expected IndexingBuildingCancelled, got {downcast:?}"
	);
	assert!(
		err.to_string().contains("mutation sequence overflowed"),
		"unexpected error message: {err}"
	);

	tx.cancel().await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn recheck_cached_admission_rejects_mid_transaction_state_changes() -> Result<()> {
	// Cache reuse must revalidate the live `!bs` state every time. A
	// generation rotation, an Online transition, or vanished build state
	// must abort the user transaction with `IndexingBuildingCancelled` —
	// otherwise later mutations write `!bg` against a generation no builder
	// will replay. An Error transition keeps queueing instead: the errored
	// generation's queue is wiped and the table rescanned on `REBUILD`.
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Matching state — recheck succeeds.
	seed_build_state(&ds, &ikb, IndexBuildPhase::Building, 1).await?;
	let outcome = run_recheck_cached_admission(&ds, ns, db, &ikb, ix.as_ref(), 1)
		.await?
		.expect("recheck on matching Building state should succeed");
	assert!(matches!(outcome, CachedAdmission::Valid));

	// Closing is still queueable.
	seed_build_state(&ds, &ikb, IndexBuildPhase::Closing, 1).await?;
	let outcome = run_recheck_cached_admission(&ds, ns, db, &ikb, ix.as_ref(), 1)
		.await?
		.expect("recheck on matching Closing state should succeed");
	assert!(matches!(outcome, CachedAdmission::Valid));

	// Generation rotation — recheck aborts.
	seed_build_state(&ds, &ikb, IndexBuildPhase::Building, 2).await?;
	let err = run_recheck_cached_admission(&ds, ns, db, &ikb, ix.as_ref(), 1)
		.await?
		.expect_err("generation mismatch must abort cached admission");
	assert!(err.to_string().contains("generation"), "unexpected error: {err}");

	// Online phase — cached writers cannot trust the cached ticket.
	seed_build_state(&ds, &ikb, IndexBuildPhase::Online, 1).await?;
	let err = run_recheck_cached_admission(&ds, ns, db, &ikb, ix.as_ref(), 1)
		.await?
		.expect_err("online phase must abort cached admission");
	assert!(err.to_string().contains("online"), "unexpected error: {err}");

	// Error phase — keeps queueing: a failed build must not abort user
	// writes. The queued mutations die with the errored generation's wipe
	// and the records are rescanned by the recovering `REBUILD INDEX`.
	seed_build_state(&ds, &ikb, IndexBuildPhase::Error, 1).await?;
	let outcome = run_recheck_cached_admission(&ds, ns, db, &ikb, ix.as_ref(), 1)
		.await?
		.expect("recheck on matching Error state should keep queueing");
	assert!(matches!(outcome, CachedAdmission::Valid));

	// Missing state under a definition the catalog still carries — recheck
	// aborts: a build vanished under a live index, which this cannot repair.
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_key(&ikb.new_bs_key()).await?;
	tx.commit().await?;
	let err = run_recheck_cached_admission(&ds, ns, db, &ikb, ix.as_ref(), 1)
		.await?
		.expect_err("missing build state must abort cached admission");
	assert!(err.to_string().contains("no longer exists"), "unexpected error: {err}");

	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn recheck_cached_admission_skips_a_retired_index_instead_of_failing_the_write() -> Result<()>
{
	// A bulk write admits once and reuses the reservation for every later
	// record. If `REMOVE INDEX` commits in between, the recheck finds no `!bs`
	// — the same observation as a build that vanished under a live definition,
	// but the opposite conclusion: there is no index left to maintain, so the
	// write skips it rather than failing. First-use admission has always split
	// on the catalog this way; the cached path must agree.
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	seed_build_state(&ds, &ikb, IndexBuildPhase::Building, 1).await?;

	// The definition a mid-transaction write still holds is read before the
	// removal, which is exactly the stale handle the recheck has to judge.
	let cached_ix = Arc::clone(&ix);
	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	let outcome = run_recheck_cached_admission(&ds, ns, db, &ikb, cached_ix.as_ref(), 1)
		.await?
		.expect("a retired index must not fail the write that was mid-transaction");
	assert!(
		matches!(outcome, CachedAdmission::Retired),
		"the recheck must report the index retired so the mutation skips it"
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
async fn seed_build_state(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	phase: IndexBuildPhase,
	generation: u64,
) -> Result<()> {
	let mut state = IndexBuildState {
		generation,
		phase,
		owner: Some(ds.id()),
		next_ticket: 0,
		initial_complete: false,
		updated_at: Utc::now(),
		owner_heartbeat_at: Some(Utc::now()),
		error: None,
		report_status: Some(report_status_from_phase(phase)),
		initial: None,
		updated: None,
		pending: None,
		initial_cursor: None,
	};
	if matches!(phase, IndexBuildPhase::Error) {
		state.error = Some("seeded test failure".to_string());
		state.report_status = Some(IndexBuildReportStatus::Error);
	}
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(&ikb.new_bs_key(), &state).await?;
	tx.commit().await?;
	Ok(())
}

/// The retirement the recheck has to notice is one that commits *during* the
/// write, so the write's own transaction cannot be what reports it.
///
/// A bulk write reads the index definition once and reuses it, which leaves
/// that definition in its transaction cache. A catalog read issued through
/// that transaction afterwards is answered from the cache and still sees the
/// index, whatever the backend's snapshot rules — so the recheck has to ask the
/// same fresh transaction that observed `!bs` missing.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn recheck_cached_admission_sees_a_retirement_the_user_transaction_cannot() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	seed_build_state(&ds, &ikb, IndexBuildPhase::Building, 1).await?;

	// The write's transaction, opened and its catalog cache warmed before the
	// removal — exactly what record 1 of a bulk write leaves behind.
	let tx = Arc::new(ds.transaction(TransactionType::Read).await?);
	assert!(
		tx.get_tb_index(ns, db, &table, ix.name.as_str(), None).await?.is_some(),
		"the write's transaction must have the definition cached for this to mean anything"
	);

	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::clone(&tx));
	let frozen = ctx.freeze();
	let builder = frozen
		.get_index_builder()
		.expect("index builder should be available on the configured Datastore")
		.clone();
	let outcome = builder.recheck_cached_admission(&frozen, &ikb, ix.as_ref(), ns, db, 1).await;
	tx.cancel().await?;

	assert!(
		matches!(outcome?, CachedAdmission::Retired),
		"a retirement that commits mid-write must still be reported as retired"
	);
	Ok(())
}

/// A replacement is only a retirement for a write that can already see it.
///
/// `DEFINE INDEX OVERWRITE` retires the old id and defines a new one under the
/// same name. A write whose own view still carries the replaced definition
/// cannot reach the new index — it is not in that write's snapshot — so
/// skipping the mutation would let the replacement publish without this
/// record. Failing is what sends the write back to retry against the
/// definition that now exists.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn recheck_cached_admission_rejects_a_replacement_the_write_cannot_see() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'one@example.com', account = 'apple' RETURN NONE;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, old_ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), old_ix.index_id);
	seed_build_state(&ds, &ikb, IndexBuildPhase::Building, 1).await?;

	// The write's transaction, opened and its catalog cache warmed before the
	// replacement commits, so its view still carries the old definition.
	let tx = Arc::new(ds.transaction(TransactionType::Read).await?);
	assert!(
		tx.get_tb_index(ns, db, &table, old_ix.name.as_str(), None).await?.is_some(),
		"the write's transaction must have the old definition cached"
	);

	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE test ON user FIELDS account").await?;
	let (_, _, _, new_ix) = get_table_index(&ds, "user", "test").await?;
	assert_ne!(new_ix.index_id, old_ix.index_id, "the overwrite must allocate a fresh id");

	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::clone(&tx));
	let frozen = ctx.freeze();
	let builder = frozen
		.get_index_builder()
		.expect("index builder should be available on the configured Datastore")
		.clone();
	let outcome = builder.recheck_cached_admission(&frozen, &ikb, old_ix.as_ref(), ns, db, 1).await;
	tx.cancel().await?;

	let err = outcome.expect_err("a replacement the write cannot see must abort it");
	assert!(err.to_string().contains("replaced"), "unexpected error: {err}");
	Ok(())
}

#[cfg(feature = "kv-mem")]
async fn run_recheck_cached_admission(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	ikb: &IndexKeyBase,
	ix: &IndexDefinition,
	cached_generation: u64,
) -> Result<Result<CachedAdmission>> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let mut ctx = ds.setup_ctx()?;
	let tx = Arc::new(tx);
	ctx.set_transaction(Arc::clone(&tx));
	let frozen = ctx.freeze();
	let builder = frozen
		.get_index_builder()
		.expect("index builder should be available on the configured Datastore")
		.clone();
	let result =
		builder.recheck_cached_admission(&frozen, ikb, ix, ns, db, cached_generation).await;
	tx.cancel().await?;
	Ok(result)
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn acquire_build_state_waits_for_prior_generation_reservations() -> Result<()> {
	// A new-generation takeover on one node must drain in-flight `!br` from
	// writers on *other* nodes before wiping the stale queues. Without the
	// drain, the wipe destroys the writer's anchor and the new build's
	// initial scan can start before the writer's commit, missing main-table
	// writes. (The takeover installs the new generation before draining, so
	// no further old-generation reservations can appear while it waits.)
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds_a, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Seed `!bs` in `Error` so takeover takes the new-generation branch.
	let errored = IndexBuildState {
		generation: 1,
		phase: IndexBuildPhase::Error,
		owner: Some(ds_a.id()),
		next_ticket: 1,
		initial_complete: false,
		updated_at: Utc::now(),
		owner_heartbeat_at: Some(Utc::now()),
		error: Some("seeded test failure".to_string()),
		report_status: Some(IndexBuildReportStatus::Error),
		initial: None,
		updated: None,
		pending: None,
		initial_cursor: None,
	};
	let seed_tx = ds_a.transaction(TransactionType::Write).await?;
	seed_tx.set_key(&ikb.new_bs_key(), &errored).await?;
	let reservation = IndexBuildReservation {
		node: ds_a.id(),
		expires_at: Utc::now() + chrono::Duration::seconds(BUILD_RESERVATION_TTL_SECS),
	};
	let br_key = ikb.new_br_key(1, 0);
	seed_tx.set_key(&br_key, &reservation).await?;
	seed_tx.commit().await?;

	// `ds_b` is the would-be takeover node. Its drain must block on ds_a's
	// live `!br`.
	let building = new_building_for_index(&ds_b, &session, ns, db, &table, Arc::clone(&ix)).await?;
	let timeout_result =
		timeout(Duration::from_millis(200), building.wait_for_prior_generation_reservations(2))
			.await;
	assert!(
		timeout_result.is_err(),
		"drain must block while another node's !br is alive in durable membership"
	);

	// Simulate ds_a's deferred release firing (e.g. user transaction committed
	// or cancelled, removing its `!br`).
	let release_tx = ds_a.transaction(TransactionType::Write).await?;
	release_tx.del_key(&br_key).await?;
	release_tx.commit().await?;

	// Drain should now return promptly.
	timeout(Duration::from_secs(5), building.wait_for_prior_generation_reservations(2))
		.await
		.expect("drain must complete after !br is removed")?;

	// Takeover proceeds with generation 2 and leaves no stranded reservations.
	let acquired =
		building.acquire_build_state().await?.expect("takeover should succeed after drain");
	assert_eq!(acquired.generation, 2);
	assert!(matches!(acquired.phase, IndexBuildPhase::Building));
	let tx = ds_a.transaction(TransactionType::Read).await?;
	let br_keys = tx.keys(ikb.new_br_all_generations_range()?, u32::MAX, 0, None).await?;
	tx.cancel().await?;
	assert!(br_keys.is_empty(), "no `!br` should remain after a clean takeover");
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn drain_prior_generation_reservations_cleans_dead_writers() -> Result<()> {
	// Stale `!br` from a writer whose node is no longer in durable membership
	// must be cleaned up by the drain. Otherwise a single crashed writer
	// would block every new-generation takeover until its TTL expired and
	// some other mechanism removed the entry.
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				DEFINE INDEX test ON user FIELDS email;
				",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Reservation owned by a node id that was never registered in durable
	// membership (`reservation_node_is_live` returns false) and whose TTL is
	// already past.
	let stale_node = Uuid::new_v4();
	let reservation = IndexBuildReservation {
		node: stale_node,
		expires_at: Utc::now() - chrono::Duration::seconds(1),
	};
	let br_key = ikb.new_br_key(1, 0);
	let seed_tx = ds.transaction(TransactionType::Write).await?;
	seed_tx.set_key(&br_key, &reservation).await?;
	seed_tx.commit().await?;

	let building = new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?;
	timeout(Duration::from_secs(5), building.wait_for_prior_generation_reservations(2))
		.await
		.expect("drain must complete promptly for a dead writer's reservation")?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let br_keys = tx.keys(ikb.new_br_all_generations_range()?, u32::MAX, 0, None).await?;
	tx.cancel().await?;
	assert!(br_keys.is_empty(), "stale `!br` from a dead writer should have been removed");
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_info_uses_durable_state_from_second_node() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	assert_eq!(index_building_status(&ds_b, &session, "user", "test").await?, "cleaning");

	drop(guard);
	wait_for_index_ready(&ds_a, &session, "user", "test").await?;
	assert_eq!(index_building_status(&ds_b, &session, "user", "test").await?, "ready");
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_blocking_rebuild_waits_for_remote_owner() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let session_rebuild = session.clone();
	let rebuild = tokio::spawn(async move {
		execute_all(&ds_b, &session_rebuild, "REBUILD INDEX test ON user").await
	});

	sleep(Duration::from_millis(200)).await;
	assert!(
		!rebuild.is_finished(),
		"blocking REBUILD INDEX returned while the remote build was still paused"
	);

	drop(guard);
	timeout(Duration::from_secs(10), rebuild)
		.await
		.map_err(|_| anyhow::anyhow!("timed out waiting for blocking rebuild"))???;
	assert_eq!(index_building_status(&ds_a, &session, "user", "test").await?, "ready");
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_blocking_rebuild_takes_over_expired_remote_owner() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds_a, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	let generation = 2;
	let now = Utc::now();
	let tx = ds_a.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation,
			phase: IndexBuildPhase::Building,
			owner: Some(uuid::Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: true,
			updated_at: now,
			owner_heartbeat_at: Some(now),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: Some(1),
			updated: Some(0),
			pending: Some(0),
			initial_cursor: None,
		},
	)
	.await?;
	tx.commit().await?;

	let session_rebuild = session.clone();
	let rebuild = tokio::spawn(async move {
		execute_all(&ds_b, &session_rebuild, "REBUILD INDEX test ON user").await
	});
	sleep(Duration::from_millis(200)).await;
	assert!(
		!rebuild.is_finished(),
		"blocking REBUILD INDEX returned before the remote lease expired"
	);

	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds_a.transaction(TransactionType::Write).await?;
	let mut state: IndexBuildState =
		tx.get_key(&ikb.new_bs_key(), None).await?.expect("build state should exist");
	state.updated_at = expired;
	state.owner_heartbeat_at = Some(expired);
	tx.set_key(&ikb.new_bs_key(), &state).await?;
	tx.commit().await?;

	timeout(Duration::from_secs(10), rebuild)
		.await
		.map_err(|_| anyhow::anyhow!("timed out waiting for takeover rebuild"))???;
	let state = durable_build_state(&ds_a, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	assert_eq!(state.generation, generation);
	assert_eq!(state.owner, None);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_info_reports_durable_error_from_second_node() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET account = 'apple', email = 'test@surrealdb.com' RETURN NONE;
			CREATE user:two SET account = 'apple', email = 'test@surrealdb.com' RETURN NONE;
			",
	)
	.await?;
	execute_all(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS account, email UNIQUE CONCURRENTLY",
	)
	.await?;

	let building = timeout(Duration::from_secs(10), async {
		loop {
			let building = index_building_json(&ds_b, &session, "user", "test").await?;
			if building.get("status").and_then(|status| status.as_str()) == Some("error") {
				return Ok::<_, anyhow::Error>(building);
			}
			sleep(Duration::from_millis(20)).await;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out waiting for durable index build error"))??;

	assert_eq!(building.get("status").and_then(|status| status.as_str()), Some("error"));
	let error_reason = building
		.get("error")
		.and_then(|error| error.as_str())
		.ok_or_else(|| anyhow::anyhow!("index info did not include building.error: {building}"))?;
	assert!(
		error_reason.contains("already contains"),
		"unexpected durable index build error: {building}"
	);
	// A failed build must not block user writes on any node: the mutation is
	// admitted (queued under the errored generation, to be wiped and
	// rescanned by a recovering `REBUILD INDEX`) and the statement succeeds.
	execute_all_retrying_conflicts(
		&ds_b,
		&session,
		"CREATE user:three SET account = 'tesla', email = 'three@surrealdb.com' RETURN NONE",
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_standard_index_replays_second_node_update() -> Result<()> {
	// Node A builds the index while node B updates the indexed field. Once
	// the build closes, only the new value should be present in the index.
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'old@example.com' RETURN NONE;
			CREATE user:two SET email = 'steady@example.com' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	execute_all_retrying_conflicts(
		&ds_b,
		&session,
		"UPDATE user:one SET email = 'new@example.com' RETURN NONE",
	)
	.await?;
	execute_all_retrying_conflicts(&ds_b, &session, "DELETE user:two RETURN NONE").await?;
	drop(guard);
	wait_for_index_ready(&ds_a, &session, "user", "test").await?;
	let building = index_building_json(&ds_a, &session, "user", "test").await?;
	assert_eq!(building.get("pending").and_then(|pending| pending.as_u64()), Some(0));
	let updated =
		building.get("updated").and_then(|updated| updated.as_u64()).ok_or_else(|| {
			anyhow::anyhow!("index info did not include building.updated: {building}")
		})?;
	assert!(
		updated >= 2,
		"expected queued update and delete to be replayed in index status: {building}"
	);

	assert_eq!(
		query_array_len(
			&ds_a,
			&session,
			"SELECT id FROM user WITH INDEX test WHERE email = 'new@example.com'"
		)
		.await?,
		1
	);
	assert_eq!(
		query_array_len(
			&ds_a,
			&session,
			"SELECT id FROM user WITH INDEX test WHERE email = 'old@example.com'"
		)
		.await?,
		0
	);
	assert_eq!(
		query_array_len(
			&ds_a,
			&session,
			"SELECT id FROM user WITH INDEX test WHERE email = 'steady@example.com'"
		)
		.await?,
		0
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_local_reservation_release_retries_conflict() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
				DEFINE TABLE user SCHEMALESS;
				CREATE user:one SET email = 'old@example.com' RETURN NONE;
				",
	)
	.await?;

	let build_guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let release_site = RetryableConflictSite::ConcurrentIndexReservationRelease;
	let writer_node = ds_b.id();
	let _release_guard = inject_retryable_conflict(release_site, writer_node);
	execute_all_retrying_conflicts(
		&ds_b,
		&session,
		"UPDATE user:one SET email = 'new@example.com' RETURN NONE",
	)
	.await?;
	assert_eq!(retryable_conflict_count(release_site, writer_node), 0);

	drop(build_guard);
	wait_for_index_ready(&ds_a, &session, "user", "test").await?;
	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'new@example.com'",
		1,
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn commit_failure_preserves_primary_error_when_reservation_cleanup_fails() -> Result<()> {
	let (ds, _) = new_index_test_ds().await?;
	let ikb = IndexKeyBase::new(NamespaceId(1), DatabaseId(1), TableName::from("user"), IndexId(1));
	let generation = 1;
	let ticket = 1;
	let reservation = IndexBuildReservation {
		node: ds.id(),
		expires_at: Utc::now() + chrono::Duration::seconds(BUILD_RESERVATION_TTL_SECS),
	};
	let br = ikb.new_br_key(generation, ticket);
	let br_key = br.encode_key()?;
	let br_val = reservation.kv_encode_value()?;

	let seed_tx = ds.transaction(TransactionType::Write).await?;
	seed_tx.set_key(&br, &reservation).await?;
	(*seed_tx).set("commit-conflict".as_bytes().into(), b"initial".as_slice()).await?;
	seed_tx.commit().await?;

	let user_tx = ds.transaction(TransactionType::Write).await?;
	(*user_tx).set("commit-conflict".as_bytes().into(), b"user-write".as_slice()).await?;
	user_tx
		.register_index_build_reservation_release(IndexBuildReservationRelease::new(
			ds.transaction_factory().clone(),
			ds.sequences().clone(),
			ds.id(),
			br_key,
			br_val,
		))
		.await;

	let conflicting_tx = ds.transaction(TransactionType::Write).await?;
	(*conflicting_tx)
		.set("commit-conflict".as_bytes().into(), b"conflicting-write".as_slice())
		.await?;
	conflicting_tx.commit().await?;

	let _release_guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexReservationRelease,
		ds.id(),
	);
	let err = user_tx
		.commit()
		.await
		.expect_err("commit conflict should remain visible when cleanup also fails");
	assert!(
		is_retryable_transaction_conflict(&err),
		"primary commit error was not preserved: {err}"
	);
	assert!(
		!err.to_string().contains("injected non-retryable error"),
		"cleanup error replaced primary commit error: {err}"
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn commit_failure_cleans_uncommitted_index_build_artifacts() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			",
	)
	.await?;
	let (ns, db, table) = get_table_ids(&ds, "user").await?;
	let ix = IndexId(42);
	seed_uncommitted_index_build_artifacts(&ds, ns, db, &table, ix).await?;

	let user_tx = ds.transaction(TransactionType::Write).await?;
	(*user_tx).set("commit-conflict".as_bytes().into(), b"user-write".as_slice()).await?;
	let ctx = ds.setup_ctx()?;
	let builder = ctx.get_index_builder().expect("index builder should exist").clone();
	user_tx
		.on_rollback(CleanUncommittedBuild::boxed(
			builder.clone(),
			builder.transaction_factory(),
			user_tx.sequences(),
			ns,
			db,
			table.clone(),
			ix,
		))
		.await;

	let conflicting_tx = ds.transaction(TransactionType::Write).await?;
	(*conflicting_tx)
		.set("commit-conflict".as_bytes().into(), b"conflicting-write".as_slice())
		.await?;
	conflicting_tx.commit().await?;

	let err = user_tx.commit().await.expect_err("commit conflict should remain visible");
	assert!(
		is_retryable_transaction_conflict(&err),
		"primary commit error was not preserved: {err}"
	);
	assert_no_index_build_artifacts(&ds, ns, db, &table, ix).await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn store_changes_failure_preserves_primary_error_when_cleanup_fails() -> Result<()> {
	let (ds, _) = new_index_test_ds().await?;
	let ikb = IndexKeyBase::new(NamespaceId(1), DatabaseId(1), TableName::from("user"), IndexId(1));
	let generation = 1;
	let ticket = 1;
	let reservation = IndexBuildReservation {
		node: ds.id(),
		expires_at: Utc::now() + chrono::Duration::seconds(BUILD_RESERVATION_TTL_SECS),
	};
	let br = ikb.new_br_key(generation, ticket);
	let br_key = br.encode_key()?;
	let br_val = reservation.kv_encode_value()?;

	let seed_tx = ds.transaction(TransactionType::Write).await?;
	seed_tx.set_key(&br, &reservation).await?;
	seed_tx.commit().await?;

	let user_tx = ds.transaction(TransactionType::Read).await?;
	let table = TableName::from("user");
	let record = RecordId {
		table: table.clone(),
		key: RecordIdKey::from("one".to_owned()),
	};
	let current: Value = "new@example.com".into();
	user_tx.changefeed_buffer_record_change(
		NamespaceId(1),
		DatabaseId(1),
		&table,
		&record,
		Record::new(Value::None).into_read_only(),
		Record::new(current).into_read_only(),
		false,
	);
	user_tx
		.register_index_build_reservation_release(IndexBuildReservationRelease::new(
			ds.transaction_factory().clone(),
			ds.sequences().clone(),
			ds.id(),
			br_key,
			br_val,
		))
		.await;

	let _release_guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexReservationRelease,
		ds.id(),
	);
	let err = user_tx
		.commit()
		.await
		.expect_err("store_changes failure should remain visible when cleanup also fails");
	assert!(
		matches!(storage_error(&err), Some(crate::kvs::Error::TransactionReadonly)),
		"primary store_changes error was not preserved: {err}"
	);
	assert!(
		!err.to_string().contains("injected non-retryable error"),
		"cleanup error replaced primary store_changes error: {err}"
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_committed_cleanup_failure_recovers_from_appending() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
					DEFINE TABLE user SCHEMALESS;
					CREATE user:one SET email = 'old@example.com' RETURN NONE;
					",
	)
	.await?;

	let build_guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let _release_guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexReservationRelease,
		ds_b.id(),
	);
	execute_all_retrying_conflicts(
		&ds_b,
		&session,
		"UPDATE user:one SET email = 'new@example.com' RETURN NONE",
	)
	.await?;

	drop(build_guard);
	wait_for_index_ready(&ds_a, &session, "user", "test").await?;
	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'new@example.com'",
		1,
	)
	.await?;
	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'old@example.com'",
		0,
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds_a, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	assert_eq!(durable_queue_all_generations_count(&ds_a, &ikb).await?, 0);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_writer_admission_honors_statement_timeout_while_closing() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
						DEFINE TABLE user SCHEMALESS;
						CREATE user:one SET email = 'old@example.com' RETURN NONE;
						DEFINE INDEX test ON user FIELDS email;
						",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds_a, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	set_durable_build_state(
		&ds_a,
		&ikb,
		durable_build_state_for_phase(IndexBuildPhase::Closing, 2, Some(ds_a.id())),
	)
	.await?;

	let started = Instant::now();
	let mut results = timeout(
		Duration::from_secs(5),
		ds_b.execute("UPDATE user:one SET email = 'new@example.com' TIMEOUT 50ms", &session, None),
	)
	.await
	.map_err(|_| anyhow::anyhow!("writer admission ignored the statement timeout"))??;
	let error = results
		.remove(0)
		.result
		.expect_err("write should time out while durable state is Closing")
		.to_string();

	assert!(
		started.elapsed() < Duration::from_secs(5),
		"write waited for an internal timeout instead of the statement timeout"
	);
	assert!(error.contains("exceeded the timeout: 50ms"), "unexpected timeout error: {error}");
	assert_eq!(durable_build_state(&ds_a, &ikb).await?.phase, IndexBuildPhase::Closing);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_writer_admission_waits_until_closing_online() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
						DEFINE TABLE user SCHEMALESS;
						CREATE user:one SET email = 'old@example.com' RETURN NONE;
						DEFINE INDEX test ON user FIELDS email;
						",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds_a, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	set_durable_build_state(
		&ds_a,
		&ikb,
		durable_build_state_for_phase(IndexBuildPhase::Closing, 2, Some(ds_a.id())),
	)
	.await?;

	let session_write = session.clone();
	let writer = tokio::spawn(async move {
		execute_all(
			&ds_b,
			&session_write,
			"UPDATE user:one SET email = 'new@example.com' RETURN NONE",
		)
		.await
	});
	sleep(Duration::from_millis(250)).await;
	assert!(!writer.is_finished(), "write returned before durable Closing became Online");

	set_durable_build_state(
		&ds_a,
		&ikb,
		durable_build_state_for_phase(IndexBuildPhase::Online, 2, None),
	)
	.await?;
	timeout(Duration::from_secs(10), writer)
		.await
		.map_err(|_| anyhow::anyhow!("timed out waiting for Closing admission write"))???;

	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'new@example.com'",
		1,
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_rolled_back_writer_releases_reservation_after_close() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
					DEFINE TABLE user SCHEMALESS;
					CREATE user:one SET email = 'old@example.com' RETURN NONE;
					",
	)
	.await?;

	let build_guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	execute_cancelled_transaction_retrying_conflicts(
		&ds_b,
		&session,
		"BEGIN; UPDATE user:one SET email = 'new@example.com'; CANCEL;",
	)
	.await?;

	drop(build_guard);
	wait_for_index_ready(&ds_a, &session, "user", "test").await?;
	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'old@example.com'",
		1,
	)
	.await?;
	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'new@example.com'",
		0,
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_admission_error_after_registration_releases_reservation() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
					DEFINE TABLE user SCHEMALESS;
					CREATE user:one SET email = 'old@example.com' RETURN NONE;
					",
	)
	.await?;

	let build_guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let _guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexAfterReservationRegistration,
		ds_b.id(),
	);
	let error = execute_error_text_retrying_conflicts(
		&ds_b,
		&session,
		"UPDATE user:one SET email = 'new@example.com' RETURN NONE",
	)
	.await?;
	assert!(error.contains("injected non-retryable error"), "unexpected error: {error}");

	drop(build_guard);
	wait_for_index_ready(&ds_a, &session, "user", "test").await?;
	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'old@example.com'",
		1,
	)
	.await?;
	expect_indexed_query_len(
		&ds_a,
		&session,
		"SELECT id FROM user WITH INDEX test WHERE email = 'new@example.com'",
		0,
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_rollback_reservation_cleanup_failure_marks_build_error() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
					DEFINE TABLE user SCHEMALESS;
					CREATE user:one SET email = 'old@example.com' RETURN NONE;
					",
	)
	.await?;

	let build_guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email CONCURRENTLY",
	)
	.await?;
	let _release_guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexReservationRelease,
		ds_b.id(),
	);
	let error = execute_error_text_retrying_conflicts(
		&ds_b,
		&session,
		"BEGIN; UPDATE user:one SET email = 'new@example.com'; CANCEL;",
	)
	.await?;
	assert!(
		error.contains("injected non-retryable error")
			|| error.contains("durable index-build reservation")
			|| error.contains("cancelled transaction"),
		"unexpected transaction error: {error}"
	);

	let building = index_building_json(&ds_a, &session, "user", "test").await?;
	assert_eq!(building.get("status").and_then(|status| status.as_str()), Some("error"));
	let reason = building.get("error").and_then(|error| error.as_str()).unwrap_or_default();
	assert!(
		reason.contains("Failed to release durable index-build reservation"),
		"unexpected durable error reason: {building}"
	);
	drop(build_guard);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_unique_index_replays_second_node_insert() -> Result<()> {
	// The queued insert must populate the unique index before the index is
	// marked ready, so a later duplicate is rejected by the online index.
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON user FIELDS email UNIQUE CONCURRENTLY",
	)
	.await?;
	execute_all_retrying_conflicts(
		&ds_b,
		&session,
		"CREATE user:queued SET email = 'queued@example.com' RETURN NONE",
	)
	.await?;
	drop(guard);
	wait_for_index_ready(&ds_a, &session, "user", "test").await?;

	assert_eq!(
		query_array_len(
			&ds_a,
			&session,
			"SELECT id FROM user WITH INDEX test WHERE email = 'queued@example.com'"
		)
		.await?,
		1
	);
	expect_statement_error(
		&ds_b,
		&session,
		"CREATE user:duplicate SET email = 'queued@example.com' RETURN NONE",
	)
	.await?;
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_fulltext_index_replays_second_node_update() -> Result<()> {
	// Full-text replay has to remove terms for the old value and add terms
	// for the new value written by the second node during the build.
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE ANALYZER simple TOKENIZERS blank FILTERS lowercase;
			DEFINE TABLE doc SCHEMALESS;
			CREATE doc:one SET text = 'old phrase' RETURN NONE;
			CREATE doc:two SET text = 'stable text' RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
		&ds_a,
		&session,
		"DEFINE INDEX test ON doc FIELDS text FULLTEXT ANALYZER simple BM25 HIGHLIGHTS CONCURRENTLY",
	)
	.await?;
	execute_all_retrying_conflicts(
		&ds_b,
		&session,
		"UPDATE doc:one SET text = 'queued phrase' RETURN NONE",
	)
	.await?;
	drop(guard);
	wait_for_index_ready(&ds_a, &session, "doc", "test").await?;
	let building = index_building_json(&ds_a, &session, "doc", "test").await?;
	assert_eq!(building.get("pending").and_then(|pending| pending.as_u64()), Some(0));
	let updated =
		building.get("updated").and_then(|updated| updated.as_u64()).ok_or_else(|| {
			anyhow::anyhow!("index info did not include building.updated: {building}")
		})?;
	assert!(
		updated >= 1,
		"expected queued full-text update to be replayed in index status: {building}"
	);

	assert_eq!(
		query_array_len(
			&ds_a,
			&session,
			"SELECT id FROM doc WITH INDEX test WHERE text @@ 'queued'"
		)
		.await?,
		1
	);
	assert_eq!(
		query_array_len(&ds_a, &session, "SELECT id FROM doc WITH INDEX test WHERE text @@ 'old'")
			.await?,
		0
	);
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn distributed_hnsw_index_replays_second_node_insert() -> Result<()> {
	// HNSW replay is append-only for this scenario: a vector inserted by the
	// second node while the build is paused must be searchable after ready.
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"
			DEFINE TABLE vec SCHEMALESS;
			CREATE vec:one SET vector = [0f, 0f] RETURN NONE;
			CREATE vec:two SET vector = [20f, 20f] RETURN NONE;
			",
	)
	.await?;

	let guard = start_index_build_paused(
			&ds_a,
			&session,
			"DEFINE INDEX test ON vec FIELDS vector HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32 EFC 16 M 4 CONCURRENTLY",
		)
		.await?;
	execute_all_retrying_conflicts(
		&ds_b,
		&session,
		"CREATE vec:queued SET vector = [10f, 10f] RETURN NONE",
	)
	.await?;
	drop(guard);
	wait_for_index_ready(&ds_a, &session, "vec", "test").await?;

	assert_eq!(
		query_array_len(
			&ds_a,
			&session,
			"SELECT id FROM vec WITH INDEX test WHERE vector <|1,40|> [10f, 10f] AND id = vec:queued"
		)
		.await?,
		1
	);
	Ok(())
}

/// Where a `CONCURRENTLY` build is held while a second node's writes queue
/// behind it.
#[cfg(feature = "kv-mem")]
#[derive(Clone, Copy, Debug)]
enum BuildPause {
	/// Before the initial scan reads a row: the scan then finds each record at
	/// its final value and has to index the queued baseline instead.
	BeforeScan,
	/// After the initial scan read its batch, while that batch's commit
	/// retries: the rows the scan holds are older than the queued writes.
	InScanBatch,
}

#[cfg(feature = "kv-mem")]
impl BuildPause {
	const ALL: [Self; 2] = [Self::BeforeScan, Self::InScanBatch];

	fn site(self) -> RetryableConflictSite {
		match self {
			Self::BeforeScan => RetryableConflictSite::ConcurrentIndexInitialCleanup,
			Self::InScanBatch => RetryableConflictSite::ConcurrentIndexInitialBatch,
		}
	}
}

/// The records of table `t` and the value each starts with; `f` is the
/// indexed field. Values are names, spelled per index kind by a literal
/// function: a word for the scalar kinds, a point for the vector kinds.
#[cfg(feature = "kv-mem")]
const TWICE_MODIFIED_SEED: [(&str, &str); 5] =
	[("twice", "v0"), ("in_one", "w0"), ("gone", "x0"), ("back", "y0"), ("still", "z0")];

/// Every way to change one record twice before a builder has replayed the
/// first change: two updates in two transactions, two updates in one, an
/// update then a delete, and a delete then a re-create. Each step is one
/// transaction, so retrying a conflicted step repeats only that step.
/// `{name}` is replaced by the literal for that value.
#[cfg(feature = "kv-mem")]
const TWICE_MODIFIED_STEPS: [&str; 7] = [
	"UPDATE t:twice SET f = {v1} RETURN NONE",
	"UPDATE t:twice SET f = {v2} RETURN NONE",
	"BEGIN; UPDATE t:in_one SET f = {w1} RETURN NONE; UPDATE t:in_one SET f = {w2} RETURN NONE; COMMIT",
	"UPDATE t:gone SET f = {x1} RETURN NONE",
	"DELETE t:gone RETURN NONE",
	"DELETE t:back RETURN NONE",
	"CREATE t:back SET f = {y1} RETURN NONE",
];

/// The records left once every step has committed, with their values.
#[cfg(feature = "kv-mem")]
const TWICE_MODIFIED_FINAL: [(&str, &str); 4] =
	[("back", "y1"), ("in_one", "w2"), ("still", "z0"), ("twice", "v2")];

/// Every value some record held at some point.
#[cfg(feature = "kv-mem")]
const TWICE_MODIFIED_HISTORY: [&str; 11] =
	["v0", "v1", "v2", "w0", "w1", "w2", "x0", "x1", "y0", "y1", "z0"];

#[cfg(feature = "kv-mem")]
fn word(name: &str) -> String {
	format!("'{name}'")
}

/// A 2-d point per value, spaced so that no query point in the history is
/// equidistant from two of the final records.
#[cfg(feature = "kv-mem")]
fn point(name: &str) -> String {
	let (x, y) = match name {
		"v0" => (0, 0),
		"v1" => (10, 0),
		"v2" => (20, 0),
		"w0" => (0, 10),
		"w1" => (0, 20),
		"w2" => (0, 30),
		"x0" => (-10, 0),
		"x1" => (-20, 0),
		"y0" => (0, -10),
		"y1" => (0, -25),
		"z0" => (50, 50),
		other => unreachable!("no point for {other}"),
	};
	format!("[{x}f, {y}f]")
}

#[cfg(feature = "kv-mem")]
fn spell(template: &str, literal: fn(&str) -> String) -> String {
	TWICE_MODIFIED_HISTORY
		.iter()
		.fold(template.to_owned(), |sql, name| sql.replace(&format!("{{{name}}}"), &literal(name)))
}

/// The ids of the records whose final value is `value`, in id order.
#[cfg(feature = "kv-mem")]
fn twice_modified_holders(value: &str) -> Vec<String> {
	TWICE_MODIFIED_FINAL
		.iter()
		.filter(|(_, held)| *held == value)
		.map(|(id, _)| (*id).to_owned())
		.collect()
}

/// The number of changes queued behind a build, across every generation.
#[cfg(feature = "kv-mem")]
async fn durable_appending_count(ds: &Datastore, ikb: &IndexKeyBase) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let bg = catch!(tx, tx.keys(ikb.new_bg_all_generations_range()?, u32::MAX, 0, None).await);
	tx.cancel().await?;
	Ok(bg.len())
}

/// A query's rows as JSON, for comparing two queries' answers.
#[cfg(feature = "kv-mem")]
async fn query_json(ds: &Datastore, session: &Session, sql: &str) -> Result<serde_json::Value> {
	let mut results = ds.execute(sql, session, None).await?;
	Ok(results.remove(0).result?.into_json_value())
}

/// Seeds `t`, starts `define` (an index named `ix`) held at `pause`, applies
/// [`TWICE_MODIFIED_STEPS`] through a second node so every write that changes
/// what the index holds queues behind the build — `queued` of them — then
/// releases the build and waits for it to publish.
#[cfg(feature = "kv-mem")]
async fn build_over_records_modified_twice(
	define: &str,
	pause: BuildPause,
	literal: fn(&str) -> String,
	queued: usize,
) -> Result<(Arc<Datastore>, Session)> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	let seed: String = TWICE_MODIFIED_SEED
		.iter()
		.map(|(id, value)| format!("CREATE t:{id} SET f = {} RETURN NONE;", literal(value)))
		.collect();
	execute_all(&ds_a, &session, &format!("DEFINE TABLE t SCHEMALESS; {seed}")).await?;
	let site = pause.site();
	let node_id = ds_a.id();
	let guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);
	execute_all(&ds_a, &session, define).await?;
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;
	for step in TWICE_MODIFIED_STEPS {
		execute_all_retrying_conflicts(&ds_b, &session, &spell(step, literal)).await?;
	}
	// The queue keeps one entry per change, a record's changes included:
	// nothing is merged before the builder replays them in order.
	let (ns, db, table, ix) = get_table_index(&ds_a, "t", "ix").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	assert_eq!(
		durable_appending_count(&ds_a, &ikb).await?,
		queued,
		"{pause:?}: one entry per change"
	);
	assert!(
		retryable_conflict_count(site, node_id) > 0,
		"{pause:?}: the build must still be held when the last write commits"
	);
	drop(guard);
	wait_for_index_ready(&ds_a, &session, "t", "ix").await?;
	Ok((ds_a, session))
}

/// Every value in the history resolves, through the index, to exactly the
/// records holding it now, and to the same rows a scan finds.
#[cfg(feature = "kv-mem")]
async fn assert_equality_lookups_match_the_rows(
	ds: &Datastore,
	session: &Session,
	pause: BuildPause,
) -> Result<()> {
	for value in TWICE_MODIFIED_HISTORY {
		let indexed = format!(
			"SELECT VALUE record::id(id) FROM t WITH INDEX ix WHERE f = '{value}' ORDER BY id"
		);
		let scanned = indexed.replace("WITH INDEX ix", "WITH NOINDEX");
		let got = query_json(ds, session, &indexed).await?;
		assert_eq!(got, serde_json::json!(twice_modified_holders(value)), "{pause:?}: {indexed}");
		assert_eq!(got, query_json(ds, session, &scanned).await?, "{pause:?}: {indexed}");
	}
	Ok(())
}

/// A standard index built while records are changed twice holds exactly one
/// entry per record, for its final value: no entry for a value a record left,
/// and none for a deleted record.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_standard_index_replays_records_modified_twice() -> Result<()> {
	for pause in BuildPause::ALL {
		let (ds, session) = build_over_records_modified_twice(
			"DEFINE INDEX ix ON t FIELDS f CONCURRENTLY",
			pause,
			word,
			TWICE_MODIFIED_STEPS.len() + 1,
		)
		.await?;
		assert_equality_lookups_match_the_rows(&ds, &session, pause).await?;
		let all = query_json(
			&ds,
			&session,
			"SELECT VALUE record::id(id) FROM t WITH INDEX ix WHERE f >= 'a' ORDER BY id",
		)
		.await?;
		let finals: Vec<&str> = TWICE_MODIFIED_FINAL.iter().map(|(id, _)| *id).collect();
		assert_eq!(all, serde_json::json!(finals), "{pause:?}: one entry per live record");
	}
	Ok(())
}

/// A unique index built while records are changed twice claims exactly the
/// final values: each is still enforced, and every value a record left, or a
/// deleted record held, is free to claim again.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_unique_index_replays_records_modified_twice() -> Result<()> {
	for pause in BuildPause::ALL {
		let (ds, session) = build_over_records_modified_twice(
			"DEFINE INDEX ix ON t FIELDS f UNIQUE CONCURRENTLY",
			pause,
			word,
			TWICE_MODIFIED_STEPS.len() + 1,
		)
		.await?;
		assert_equality_lookups_match_the_rows(&ds, &session, pause).await?;
		for value in TWICE_MODIFIED_HISTORY {
			let sql = format!("CREATE t:{value}_again SET f = '{value}' RETURN NONE");
			let created = execute_all(&ds, &session, &sql).await;
			let held = !twice_modified_holders(value).is_empty();
			assert_eq!(
				created.is_err(),
				held,
				"{pause:?}: {sql} must fail exactly when a record holds '{value}': {created:?}"
			);
		}
	}
	Ok(())
}

/// The total a COUNT index holds: every `!iu` delta it has stored, summed.
#[cfg(feature = "kv-mem")]
async fn count_index_total(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: IndexId,
) -> Result<i64> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let rng = IndexCountPrefix {
		ns,
		db,
		tb: Cow::Borrowed(table),
		ix,
	}
	.range()?;
	let keys = catch!(tx, tx.keys(rng, u32::MAX, 0, None).await);
	tx.cancel().await?;
	let mut total = 0;
	for key in keys {
		let iu = IndexCountKey::decode_key(&key)?;
		total += if iu.pos {
			iu.count as i64
		} else {
			-(iu.count as i64)
		};
	}
	Ok(total)
}

/// A COUNT index built while records are changed twice counts each live
/// record once, and a conditional COUNT index counts a record whose match
/// flips twice by its final value alone. The index's stored total is read
/// directly: an unconditional count query is answered from the table's keys,
/// not the index.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_count_index_replays_records_modified_twice() -> Result<()> {
	// An unconditional COUNT index is touched only by the two deletes and the
	// re-create; a conditional one by every change that flips a match.
	let cases = [
		("DEFINE INDEX ix ON t COUNT CONCURRENTLY", "SELECT count() FROM t GROUP ALL", 4, 3),
		// `twice`, `in_one` and `gone` each match only at their intermediate
		// value; `back` matches only once it is re-created.
		(
			"DEFINE INDEX ix ON t COUNT WHERE f IN ['v1', 'w1', 'x1', 'y1'] CONCURRENTLY",
			"SELECT count() FROM t WHERE f IN ['v1', 'w1', 'x1', 'y1'] GROUP ALL",
			1,
			TWICE_MODIFIED_STEPS.len() + 1,
		),
	];
	for (define, count, expected, queued) in cases {
		for pause in BuildPause::ALL {
			let (ds, session) =
				build_over_records_modified_twice(define, pause, word, queued).await?;
			let (ns, db, table, ix) = get_table_index(&ds, "t", "ix").await?;
			assert_eq!(
				count_index_total(&ds, ns, db, &table, ix.index_id).await?,
				expected,
				"{pause:?}: {define}"
			);
			assert_eq!(
				count_query_value(&ds, &session, count).await?,
				expected,
				"{pause:?}: {count}"
			);
			let scanned = count.replace("FROM t", "FROM t WITH NOINDEX");
			assert_eq!(
				count_query_value(&ds, &session, &scanned).await?,
				expected,
				"{pause:?}: {scanned}"
			);
		}
	}
	Ok(())
}

/// A full-text index built while records are changed twice matches each term
/// exactly where the rows hold it, and scores every match as an index built
/// over the final rows does: its document count and lengths carry nothing of
/// a value a record left or a record that was deleted.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_fulltext_index_replays_records_modified_twice() -> Result<()> {
	const ANALYZER: &str = "DEFINE ANALYZER simple TOKENIZERS blank FILTERS lowercase;";
	for pause in BuildPause::ALL {
		let (ds, session) = build_over_records_modified_twice(
			&format!(
				"{ANALYZER} DEFINE INDEX ix ON t FIELDS f FULLTEXT ANALYZER simple BM25 CONCURRENTLY"
			),
			pause,
			word,
			TWICE_MODIFIED_STEPS.len() + 1,
		)
		.await?;
		execute_all(
			&ds,
			&session,
			"DEFINE INDEX reference ON t FIELDS f FULLTEXT ANALYZER simple BM25",
		)
		.await?;
		for value in TWICE_MODIFIED_HISTORY {
			let indexed = format!(
				"SELECT record::id(id) AS rid, search::score(0) AS score FROM t WITH INDEX ix WHERE f @0@ '{value}' ORDER BY rid"
			);
			let got = query_json(&ds, &session, &indexed).await?;
			let ids: Vec<&str> = got
				.as_array()
				.into_iter()
				.flatten()
				.filter_map(|row| row["rid"].as_str())
				.collect();
			assert_eq!(ids, twice_modified_holders(value), "{pause:?}: {indexed}");
			let reference = indexed.replace("WITH INDEX ix", "WITH INDEX reference");
			assert_eq!(got, query_json(&ds, &session, &reference).await?, "{pause:?}: {indexed}");
		}
	}
	Ok(())
}

/// Waits until the index's pending vector updates are folded into its graph.
#[cfg(feature = "kv-mem")]
async fn wait_for_index_drained(ds: &Datastore, session: &Session, index: &str) -> Result<()> {
	timeout(Duration::from_secs(10), async {
		loop {
			let building = index_building_json(ds, session, "t", index).await?;
			if building.get("compacting").and_then(|compacting| compacting.as_bool()) == Some(false)
			{
				return Ok(());
			}
			sleep(Duration::from_millis(20)).await;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("timed out waiting for {index} to drain its pending updates"))?
}

/// From every point a record ever held, the index's nearest neighbour and its
/// distance are the brute-force nearest neighbour and distance over the live
/// rows, and a wide search returns each live record exactly once. Distances are
/// compared to three decimals: the index scores in the vectors' `F32`, brute
/// force in the rows' floats. No point is equidistant from two live records.
#[cfg(feature = "kv-mem")]
async fn assert_nearest_neighbours_match_brute_force(
	ds: &Datastore,
	session: &Session,
	context: &str,
	points: &[String],
	live: &[&str],
) -> Result<()> {
	for at in points {
		let indexed = format!(
			"SELECT record::id(id) AS id, math::fixed(vector::distance::knn(), 3) AS distance FROM t WITH INDEX ix WHERE f <|1,40|> {at}"
		);
		let brute = format!(
			"SELECT record::id(id) AS id, math::fixed(vector::distance::knn(), 3) AS distance FROM t WITH NOINDEX WHERE f <|1,EUCLIDEAN|> {at}"
		);
		assert_eq!(
			query_json(ds, session, &indexed).await?,
			query_json(ds, session, &brute).await?,
			"{context}: nearest neighbour of {at}"
		);
	}
	let wide = query_json(
		ds,
		session,
		"SELECT VALUE record::id(id) FROM t WITH INDEX ix WHERE f <|10,40|> [0f, 0f] ORDER BY id",
	)
	.await?;
	assert_eq!(wide, serde_json::json!(live), "{context}: each live record exactly once");
	Ok(())
}

/// Builds a vector index while records are changed twice, then changes
/// records twice again once it is online, and checks the answers each time:
/// with the queued changes still pending, once the build has drained them into
/// the graph, and once compaction has folded the online changes — which
/// remove vectors the graph holds — in as well.
#[cfg(feature = "kv-mem")]
async fn assert_vector_index_replays_records_modified_twice(define: &str) -> Result<()> {
	for pause in BuildPause::ALL {
		let (ds, session) =
			build_over_records_modified_twice(define, pause, point, TWICE_MODIFIED_STEPS.len() + 1)
				.await?;
		let history: Vec<String> = TWICE_MODIFIED_HISTORY.iter().map(|name| point(name)).collect();
		let finals: Vec<&str> = TWICE_MODIFIED_FINAL.iter().map(|(id, _)| *id).collect();
		let context = format!("{pause:?} after the build");
		assert_nearest_neighbours_match_brute_force(&ds, &session, &context, &history, &finals)
			.await?;
		wait_for_index_drained(&ds, &session, "ix").await?;
		let context = format!("{pause:?} after the drain");
		assert_nearest_neighbours_match_brute_force(&ds, &session, &context, &history, &finals)
			.await?;

		for step in [
			"UPDATE t:twice SET f = [30f, 0f] RETURN NONE",
			"UPDATE t:twice SET f = [40f, 0f] RETURN NONE",
			"BEGIN; UPDATE t:in_one SET f = [0f, 40f] RETURN NONE; UPDATE t:in_one SET f = [0f, 44f] RETURN NONE; COMMIT",
			"UPDATE t:still SET f = [60f, 60f] RETURN NONE",
			"DELETE t:still RETURN NONE",
		] {
			execute_all(&ds, &session, step).await?;
		}
		let online: Vec<String> = [
			"[20f, 0f]",
			"[30f, 0f]",
			"[40f, 0f]",
			"[0f, 30f]",
			"[0f, 40f]",
			"[0f, 44f]",
			"[50f, 50f]",
			"[60f, 60f]",
		]
		.into_iter()
		.chain(history.iter().map(String::as_str))
		.map(str::to_owned)
		.collect();
		let live = ["back", "in_one", "twice"];
		let context = format!("{pause:?} with online changes pending");
		assert_nearest_neighbours_match_brute_force(&ds, &session, &context, &online, &live)
			.await?;
		Datastore::index_compaction(
			Arc::clone(&ds),
			Duration::from_secs(1),
			CancellationToken::new(),
		)
		.await?;
		wait_for_index_drained(&ds, &session, "ix").await?;
		let context = format!("{pause:?} after compacting the online changes");
		assert_nearest_neighbours_match_brute_force(&ds, &session, &context, &online, &live)
			.await?;
	}
	Ok(())
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_hnsw_index_replays_records_modified_twice() -> Result<()> {
	assert_vector_index_replays_records_modified_twice(
		"DEFINE INDEX ix ON t FIELDS f HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32 EFC 16 M 4 CONCURRENTLY",
	)
	.await
}

#[cfg(all(feature = "kv-mem", diskann))]
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_diskann_index_replays_records_modified_twice() -> Result<()> {
	assert_vector_index_replays_records_modified_twice(
		"DEFINE INDEX ix ON t FIELDS f DISKANN DIMENSION 2 DIST EUCLIDEAN TYPE F32 CONCURRENTLY",
	)
	.await
}

/// Records changed twice while the build's own drain is folding pendings into
/// the graph: every drain batch is built and then fails its commit, so it is
/// re-planned from the pendings as they stand, until the build is released.
/// Each record keeps a single pending entry however often it changes, and the
/// drain that finally commits leaves the graph answering for the final rows.
#[cfg(feature = "kv-mem")]
async fn assert_vector_drain_folds_records_modified_twice(
	define: &str,
	site: RetryableConflictSite,
) -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	let seed: String = TWICE_MODIFIED_SEED
		.iter()
		.map(|(id, value)| format!("CREATE t:{id} SET f = {} RETURN NONE;", point(value)))
		.collect();
	execute_all(&ds_a, &session, &format!("DEFINE TABLE t SCHEMALESS; {seed}")).await?;
	let node_id = ds_a.id();
	let guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);
	execute_all(&ds_a, &session, define).await?;
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;
	for step in TWICE_MODIFIED_STEPS {
		execute_all_retrying_conflicts(&ds_b, &session, &spell(step, point)).await?;
	}
	assert!(
		retryable_conflict_count(site, node_id) > 0,
		"the drain must still be retrying when the last write commits"
	);
	drop(guard);
	wait_for_index_drained(&ds_a, &session, "ix").await?;
	let history: Vec<String> = TWICE_MODIFIED_HISTORY.iter().map(|name| point(name)).collect();
	let finals: Vec<&str> = TWICE_MODIFIED_FINAL.iter().map(|(id, _)| *id).collect();
	assert_nearest_neighbours_match_brute_force(
		&ds_a,
		&session,
		"after the drain",
		&history,
		&finals,
	)
	.await
}

#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn hnsw_build_drain_folds_records_modified_twice() -> Result<()> {
	assert_vector_drain_folds_records_modified_twice(
		"DEFINE INDEX ix ON t FIELDS f HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32 EFC 16 M 4 CONCURRENTLY",
		RetryableConflictSite::ConcurrentIndexHnswPendingCompaction,
	)
	.await
}

#[cfg(all(feature = "kv-mem", diskann))]
#[tokio::test(flavor = "multi_thread")]
async fn diskann_build_drain_folds_records_modified_twice() -> Result<()> {
	assert_vector_drain_folds_records_modified_twice(
		"DEFINE INDEX ix ON t FIELDS f DISKANN DIMENSION 2 DIST EUCLIDEAN TYPE F32 CONCURRENTLY",
		RetryableConflictSite::ConcurrentIndexDiskAnnPendingCompaction,
	)
	.await
}

#[tokio::test(flavor = "multi_thread")]
async fn concurrent_indexing_retries_initial_cleanup_commit_conflict() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	let site = RetryableConflictSite::ConcurrentIndexInitialCleanup;
	let node_id = ds.id();
	let _guard = inject_retryable_conflict(site, node_id);

	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
			",
	)
	.await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

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

#[tokio::test(flavor = "multi_thread")]
async fn concurrent_indexing_retries_initial_batch_commit_conflict() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:1 SET email = 'one@example.com' RETURN NONE;
			CREATE user:2 SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;
	let site = RetryableConflictSite::ConcurrentIndexInitialBatch;
	let node_id = ds.id();
	let _guard = inject_retryable_conflict(site, node_id);

	execute_all(&ds, &session, "DEFINE INDEX test ON user FIELDS email CONCURRENTLY").await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

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

#[tokio::test(flavor = "multi_thread")]
async fn concurrent_indexing_retries_initial_cleanup_stops_after_abort() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	let site = RetryableConflictSite::ConcurrentIndexInitialCleanup;
	let node_id = ds.id();
	let _guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);

	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
			",
	)
	.await?;
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;

	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	let remaining = wait_for_retry_conflict_count_to_stabilize(site, node_id).await?;
	assert!(remaining > 0, "abort should stop retries before all conflicts are consumed");
	Ok(())
}

/// The HNSW pending drain that closes a blocking build contends with the
/// datastore's periodic index compaction over the same batch, so the loser's
/// commit fails with a retryable conflict. That conflict must be retried
/// against a freshly read plan, not returned: it is the statement's own error
/// otherwise, and `REBUILD INDEX` reports a raw transaction conflict the caller
/// can do nothing with.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn rebuild_index_retries_a_conflicted_hnsw_pending_compaction() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let site = RetryableConflictSite::ConcurrentIndexHnswPendingCompaction;
	let node_id = ds.id();
	let _guard = inject_retryable_conflict(site, node_id);

	execute_all(&ds, &session, "REBUILD INDEX hx ON t").await?;

	assert_eq!(
		retryable_conflict_count(site, node_id),
		0,
		"the rebuild must consume the injected conflict by retrying the drain"
	);
	// A retry that gave up early would leave pendings uncompacted, so the graph
	// would answer with fewer neighbours than the table holds.
	expect_indexed_query_len(&ds, &session, "SELECT id FROM t WHERE vec <|2,40|> [1.0f, 0.0f]", 2)
		.await
}

/// DiskANN counterpart of
/// [`rebuild_index_retries_a_conflicted_hnsw_pending_compaction`]. Its apply
/// owns the commit, so the conflict arrives as the apply's own error.
#[cfg(all(feature = "kv-mem", diskann))]
#[tokio::test(flavor = "multi_thread")]
async fn rebuild_index_retries_a_conflicted_diskann_pending_compaction() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX dx ON t FIELDS vec DISKANN DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let site = RetryableConflictSite::ConcurrentIndexDiskAnnPendingCompaction;
	let node_id = ds.id();
	let _guard = inject_retryable_conflict(site, node_id);

	execute_all(&ds, &session, "REBUILD INDEX dx ON t").await?;

	assert_eq!(
		retryable_conflict_count(site, node_id),
		0,
		"the rebuild must consume the injected conflict by retrying the drain"
	);
	expect_indexed_query_len(&ds, &session, "SELECT id FROM t WHERE vec <|2,40|> [1.0f, 0.0f]", 2)
		.await
}

/// The periodic index-compaction task must leave an index alone while a local
/// build owns it.
///
/// A `REBUILD INDEX` that migrates the on-disk format holds the new definition
/// in its own uncommitted transaction, so the compaction task reads the retired
/// one from the catalog. Compacting from there folds the index's pendings into
/// the layout the rebuild is replacing, and the published index is left without
/// them — a silently empty vector index rather than a failed statement.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn index_compaction_leaves_an_index_its_builder_still_owns() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	let pendings = count_hnsw_pendings(&ds, &ikb).await?;
	assert!(pendings > 0, "the fixture must leave pendings for a compaction to consume");

	// Park a build in its pre-scan cleanup retry loop. The injection aborts the
	// transaction that both wipes the index data and would commit the wipe, so
	// the pendings above survive while the index stays registered to a builder.
	let site = RetryableConflictSite::ConcurrentIndexInitialCleanup;
	let node_id = ds.id();
	let _guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);
	execute_all(&ds, &session, "REBUILD INDEX hx ON t CONCURRENTLY").await?;
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;

	assert_eq!(
		count_hnsw_pendings(&ds, &ikb).await?,
		pendings,
		"compaction must leave the pendings to the builder that owns the index"
	);
	// Stop the parked build so the task does not outlive the test.
	execute_all(&ds, &session, "REMOVE INDEX hx ON t").await?;
	Ok(())
}

/// `INFO FOR INDEX` must say whether the index is still folding queued writes
/// into itself, because `status` alone cannot.
///
/// An index whose compaction queue is not drained answers a kNN search by
/// scoring the queued entries by hand, which costs far more than the index it
/// is standing in for — measured at ~600ms against ~5ms on a 1M-row HNSW index.
/// Every other field here reads exactly the same in both states: `status` is
/// `ready`, and `pending` — which counts writes that arrived *during* a
/// `CONCURRENTLY` build — is 0. Without `compacting`, a caller that builds an
/// index and then queries has no way to tell the two apart.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn info_for_index_reports_an_undrained_compaction_queue() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;

	let building = index_building_json(&ds, &session, "t", "hx").await?;
	assert_eq!(
		building.get("compacting").and_then(|v| v.as_bool()),
		Some(true),
		"records were written and not yet folded into the graph: {building}"
	);
	// The fields that already existed cannot distinguish this state, which is
	// the whole reason for the two above.
	assert_eq!(building.get("status").and_then(|v| v.as_str()), Some("ready"), "{building}");
	assert_eq!(building.get("pending").and_then(|v| v.as_u64()), Some(0), "{building}");

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;

	let building = index_building_json(&ds, &session, "t", "hx").await?;
	assert_eq!(
		building.get("compacting").and_then(|v| v.as_bool()),
		Some(false),
		"the queue drained, so the index now answers at index speed: {building}"
	);
	Ok(())
}

/// The DiskANN half of [`info_for_index_reports_an_undrained_compaction_queue`].
///
/// Worth its own test rather than a parameter: the two engines keep pending
/// work in different places. HNSW appends to one range; DiskANN writes to a
/// sharded range and gates each shard on its own guard, so a probe that reads
/// only the unsharded legacy range reports a settled index no matter how much
/// is outstanding. That is precisely the shape of the bug this covers.
#[cfg(all(feature = "kv-mem", diskann))]
#[tokio::test(flavor = "multi_thread")]
async fn info_for_index_reports_an_undrained_diskann_pending_set() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX dx ON t FIELDS vec DISKANN DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;

	let building = index_building_json(&ds, &session, "t", "dx").await?;
	assert_eq!(
		building.get("compacting").and_then(|v| v.as_bool()),
		Some(true),
		"records were written and not yet folded into the graph: {building}"
	);
	assert_eq!(building.get("status").and_then(|v| v.as_str()), Some("ready"), "{building}");
	assert_eq!(building.get("pending").and_then(|v| v.as_u64()), Some(0), "{building}");

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;

	let building = index_building_json(&ds, &session, "t", "dx").await?;
	assert_eq!(
		building.get("compacting").and_then(|v| v.as_bool()),
		Some(false),
		"the pending set drained, so the index now answers at index speed: {building}"
	);
	Ok(())
}

/// The exclusion must hold cluster-wide, not just for builds on this node. The
/// `IndexCompaction` task lease can sit on a different node from the one running
/// the rebuild, and that node's local builder registry knows nothing about it.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn index_compaction_leaves_an_index_a_remote_builder_owns() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	let pendings = count_hnsw_pendings(&ds, &ikb).await?;
	assert!(pendings > 0, "the fixture must leave pendings for a compaction to consume");
	claim_build_for_a_remote_owner(&ds, &ikb, chrono::Duration::zero()).await?;

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;

	assert_eq!(
		count_hnsw_pendings(&ds, &ikb).await?,
		pendings,
		"compaction must leave the pendings to the builder that owns the index"
	);
	Ok(())
}

/// A heartbeat lapse is not a fence. `maintain_build_ownership` accepts the
/// same `(generation, owner)` whatever the heartbeat age, so a builder stalled
/// inside one long uninterruptible stretch can resume and keep writing; letting
/// compaction in on wall-clock expiry alone would put it alongside a live
/// writer. Only a committed takeover changes the owner.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn index_compaction_still_defers_to_a_build_whose_heartbeat_lapsed() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	let pendings = count_hnsw_pendings(&ds, &ikb).await?;
	assert!(pendings > 0, "the fixture must leave pendings for a compaction to consume");
	claim_build_for_a_remote_owner(
		&ds,
		&ikb,
		chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS * 4),
	)
	.await?;

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;

	assert_eq!(
		count_hnsw_pendings(&ds, &ikb).await?,
		pendings,
		"an expired heartbeat is a takeover trigger, not evidence that nobody is writing"
	);
	Ok(())
}

/// The window between publishing `Online` and the statement committing its
/// catalog change is still owned: the build's own pending drain runs there, and
/// the catalog still advertises the format the rebuild is replacing. Ownership
/// is not released until that drain is done.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn index_compaction_defers_to_an_online_build_that_has_not_released() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);
	let pendings = count_hnsw_pendings(&ds, &ikb).await?;
	assert!(pendings > 0, "the fixture must leave pendings for a compaction to consume");
	// A published generation whose owner has not yet released it — what a
	// blocking rebuild looks like from another node while it drains.
	let mut state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	assert_eq!(state.owner, None, "a finished build must have released ownership");
	state.owner = Some(Uuid::now_v7());
	state.owner_heartbeat_at = Some(Utc::now());
	set_durable_build_state(&ds, &ikb, state).await?;

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;

	assert_eq!(
		count_hnsw_pendings(&ds, &ikb).await?,
		pendings,
		"an Online generation still owned by its builder must be left to that builder"
	);
	Ok(())
}

/// Run a build the way a statement does: inside a write transaction that stays
/// open across it and is the caller's to close.
///
/// Returns once the build task has exited, whether the statement waited on it
/// (`blocking`) or only spawned it, so a caller can assert on what the finished
/// build left behind while its statement is still uncommitted.
#[cfg(feature = "kv-mem")]
async fn build_index_inside_an_open_statement_transaction(
	ds: &Arc<Datastore>,
	session: &Session,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: Arc<IndexDefinition>,
	blocking: bool,
) -> Result<Arc<crate::kvs::Transaction>> {
	let txn = Arc::new(ds.transaction(TransactionType::Write).await?);
	let table_def = catch!(txn, txn.get_tb(ns, db, table, None).await).expect("table should exist");
	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::clone(&txn));
	let ctx = ctx.freeze();
	let builder = ctx.get_index_builder().expect("index builder should exist").clone();
	let index_id = ix.index_id;
	let rcv =
		builder.build(&ctx, ds.setup_options(session), table_def.table_id, ix, blocking).await?;
	match rcv {
		Some(rcv) => rcv.await.expect("the build task must report its result")?,
		None => {
			let building = local_builder_for_key(ds, ns, db, table, index_id)
				.await?
				.expect("the build registers a local builder");
			wait_for_finished_builder(&building).await?;
		}
	}
	Ok(txn)
}

/// `CONCURRENTLY` returns as soon as the build task is spawned, so its
/// statement transaction — the one staging the definition the build is made
/// against — is still uncommitted while the build runs and can outlast it on a
/// small index. Ownership has to cover that too, not just the blocking case.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn build_ownership_outlives_a_concurrent_build_until_its_statement_commits() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	let txn = build_index_inside_an_open_statement_transaction(
		&ds,
		&session,
		ns,
		db,
		&table,
		Arc::clone(&ix),
		false,
	)
	.await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	assert!(
		state.owner.is_some(),
		"a concurrent build must hold the fence until its statement transaction closes"
	);

	txn.commit().await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.owner, None, "the commit must release the fence");
	Ok(())
}

/// A blocking build publishes `Online` and drains its pendings while the
/// statement that started it still holds the definition it built against in an
/// uncommitted transaction. Every other node reads the previous definition for
/// that whole window, so ownership — the only durable signal that the build
/// happened — has to outlast the builder task itself.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn build_ownership_outlives_the_builder_until_its_statement_commits() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	let txn = build_index_inside_an_open_statement_transaction(
		&ds,
		&session,
		ns,
		db,
		&table,
		Arc::clone(&ix),
		true,
	)
	.await?;

	let building = local_builder_for_key(&ds, ns, db, &table, ix.index_id)
		.await?
		.expect("the build registers a local builder");
	assert!(building.is_finished(), "a blocking build reports only after its task has exited");
	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	assert!(
		state.owner.is_some(),
		"ownership must still fence compaction while the statement transaction is open"
	);

	txn.commit().await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(
		state.owner, None,
		"the commit that publishes the definition must release the fence"
	);
	Ok(())
}

/// The fence answers a compaction request with "leave it to the builder", and
/// the queue entry that carried it is deleted with its batch either way. That
/// costs nothing while the builder still has a drain to run, but the fence
/// outlives its last one: a write committing between the drain and the
/// statement's commit queues a pending whose request is consumed by a pass that
/// does not act on it. Releasing the fence has to put a request back.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn releasing_build_ownership_requeues_compaction_skipped_by_the_fence() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	let txn = build_index_inside_an_open_statement_transaction(
		&ds,
		&session,
		ns,
		db,
		&table,
		Arc::clone(&ix),
		true,
	)
	.await?;
	assert_eq!(
		count_hnsw_pendings(&ds, &ikb).await?,
		0,
		"the build drains the index's pendings before it reports"
	);

	// A write in the window the fence outlives: the build has drained for the
	// last time, and the statement that publishes its definition is still open.
	execute_all(&ds, &session, "CREATE t:2 SET vec = [0.0, 1.0]").await?;
	let pendings = count_hnsw_pendings(&ds, &ikb).await?;
	assert!(pendings > 0, "the write must queue a pending for compaction to consume");

	// Consumes the request that write queued without acting on it.
	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;
	assert_eq!(
		count_hnsw_pendings(&ds, &ikb).await?,
		pendings,
		"the fence must leave the pending to the builder"
	);

	txn.commit().await?;

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;
	assert_eq!(
		count_hnsw_pendings(&ds, &ikb).await?,
		0,
		"the released fence must queue the compaction it turned away"
	);
	Ok(())
}

/// A statement that does not commit leaves the definition background
/// compaction was already reading, so the fence it was holding has to go too —
/// otherwise a rolled-back rebuild strands the index with no maintenance.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn build_ownership_is_released_when_its_statement_rolls_back() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	let txn = build_index_inside_an_open_statement_transaction(
		&ds,
		&session,
		ns,
		db,
		&table,
		Arc::clone(&ix),
		true,
	)
	.await?;
	txn.cancel().await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.owner, None, "a rolled-back statement must not leave the index fenced");
	Ok(())
}

/// The exclusion is scoped to the index kinds whose builders drain their own
/// pendings. A full-text or count builder has no such drain, so skipping its
/// compaction request would drop it — the batch that carried it is deleted
/// either way — and leave the deltas uncompacted until the next write.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
async fn index_compaction_still_drains_a_count_index_under_build() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX cx ON t COUNT;
		 CREATE t:1 SET n = 1;
		 CREATE t:2 SET n = 2;
		 CREATE t:3 SET n = 3;",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "cx").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let deltas = count_index_delta_keys(&ds, ns, db, &table, ix.index_id).await?;
	assert!(deltas > 1, "the fixture must leave deltas for a compaction to fold");
	claim_build_for_a_remote_owner(&ds, &ikb, chrono::Duration::zero()).await?;

	Datastore::index_compaction(Arc::clone(&ds), Duration::from_secs(1), CancellationToken::new())
		.await?;

	assert!(
		count_index_delta_keys(&ds, ns, db, &table, ix.index_id).await? < deltas,
		"a count index under build must still be compacted"
	);
	Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn concurrent_indexing_retries_initial_batch_stops_after_abort() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:1 SET email = 'one@example.com' RETURN NONE;
			CREATE user:2 SET email = 'two@example.com' RETURN NONE;
			",
	)
	.await?;
	let site = RetryableConflictSite::ConcurrentIndexInitialBatch;
	let node_id = ds.id();
	let _guard = inject_retryable_conflicts(site, node_id, REPEATED_RETRY_CONFLICTS);

	execute_all(&ds, &session, "DEFINE INDEX test ON user FIELDS email CONCURRENTLY").await?;
	wait_for_retry_conflict(site, node_id, REPEATED_RETRY_CONFLICTS).await?;

	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;

	let remaining = wait_for_retry_conflict_count_to_stabilize(site, node_id).await?;
	assert!(remaining > 0, "abort should stop retries before all conflicts are consumed");
	Ok(())
}

/// Regression test for surrealdb/surrealdb#7304.
///
/// The background `Building` task's `FrozenContext` used to clone the
/// owning `IndexBuilder` back into itself, forming an
/// `Arc<RwLock<HashMap<.., Arc<Building>>>>` cycle that pinned the
/// `Datastore` (and its storage handles, leaking ~7 fds per RocksDB and
/// ~3 per SurrealKV instance) for the lifetime of the process.
///
/// After the fix, dropping the `Datastore` must let the inner
/// `IndexBuilder::indexes` `Arc` reach zero strong references once any
/// in-flight build task observes the drop.
#[tokio::test(flavor = "multi_thread")]
async fn datastore_drop_releases_index_builder_after_build() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
		DEFINE TABLE user SCHEMALESS;
		DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
		",
	)
	.await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	let weak_indexes = Arc::downgrade(&ds.index_builder().indexes);
	drop(ds);

	// The build task captured an `Arc<Building>` for its lifetime; once
	// `Datastore` drops, the `IndexBuilder::indexes` Arc should be
	// released as soon as the spawn task finalises its `BuildingFinishGuard`.
	timeout(Duration::from_secs(5), async {
		loop {
			if weak_indexes.upgrade().is_none() {
				return;
			}
			sleep(Duration::from_millis(20)).await;
		}
	})
	.await
	.map_err(|_| {
		anyhow::anyhow!(
			"IndexBuilder::indexes Arc not released after Datastore drop — \
			 index Building still pins the back-reference (regression of #7304)"
		)
	})?;
	Ok(())
}

// ---------------------------------------------------------------------------
// Table-level doc-ID space lifecycle under concurrent index DDL.
//
// A table's shared doc-ID space (`!di` record→doc, `!dd` doc→record) exists iff
// the table carries at least one doc-ID-consuming index (full-text / HNSW /
// DiskAnn). These tests exercise that lifecycle through the real DEFINE/REMOVE
// INDEX statement paths — including concurrent removal, where each REMOVE
// independently decides whether it dropped the last consumer.
// ---------------------------------------------------------------------------

/// Drain the deferred reclaim queue, so a test can assert on the shared doc-ID
/// space a last-consumer drop enqueued for background reclaim.
async fn drain_reclaim_queue(ds: &Arc<Datastore>) {
	const MAX_PASSES: usize = 64;
	for _ in 0..MAX_PASSES {
		let (batches, _) = Datastore::reclaim_tombstones(
			Arc::clone(ds),
			web_time::Duration::from_secs(1),
			web_time::Duration::ZERO,
			tokio_util::sync::CancellationToken::new(),
		)
		.await
		.expect("the reclaim pass must not fail");
		if batches == 0 {
			return;
		}
	}
}

/// Returns `(record→doc count, doc→record count)` for `table`'s shared doc-ID
/// space. Each prefix is scanned over its own range, so the `!dh`/`!ds` sequence
/// keys (which deliberately survive a purge) are excluded from the counts.
async fn count_doc_id_mappings(ds: &Datastore, table: &str) -> Result<(usize, usize)> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let ns = tx.get_ns_by_name("test", None).await?.expect("namespace should exist");
	let db = tx.get_db_by_name("test", "test", None).await?.expect("database should exist");
	let tb: TableName = table.into();
	let di = DocLookupPrefix::new(ns.namespace_id, db.database_id, Cow::Borrowed(&tb)).range()?;
	let dd = DocKeyPrefix::new(ns.namespace_id, db.database_id, Cow::Borrowed(&tb)).range()?;
	let di_keys = tx.keys(di, u32::MAX, 0, None).await?;
	let dd_keys = tx.keys(dd, u32::MAX, 0, None).await?;
	tx.cancel().await?;
	Ok((di_keys.len(), dd_keys.len()))
}

/// The shared doc-ID space must survive removal of a non-last consumer and be
/// reclaimed only when the last doc-ID-consuming index is dropped.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn table_doc_ids_purged_only_when_last_consumer_removed() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	// Two full-text indexes on the same table share one doc-ID space.
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25;
		 CREATE t:1 SET a = 'alpha', b = 'one';
		 CREATE t:2 SET a = 'beta',  b = 'two';
		 CREATE t:3 SET a = 'gamma', b = 'three';",
	)
	.await?;
	// One shared doc-ID per record, in both directions.
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (3, 3), "one shared doc-ID per record");

	// Dropping one of two consumers leaves the mappings — ft2 still needs them.
	execute_all(&ds, &session, "REMOVE INDEX ft1 ON t;").await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(3, 3),
		"mappings survive while another doc-ID index remains"
	);

	// Dropping the last consumer reclaims the whole shared space.
	execute_all(&ds, &session, "REMOVE INDEX ft2 ON t;").await?;
	drain_reclaim_queue(&ds).await;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(0, 0),
		"mappings purged once the last doc-ID index is removed"
	);
	Ok(())
}

/// B-tree indexes at the current format version append the record's shared
/// doc-ID to every entry value and consume the table's doc-ID space: mappings
/// are created on insert, reclaimed when the record is deleted, and purged
/// when the last consumer index is removed.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn btree_index_entries_carry_doc_ids() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX idx_a ON t FIELDS a;
		 DEFINE INDEX uniq_b ON t FIELDS b UNIQUE;
		 CREATE t:1 SET a = 'alpha', b = 1;
		 CREATE t:2 SET a = 'beta',  b = 2;",
	)
	.await?;
	// Both b-tree indexes share one doc-ID per record.
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (2, 2), "one shared doc-ID per record");

	// Every index entry value carries the record's shared doc-ID.
	let tx = ds.transaction(TransactionType::Read).await?;
	let ns = tx.get_ns_by_name("test", None).await?.expect("namespace should exist");
	let db = tx.get_db_by_name("test", "test", None).await?.expect("database should exist");
	let tb: TableName = "t".into();
	let docids = crate::idx::docids::TableDocIds::new(ns.namespace_id, db.database_id, tb.clone());
	let indexes = tx.all_tb_indexes(ns.namespace_id, db.database_id, &tb, None).await?;
	assert_eq!(indexes.len(), 2);
	let mut entries = 0;
	for ix in indexes.iter() {
		assert!(ix.has_entry_doc_ids(), "fresh b-tree indexes carry entry doc-IDs");
		let rng = EntryPrefix {
			ns: ns.namespace_id,
			db: db.database_id,
			tb: Cow::Borrowed(&tb),
			ix: ix.index_id,
		}
		.range()?;
		for (_, entry) in tx.scan(rng, u32::MAX, 0, None).await? {
			let expected = docids.get_doc_id(&tx, &entry.rid.key).await?;
			assert!(expected.is_some(), "indexed record has a shared doc-ID mapping");
			assert_eq!(entry.doc_id, expected, "entry doc-ID matches the shared mapping");
			entries += 1;
		}
	}
	assert_eq!(entries, 4, "one entry per record per index");
	tx.cancel().await?;

	// Record deletion removes the index entries and reclaims the mapping.
	execute_all(&ds, &session, "DELETE t:1;").await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (1, 1), "mapping reclaimed on delete");

	// Removing one consumer keeps the space; removing the last reclaims it.
	execute_all(&ds, &session, "REMOVE INDEX idx_a ON t;").await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(1, 1),
		"mappings survive while another b-tree consumer remains"
	);
	execute_all(&ds, &session, "REMOVE INDEX uniq_b ON t;").await?;
	drain_reclaim_queue(&ds).await;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(0, 0),
		"mappings purged once the last consumer is removed"
	);
	Ok(())
}

/// An index-only bitmap COUNT (`SELECT count() … WHERE <AND of indexed
/// predicates> GROUP ALL`, issue #547) reads index entries only — zero
/// record fetches. Proved behaviorally: after deleting the record *values*
/// directly at the KV layer (leaving index entries and doc-ID mappings
/// intact), the bitmap count still reports the indexed cardinality, while a
/// NOINDEX count — which must fetch records — reports zero.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn bitmap_count_performs_zero_record_fetches() -> Result<()> {
	use surrealdb_types::Value as PublicValue;

	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE FIELD a ON t TYPE string;
		 DEFINE FIELD b ON t TYPE bool;
		 DEFINE INDEX idx_a ON t FIELDS a;
		 DEFINE INDEX idx_b ON t FIELDS b;
		 CREATE t:1 SET a = 'x', b = true;
		 CREATE t:2 SET a = 'x', b = true;
		 CREATE t:3 SET a = 'x', b = false;
		 CREATE t:4 SET a = 'y', b = true;",
	)
	.await?;

	let count = |sql: &'static str| {
		let ds = &ds;
		let session = &session;
		async move {
			let mut results = ds.execute(sql, session, None).await?;
			let value = results.remove(0).result?;
			match value {
				PublicValue::Array(rows) if rows.len() == 1 => match rows.into_iter().next() {
					Some(PublicValue::Object(obj)) => match obj.get("count") {
						Some(PublicValue::Number(n)) => {
							n.to_int().ok_or_else(|| anyhow::anyhow!("non-integer count"))
						}
						other => anyhow::bail!("unexpected count value: {other:?}"),
					},
					other => anyhow::bail!("unexpected count row: {other:?}"),
				},
				other => anyhow::bail!("unexpected count result: {other:?}"),
			}
		}
	};

	const BITMAP_COUNT: &str = "SELECT count() FROM t WHERE a = 'x' AND b = true GROUP ALL";
	const NOINDEX_COUNT: &str =
		"SELECT count() FROM t WITH NOINDEX WHERE a = 'x' AND b = true GROUP ALL";
	assert_eq!(count(BITMAP_COUNT).await?, 2);
	assert_eq!(count(NOINDEX_COUNT).await?, 2);

	// Delete the record values directly at the KV layer, leaving the index
	// entries and the shared doc-ID mappings untouched.
	{
		let tx = ds.transaction(TransactionType::Write).await?;
		let ns = tx.get_ns_by_name("test", None).await?.expect("namespace should exist");
		let db = tx.get_db_by_name("test", "test", None).await?.expect("database should exist");
		let tb: TableName = "t".into();
		let rng = RecordPrefix {
			ns: ns.namespace_id,
			db: db.database_id,
			tb: std::borrow::Cow::Borrowed(&tb),
		}
		.range()?;
		for key in tx.keys_raw(rng, u32::MAX, 0, None).await? {
			tx.del(key.into()).await?;
		}
		tx.commit().await?;
	}

	// The bitmap count never fetched a record, so it still reports the
	// indexed cardinality; the NOINDEX count reads records and finds none.
	assert_eq!(count(BITMAP_COUNT).await?, 2, "bitmap count reads index entries only");
	assert_eq!(count(NOINDEX_COUNT).await?, 0, "record-fetching count sees the deletions");
	Ok(())
}

/// Rewrites the stored `format_version` of `table`'s `index`, simulating an
/// index persisted by an older binary. The table definition is rewritten in the
/// same transaction, so cached index lists are refreshed and the next statement
/// plans and maintains the index through the layout that version selects.
///
/// The index must be empty: only the definition changes, so any data already
/// written in another layout would be left unreachable.
#[cfg(feature = "kv-mem")]
async fn downgrade_index_format(
	ds: &Datastore,
	table: &str,
	index: &str,
	format_version: u16,
) -> Result<()> {
	let tx = ds.transaction(TransactionType::Write).await?;
	let ns = tx.get_ns_by_name("test", None).await?.expect("namespace should exist");
	let db = tx.get_db_by_name("test", "test", None).await?.expect("database should exist");
	let tb: TableName = table.into();
	let ix = tx
		.get_tb_index(ns.namespace_id, db.database_id, &tb, index, None)
		.await?
		.expect("index should exist");
	let mut old = (*ix).clone();
	old.format_version = format_version;
	tx.put_tb_index(ns.namespace_id, db.database_id, &tb, &old).await?;
	// Bump the table definition so cached index lists are refreshed.
	let tb_def = tx.expect_tb(ns.namespace_id, db.database_id, &tb).await?;
	tx.put_tb("test", "test", &tb_def).await?;
	tx.commit().await?;
	Ok(())
}

/// Runs `sql` under an explicit planner strategy — the two query engines are
/// selected per session — and returns every row's record ID in sorted
/// `table:key` form. Rows may be bare record IDs (`SELECT VALUE id`) or objects
/// carrying an `id` field.
#[cfg(feature = "kv-mem")]
async fn planner_result_ids(
	ds: &Datastore,
	strategy: crate::dbs::NewPlannerStrategy,
	sql: &str,
) -> Result<Vec<String>> {
	use surrealdb_types::ToSql;

	let session = Session::owner().with_ns("test").with_db("test").new_planner_strategy(strategy);
	let mut results = ds.execute(sql, &session, None).await?;
	let value = results.remove(0).result?;
	let surrealdb_types::Value::Array(rows) = value else {
		anyhow::bail!("query returned non-array value: {value:?}");
	};
	let mut ids = Vec::with_capacity(rows.len());
	for row in rows.iter() {
		let id = match row {
			surrealdb_types::Value::Object(obj) => obj.get("id"),
			other => Some(other),
		};
		match id {
			Some(surrealdb_types::Value::RecordId(rid)) => ids.push(rid.to_sql()),
			other => anyhow::bail!("row without a record id: {other:?}"),
		}
	}
	ids.sort();
	Ok(ids)
}

/// Asserts that the engine `strategy` selects answers `sql` with exactly
/// `expected` (sorted `table:key` form).
#[cfg(feature = "kv-mem")]
async fn assert_planner_returns(
	ds: &Datastore,
	strategy: crate::dbs::NewPlannerStrategy,
	sql: &str,
	expected: &[&str],
) -> Result<()> {
	let ids = planner_result_ids(ds, strategy, sql).await?;
	assert_eq!(ids, expected, "{strategy} engine: {sql}");
	Ok(())
}

/// Asserts that both query engines answer `sql` with exactly `expected`. The
/// default `BestEffortReadOnlyStatements` strategy cannot pin an engine, so
/// each side asks for its engine explicitly.
#[cfg(feature = "kv-mem")]
async fn assert_both_planners_return(ds: &Datastore, sql: &str, expected: &[&str]) -> Result<()> {
	use crate::dbs::NewPlannerStrategy;

	assert_planner_returns(ds, NewPlannerStrategy::ComputeOnly, sql, expected).await?;
	assert_planner_returns(ds, NewPlannerStrategy::AllReadOnlyStatements, sql, expected).await?;
	Ok(())
}

/// An index defined before the doc-ID entry format (simulated by downgrading
/// `format_version`) keeps working with bare record-ID entry values: writes,
/// guarded deletes and index-backed queries stay consistent, and the table
/// never allocates shared doc-ID mappings for it.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn btree_index_pre_doc_id_format_stays_maintainable() -> Result<()> {
	use crate::catalog::BTREE_ENTRY_DOC_IDS_FORMAT_VERSION;

	let (ds, session) = new_index_test_ds().await?;
	execute_all(&ds, &session, "DEFINE INDEX idx_a ON t FIELDS a;").await?;

	// Downgrade the (empty) index definition to the pre-doc-ID format,
	// simulating an index defined by an older binary.
	downgrade_index_format(&ds, "t", "idx_a", BTREE_ENTRY_DOC_IDS_FORMAT_VERSION - 1).await?;
	let (_, _, _, ix) = get_table_index(&ds, "t", "idx_a").await?;
	assert!(!ix.uses_doc_ids());

	// Writes through the old-format definition keep the index consistent
	// (bare record-ID values, guarded deletes still match)...
	execute_all(
		&ds,
		&session,
		"CREATE t:1 SET a = 'alpha';
		 CREATE t:2 SET a = 'gamma';
		 UPDATE t:1 SET a = 'beta';
		 DELETE t:2;",
	)
	.await?;
	assert_eq!(query_array_len(&ds, &session, "SELECT * FROM t WHERE a = 'beta'").await?, 1);
	assert_eq!(query_array_len(&ds, &session, "SELECT * FROM t WHERE a = 'alpha'").await?, 0);
	assert_eq!(query_array_len(&ds, &session, "SELECT * FROM t WHERE a = 'gamma'").await?, 0);
	// ...and no shared doc-ID mappings are allocated for it.
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (0, 0));
	Ok(())
}

/// A full-text index whose stored format predates the shared table-level
/// doc-ID space (simulated by downgrading `format_version` to 0) serves
/// MATCHES under both query engines. Its maintenance stays on the private
/// per-index doc-ID layout — the table allocates no shared doc-ID mappings for
/// it — until an explicit REBUILD moves it onto the shared space, which
/// changes neither engine's answer.
///
/// MATCHES is only answerable from a full-text index, so every assertion here
/// reads the index under test.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn legacy_fulltext_index_serves_matches_under_both_planners() -> Result<()> {
	// 'bravo' is carried by t:1 and t:2 as created, by t:3 through the update,
	// and no longer by the deleted t:4.
	const MATCHES: &str = "SELECT VALUE id FROM t WHERE content @@ 'bravo'";
	const CARRIERS: &[&str] = &["t:1", "t:2", "t:3"];

	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft ON t FIELDS content FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	downgrade_index_format(&ds, "t", "ft", 0).await?;
	let (_, _, _, ix) = get_table_index(&ds, "t", "ft").await?;
	assert!(ix.uses_doc_ids() && !ix.uses_shared_doc_ids());

	// Legacy maintenance: inserts, an update that both retracts and adds a
	// term, and a delete that retracts one.
	execute_all(
		&ds,
		&session,
		"CREATE t:1 SET content = 'alpha bravo';
		 CREATE t:2 SET content = 'bravo charlie';
		 CREATE t:3 SET content = 'delta';
		 CREATE t:4 SET content = 'bravo echo';
		 UPDATE t:3 SET content = 'bravo foxtrot';
		 DELETE t:4;",
	)
	.await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(0, 0),
		"a legacy full-text index keeps its private doc-ID space"
	);
	assert_both_planners_return(&ds, MATCHES, CARRIERS).await?;

	// Compact the postings the writes appended, so the same terms have to be
	// resolved from the compacted legacy layout. `new_index_test_ds` runs
	// without maintenance tasks, so this drains the compaction queue itself.
	let (batches, errors) = Datastore::index_compaction(
		Arc::clone(&ds),
		Duration::from_secs(60),
		tokio_util::sync::CancellationToken::new(),
	)
	.await?;
	assert_eq!(errors, 0, "the legacy layout must compact cleanly");
	assert!(batches > 0, "the writes must leave the index queued for compaction");
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (0, 0));
	assert_both_planners_return(&ds, MATCHES, CARRIERS).await?;

	execute_all(&ds, &session, "REBUILD INDEX ft ON t;").await?;
	let (_, _, _, ix) = get_table_index(&ds, "t", "ft").await?;
	assert!(ix.uses_shared_doc_ids(), "the rebuild must stamp the current format");
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(3, 3),
		"the rebuilt index allocates one shared doc-ID per surviving record"
	);
	assert_both_planners_return(&ds, MATCHES, CARRIERS).await?;
	Ok(())
}

/// Coverage shared by the legacy HNSW and DiskANN tests. `define_index` must
/// define a 2-D vector index named `vx` on `t.pt` with `DIST EUCLIDEAN`, which
/// is downgraded to the pre-shared-doc-ID format while still empty.
///
/// Euclidean distances from the query point `[0, 0]`: t:1 = 1, t:6 = 1.5,
/// t:2 = 2, t:3 = 3, t:5 = 5 (the update moved it out from 0.75). The deleted
/// t:4 was the nearest of all at 0.5, so a stale entry for either the updated
/// or the deleted record would displace an expected neighbour.
///
/// 'bravo' is carried by t:1, t:2 and t:3 but not by t:6, which sits between
/// t:1 and t:2: a KNN restricted to the matching records answers `[t:1, t:2]`,
/// while one that takes the two nearest overall and filters afterwards keeps
/// only `[t:1]`. Every KNN-with-MATCHES expectation below therefore pins which
/// of the two an engine performs.
#[cfg(feature = "kv-mem")]
async fn legacy_vector_index_knn_under_both_planners(define_index: &str) -> Result<()> {
	use crate::dbs::NewPlannerStrategy::{AllReadOnlyStatements, ComputeOnly};

	// An explicit `ef` plans through the ANN index on both engines.
	const KNN: &str = "SELECT VALUE id FROM t WHERE pt <|2,40|> [0.0, 0.0]";
	// A MATCHES conjunct that cannot drive an index iterator of its own,
	// paired with the `<|k,DIST|>` KNN form.
	const OR_MATCHES_KNN: &str = "SELECT VALUE id FROM t \
		WHERE (content @@ 'bravo' OR content = 'unmatched') AND pt <|2,EUCLIDEAN|> [0.0, 0.0]";
	// A top-level MATCHES, which the current-format full-text index serves.
	const MATCHES_KNN: &str =
		"SELECT VALUE id FROM t WHERE content @@ 'bravo' AND pt <|2,40|> [0.0, 0.0]";
	const NEAREST_TWO: &[&str] = &["t:1", "t:6"];
	const NEAREST_TWO_MATCHING: &[&str] = &["t:1", "t:2"];

	let (ds, session) = new_index_test_ds().await?;
	execute_all(&ds, &session, define_index).await?;
	downgrade_index_format(&ds, "t", "vx", 0).await?;
	let (_, _, _, ix) = get_table_index(&ds, "t", "vx").await?;
	assert!(ix.uses_doc_ids() && !ix.uses_shared_doc_ids());

	// Legacy maintenance: inserts, an update that moves a vector out of the
	// nearest pair, and a delete that removes the nearest point of all.
	execute_all(
		&ds,
		&session,
		"CREATE t:1 SET pt = [1.0, 0.0], content = 'alpha bravo';
		 CREATE t:2 SET pt = [0.0, 2.0], content = 'bravo charlie';
		 CREATE t:3 SET pt = [3.0, 0.0], content = 'bravo delta';
		 CREATE t:4 SET pt = [0.5, 0.0], content = 'echo';
		 CREATE t:5 SET pt = [0.0, 0.75], content = 'foxtrot';
		 CREATE t:6 SET pt = [1.5, 0.0], content = 'zulu golf';
		 UPDATE t:5 SET pt = [0.0, 5.0];
		 DELETE t:4;",
	)
	.await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(0, 0),
		"a legacy vector index keeps its private doc-ID space"
	);
	// Answered from the record-keyed pendings, which no compaction has drained
	// into the graph yet.
	assert_both_planners_return(&ds, KNN, NEAREST_TWO).await?;

	// Compact, so the same rows have to come back out of the graph the legacy
	// layout persisted. `new_index_test_ds` runs without maintenance tasks, so
	// this drains the compaction queue itself.
	let (batches, errors) = Datastore::index_compaction(
		Arc::clone(&ds),
		Duration::from_secs(60),
		tokio_util::sync::CancellationToken::new(),
	)
	.await?;
	assert_eq!(errors, 0, "the legacy layout must compact cleanly");
	assert!(batches > 0, "the writes must leave the index queued for compaction");
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (0, 0));
	assert_both_planners_return(&ds, KNN, NEAREST_TWO).await?;

	// A current-format full-text index built over the existing records opens
	// the table's shared doc-ID space. The legacy vector index keeps ignoring
	// it, so both layouts are live on one table and serve one statement
	// together.
	execute_all(&ds, &session, "DEFINE ANALYZER simple TOKENIZERS blank;").await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX ft ON t FIELDS content FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(5, 5),
		"the current-format full-text index allocates one shared doc-ID per record"
	);
	assert_both_planners_return(&ds, KNN, NEAREST_TWO).await?;

	// A MATCHES the full-text index cannot answer on its own leaves the
	// compute-only engine on a table scan, where excluding the legacy vector
	// index from KNN planning hands the statement to the brute-force KNN pass.
	// The exec engine takes the same rows through a top-K over its own filtered
	// scan. Both restrict the search to the matching records.
	assert_both_planners_return(&ds, OR_MATCHES_KNN, NEAREST_TWO_MATCHING).await?;

	// A top-level MATCHES is served by the full-text index. The exec engine
	// keeps the ANN search and evaluates MATCHES per candidate — a legacy
	// vector index cannot join the shared-doc-ID bitmap prefilter, so this is
	// the path that keeps the search restricted to the matching records.
	assert_planner_returns(&ds, AllReadOnlyStatements, MATCHES_KNN, NEAREST_TWO_MATCHING).await?;
	// KNN nested under OR: the exec planner rejects the shape outright before
	// union analysis, so a multi-index OR union can never contain a KNN
	// branch — legacy or current format.
	const UNION_MATCHES_KNN: &str = "SELECT VALUE id FROM t \
		WHERE (content @@ 'bravo' AND pt <|2,40|> [0.0, 0.0]) OR content @@ 'zulu'";
	let err = planner_result_ids(&ds, AllReadOnlyStatements, UNION_MATCHES_KNN)
		.await
		.expect_err("KNN under OR must be rejected by the exec planner");
	assert!(err.to_string().contains("top level of the WHERE clause"), "unexpected error: {err}");
	// The compute-only engine accepts the shape, but MATCHES anywhere in the
	// statement excludes the legacy vector index from indexed KNN planning,
	// and the `<|k,ef|>` form has no brute-force fallback: the KNN conjunct
	// evaluates false for every row, the whole branch contributes nothing,
	// and only the 'zulu' branch survives.
	assert_planner_returns(&ds, ComputeOnly, UNION_MATCHES_KNN, &["t:6"]).await?;

	// A SELECT planned inside a function body is compiled without plan-time
	// catalog context, so its source resolves at execute time through
	// DynamicScan, which re-plans the index access per run. The legacy vector
	// index must keep the MATCHES conjunct evaluable during ANN traversal on
	// that path too.
	execute_all(
		&ds,
		&session,
		"DEFINE FUNCTION fn::knn_plain() { \
			RETURN SELECT VALUE id FROM t WHERE pt <|2,40|> [0.0, 0.0]; };
		 DEFINE FUNCTION fn::knn_matches() { \
			RETURN SELECT VALUE id FROM t \
			WHERE content @@ 'bravo' AND pt <|2,40|> [0.0, 0.0]; };",
	)
	.await?;
	assert_planner_returns(&ds, AllReadOnlyStatements, "RETURN fn::knn_plain()", NEAREST_TWO)
		.await?;
	assert_planner_returns(
		&ds,
		AllReadOnlyStatements,
		"RETURN fn::knn_matches()",
		NEAREST_TWO_MATCHING,
	)
	.await?;
	// The compute-only engine cannot combine an index-served MATCHES with a KNN
	// conjunct: the full-text index becomes its iterator, which disables the
	// brute-force KNN pass, and the KNN conjunct is then false for every row.
	// That is a property of the engine rather than of the legacy layout — the
	// rebuilt, current-format index below answers the same way.
	assert_planner_returns(&ds, ComputeOnly, MATCHES_KNN, &[]).await?;

	// The rebuild moves the vector index onto the shared space it was ignoring.
	execute_all(&ds, &session, "REBUILD INDEX vx ON t;").await?;
	let (_, _, _, ix) = get_table_index(&ds, "t", "vx").await?;
	assert!(ix.uses_shared_doc_ids(), "the rebuild must stamp the current format");
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (5, 5));
	assert_both_planners_return(&ds, KNN, NEAREST_TWO).await?;
	// The exec engine now restricts the ANN search with the shared-doc-ID
	// bitmap prefilter instead, and answers both MATCHES shapes identically.
	assert_planner_returns(&ds, AllReadOnlyStatements, MATCHES_KNN, NEAREST_TWO_MATCHING).await?;
	assert_planner_returns(&ds, AllReadOnlyStatements, OR_MATCHES_KNN, NEAREST_TWO_MATCHING)
		.await?;
	// On the compute-only engine a current-format vector index is planned for
	// every KNN, including the shapes above: MATCHES is then evaluated inside
	// the ANN traversal, where it computes to `false`. Keeping the legacy index
	// out of those plans is what the rows above depend on.
	assert_planner_returns(&ds, ComputeOnly, MATCHES_KNN, &[]).await?;
	assert_planner_returns(&ds, ComputeOnly, OR_MATCHES_KNN, &[]).await?;
	// A runtime-resolved source never carries a bitmap prefilter, so on that
	// path the MATCHES conjunct stays evaluable during traversal for the
	// rebuilt, current-format index too: the top-k is still chosen among the
	// matching records.
	assert_planner_returns(&ds, AllReadOnlyStatements, "RETURN fn::knn_plain()", NEAREST_TWO)
		.await?;
	assert_planner_returns(
		&ds,
		AllReadOnlyStatements,
		"RETURN fn::knn_matches()",
		NEAREST_TWO_MATCHING,
	)
	.await?;
	Ok(())
}

/// A current-format vector index combined with a MATCHES served by a legacy
/// (format 0) full-text index: the MATCHES conjunct cannot join the
/// shared-doc-ID bitmap prefilter, so the ANN search must keep it evaluable
/// during traversal — with no prefilter at all, and alongside an allow-list
/// built from another coverable conjunct. Distances from `[0, 0]`:
/// t:1 = 1, t:6 = 1.5, t:2 = 2, t:3 = 3; 'bravo' is carried by t:1, t:2 and
/// t:3 but not t:6, so a top-2 chosen without the text predicate would keep
/// t:6 and lose t:2.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn uncovered_matches_restricts_current_format_knn() -> Result<()> {
	use crate::dbs::NewPlannerStrategy::AllReadOnlyStatements;

	const MATCHES_KNN: &str =
		"SELECT VALUE id FROM t WHERE content @@ 'bravo' AND pt <|2,40|> [0.0, 0.0]";
	const COVERED_AND_MATCHES_KNN: &str = "SELECT VALUE id FROM t \
		WHERE flag = true AND content @@ 'bravo' AND pt <|2,40|> [0.0, 0.0]";
	const NEAREST_TWO_MATCHING: &[&str] = &["t:1", "t:2"];

	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft ON t FIELDS content FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	downgrade_index_format(&ds, "t", "ft", 0).await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX vx ON t FIELDS pt HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32 EFC 16 M 4;
		 DEFINE INDEX flag_idx ON t FIELDS flag;
		 CREATE t:1 SET pt = [1.0, 0.0], content = 'alpha bravo', flag = true;
		 CREATE t:2 SET pt = [0.0, 2.0], content = 'bravo charlie', flag = true;
		 CREATE t:3 SET pt = [3.0, 0.0], content = 'bravo delta', flag = true;
		 CREATE t:6 SET pt = [1.5, 0.0], content = 'zulu golf', flag = true;",
	)
	.await?;
	let (_, _, _, vx) = get_table_index(&ds, "t", "vx").await?;
	assert!(vx.uses_shared_doc_ids(), "the vector index under test is current-format");

	// The legacy MATCHES is the only non-KNN conjunct: no prefilter can be
	// built, so the compiled MATCHES-aware condition restricts the traversal.
	assert_planner_returns(&ds, AllReadOnlyStatements, MATCHES_KNN, NEAREST_TWO_MATCHING).await?;
	// A coverable conjunct produces an allow-list that cannot include the
	// MATCHES: the compiled condition must stay active alongside it.
	assert_planner_returns(
		&ds,
		AllReadOnlyStatements,
		COVERED_AND_MATCHES_KNN,
		NEAREST_TWO_MATCHING,
	)
	.await?;
	Ok(())
}

/// An HNSW index whose stored format predates the shared table-level doc-ID
/// space (simulated by downgrading `format_version` to 0) serves KNN under
/// both query engines — on its own and alongside a MATCHES conjunct answered
/// by a current-format full-text index on the same table — and keeps its
/// private doc-ID layout until an explicit REBUILD. See
/// [`legacy_vector_index_knn_under_both_planners`] for the fixture's distances.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn legacy_hnsw_index_serves_knn_under_both_planners() -> Result<()> {
	legacy_vector_index_knn_under_both_planners(
		"DEFINE INDEX vx ON t FIELDS pt HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32 EFC 16 M 4;",
	)
	.await
}

/// DiskANN counterpart of [`legacy_hnsw_index_serves_knn_under_both_planners`]:
/// a pre-shared-doc-ID DiskANN index serves KNN under both query engines, on
/// its own and with a MATCHES conjunct, and keeps its private doc-ID layout
/// until an explicit REBUILD.
#[cfg(all(feature = "kv-mem", diskann))]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn legacy_diskann_index_serves_knn_under_both_planners() -> Result<()> {
	legacy_vector_index_knn_under_both_planners(
		"DEFINE INDEX vx ON t FIELDS pt DISKANN DIMENSION 2 DIST EUCLIDEAN TYPE F32;",
	)
	.await
}

/// Concurrent removal of the *only* two consumers must not leak the shared
/// space. Each REMOVE independently checks whether another consumer remains, so
/// without serialization both could observe the other still present and skip the
/// purge. The table-definition write serializes them, so whichever commits last
/// sees no remaining consumer and reclaims the mappings.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[test_log::test]
async fn concurrent_removal_of_last_doc_id_indexes_purges_mappings() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25;
		 CREATE t:1 SET a = 'alpha', b = 'one';
		 CREATE t:2 SET a = 'beta',  b = 'two';
		 CREATE t:3 SET a = 'gamma', b = 'three';",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (3, 3));

	// Drop both consumers concurrently, retrying the loser of the
	// table-definition write conflict.
	let task_a = {
		let (ds, session) = (Arc::clone(&ds), session.clone());
		tokio::spawn(async move {
			execute_all_retrying_conflicts(&ds, &session, "REMOVE INDEX ft1 ON t;").await
		})
	};
	let task_b = {
		let (ds, session) = (Arc::clone(&ds), session.clone());
		tokio::spawn(async move {
			execute_all_retrying_conflicts(&ds, &session, "REMOVE INDEX ft2 ON t;").await
		})
	};
	let (ra, rb) = tokio::join!(task_a, task_b);
	ra.expect("task A panicked")?;
	rb.expect("task B panicked")?;

	// Both consumers gone → space fully reclaimed, nothing leaked.
	drain_reclaim_queue(&ds).await;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(0, 0),
		"no leaked mappings after concurrent last-consumer removal"
	);
	Ok(())
}

/// Concurrently building two doc-ID indexes over the same pre-existing records
/// must converge on a single shared doc-ID per record (no divergence or
/// duplication): `resolve_or_assign` is serialized by the per-record `!di` write
/// conflict.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[test_log::test]
async fn concurrent_definition_of_doc_id_indexes_shares_one_space() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 CREATE t:1 SET a = 'alpha', b = 'one';
		 CREATE t:2 SET a = 'beta',  b = 'two';
		 CREATE t:3 SET a = 'gamma', b = 'three';",
	)
	.await?;
	// No doc-ID index yet, so the space is empty.
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(0, 0),
		"no mappings before any doc-ID index"
	);

	let task_a = {
		let (ds, session) = (Arc::clone(&ds), session.clone());
		tokio::spawn(async move {
			execute_all_retrying_conflicts(
				&ds,
				&session,
				"DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
			)
			.await
		})
	};
	let task_b = {
		let (ds, session) = (Arc::clone(&ds), session.clone());
		tokio::spawn(async move {
			execute_all_retrying_conflicts(
				&ds,
				&session,
				"DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25;",
			)
			.await
		})
	};
	let (ra, rb) = tokio::join!(task_a, task_b);
	ra.expect("task A panicked")?;
	rb.expect("task B panicked")?;

	// Exactly one shared doc-ID per record after both builds backfill.
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(3, 3),
		"one shared doc-ID per record after concurrent index builds"
	);
	Ok(())
}

/// Multi-instance variant of the concurrent-removal test: two SurrealDB
/// instances with distinct node ids share one storage engine (the deployment
/// shape the doc-ID space must tolerate) and each drops one of the two — and
/// only — consumers concurrently. Serialization happens at the shared-storage
/// table-definition write, not in any node-local state, so the space is
/// reclaimed exactly once with no leak regardless of which node commits last.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[test_log::test]
async fn distributed_concurrent_removal_of_last_doc_id_indexes_purges_mappings() -> Result<()> {
	let (ds_a, ds_b, session) = new_distributed_index_test_ds().await?;
	execute_all(
		&ds_a,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25;
		 CREATE t:1 SET a = 'alpha', b = 'one';
		 CREATE t:2 SET a = 'beta',  b = 'two';
		 CREATE t:3 SET a = 'gamma', b = 'three';",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds_a, "t").await?, (3, 3));

	// Node A drops ft1, node B drops ft2, at the same time.
	let ds_a = Arc::new(ds_a);
	let ds_b = Arc::new(ds_b);
	let task_a = {
		let (ds, session) = (Arc::clone(&ds_a), session.clone());
		tokio::spawn(async move {
			execute_all_retrying_conflicts(&ds, &session, "REMOVE INDEX ft1 ON t;").await
		})
	};
	let task_b = {
		let (ds, session) = (Arc::clone(&ds_b), session.clone());
		tokio::spawn(async move {
			execute_all_retrying_conflicts(&ds, &session, "REMOVE INDEX ft2 ON t;").await
		})
	};
	let (ra, rb) = tokio::join!(task_a, task_b);
	ra.expect("node A task panicked")?;
	rb.expect("node B task panicked")?;

	// Read from a fresh transaction: both consumers gone across both nodes, the
	// shared space is reclaimed, and nothing leaked.
	drain_reclaim_queue(&ds_a).await;
	assert_eq!(
		count_doc_id_mappings(&ds_a, "t").await?,
		(0, 0),
		"no leaked mappings after concurrent cross-instance last-consumer removal"
	);
	Ok(())
}

/// `DEFINE INDEX ... OVERWRITE` that replaces the last doc-ID consumer with a
/// non-doc-ID index must reclaim the shared space, just like `REMOVE INDEX`.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn overwrite_last_doc_id_index_with_plain_index_purges_mappings() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ix ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 CREATE t:1 SET a = 'alpha';
		 CREATE t:2 SET a = 'beta';",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (2, 2));

	// Overwriting the only doc-ID index with a plain b-tree index keeps the
	// space: b-tree indexes at the current format are doc-ID consumers too.
	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE ix ON t FIELDS a;").await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(2, 2),
		"mappings kept when OVERWRITE replaces the consumer with a b-tree consumer"
	);

	// Overwriting with a COUNT index — the only non-consumer kind — drops the
	// last consumer, so the shared space must be reclaimed.
	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE ix ON t COUNT;").await?;
	drain_reclaim_queue(&ds).await;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(0, 0),
		"mappings purged when OVERWRITE drops the last doc-ID consumer"
	);
	Ok(())
}

/// `OVERWRITE` must NOT purge when another doc-ID index still consumes the space.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn overwrite_doc_id_index_keeps_mappings_when_another_consumer_survives() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25;
		 CREATE t:1 SET a = 'alpha', b = 'one';
		 CREATE t:2 SET a = 'beta',  b = 'two';",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (2, 2));

	// Overwrite ft1 with a plain index while ft2 (doc-ID) remains a consumer.
	execute_all(&ds, &session, "DEFINE INDEX OVERWRITE ft1 ON t FIELDS a;").await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(2, 2),
		"mappings survive OVERWRITE while another doc-ID index remains"
	);
	Ok(())
}

/// `OVERWRITE` must NOT purge when the replacement is itself a doc-ID index, even
/// if it is the only consumer — the space keeps being used.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn overwrite_last_doc_id_index_with_doc_id_index_keeps_mappings() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ix ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 CREATE t:1 SET a = 'alpha';
		 CREATE t:2 SET a = 'beta';",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (2, 2));

	// Overwrite the only doc-ID index with another doc-ID index (still full-text,
	// different analyzer): a consumer still exists, so the space is preserved and
	// the rebuild re-resolves the same ids.
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple2 TOKENIZERS class;
		 DEFINE INDEX OVERWRITE ix ON t FIELDS a FULLTEXT ANALYZER simple2 BM25;",
	)
	.await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(2, 2),
		"mappings kept when the replacement is itself a doc-ID index"
	);
	Ok(())
}

/// Regression guard for the delete-during-build deferral path: a record deleted
/// while a doc-ID index is building must leave the shared doc-ID space in a
/// consistent state. The delete is enqueued for the building index, so the
/// central removal is deferred and the builder's replay reclaims the mapping.
///
/// NB: with `ft1` already Online this drives the *single-builder inline* reclaim
/// (no sibling is building, so the delete's replay reclaims the mapping right
/// away). The two-builders-at-once case — where the replay defers the reclaim
/// through a durable `!dp` marker and a later sweep completes it — is covered by
/// [`concurrent_doc_id_index_build_reclaims_deferred_mapping`] (the sweep's
/// decision matrix, driven directly) and
/// [`deferred_doc_id_reclaim_survives_across_builds`] (the end-to-end wiring
/// through a real replay, a bailing sweep, and a later reclaiming build).
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn delete_during_doc_id_index_build_keeps_shared_mapping_consistent() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	// ft1 is built first, so every record already has a shared doc-ID before ft2
	// starts building.
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 CREATE t:1 SET a = 'alpha', b = 'x';
		 CREATE t:2 SET a = 'beta',  b = 'y';
		 CREATE t:3 SET a = 'gamma', b = 'z';
		 DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (3, 3));

	// Start a second doc-ID index build and delete a record while it is queued.
	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25 CONCURRENTLY",
	)
	.await?;
	execute_all_retrying_conflicts(&ds, &session, "DELETE t:2;").await?;
	drop(guard);
	wait_for_index_ready(&ds, &session, "t", "ft2").await?;

	// Exactly the two surviving records remain mapped — the deleted record's
	// mapping was reclaimed once, not left stale.
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(2, 2),
		"delete during an index build must not leave a stale shared doc-ID mapping"
	);
	Ok(())
}

async fn read_shared_doc_id(
	ds: &Datastore,
	docs: &crate::idx::docids::TableDocIds,
	id: &RecordIdKey,
) -> Result<Option<crate::idx::docids::DocId>> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let d = docs.get_doc_id(&tx, id).await?;
	tx.cancel().await?;
	Ok(d)
}

async fn read_shared_record_id(
	ds: &Datastore,
	docs: &crate::idx::docids::TableDocIds,
	doc_id: crate::idx::docids::DocId,
) -> Result<Option<RecordIdKey>> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let id = docs.get_record_id(&tx, doc_id).await?;
	tx.cancel().await?;
	Ok(id)
}

/// Assigns (or resolves) a shared doc-ID for `id` in its own committed
/// transaction.
async fn assign_shared_doc_id(
	ds: &Datastore,
	docs: &crate::idx::docids::TableDocIds,
	id: &RecordIdKey,
) -> Result<crate::idx::docids::DocId> {
	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(ds.transaction(TransactionType::Write).await?.into());
	let ctx = ctx.freeze();
	let d = docs.resolve_or_assign(&ctx, id).await?;
	ctx.tx().commit().await?;
	Ok(d)
}

/// Writes a durable `!dp` pending-reclaim marker for `id`, as the delete
/// replay's defer branch would.
async fn seed_pending_reclaim(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	id: &RecordIdKey,
) -> Result<()> {
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(&DocPendingKey::new(ns, db, Cow::Borrowed(table), RecordIdentity(id.clone())), &())
		.await?;
	tx.commit().await
}

/// Writes a `!dp` marker in the encoding a previous release used for it: the
/// record id under the index format, which is what `!di` still spells, so the
/// bytes are that key's with its route tag swapped. Such a marker names an id
/// this release cannot decode.
async fn seed_pending_reclaim_in_previous_encoding(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	id: &RecordIdKey,
) -> Result<()> {
	let mut key =
		DocLookupKey::new(ns, db, Cow::Borrowed(table), Cow::Borrowed(id)).encode_key()?.to_vec();
	let tag = key
		.windows(3)
		.position(|w| w == b"!di")
		.expect("the erased forward key carries its route tag");
	key[tag..tag + 3].copy_from_slice(b"!dp");
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set(Key::from(key), Vec::new()).await?;
	tx.commit().await
}

/// Counts the `!dp` pending-reclaim markers on a table.
async fn count_pending_reclaims(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
) -> Result<usize> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let rng = DocPendingPrefix::new(ns, db, Cow::Borrowed(table)).range()?;
	let keys = tx.keys(rng, u32::MAX, 0, None).await?;
	tx.cancel().await?;
	Ok(keys.len())
}

/// Deterministic guard for the concurrent-build reclaim of the shared doc-ID
/// space — the two-builders-at-once case. When two doc-ID indexes build at the
/// same time, each defers a deleted record's central mapping removal through a
/// durable `!dp` marker (the sibling may still need the mapping to replay its
/// own copy of the delete); a later sweep with no building sibling must reclaim
/// it, or the `!di`/`!dd` pair is orphaned and a later re-create wrongly reuses
/// the id.
///
/// Drives [`Building::reclaim_deferred_doc_ids`] directly against a simulated
/// sibling build state to cover its whole decision matrix: markers (and
/// mappings) survive while a sibling is still building, are reclaimed once no
/// sibling is building and the record is gone, and a still-present record keeps
/// its live mapping while its stale marker is consumed. Both directions of the
/// mapping are asserted, for a plain id and for one holding a number in a
/// nested value — which the marker must address as precisely as the mapping
/// does, or the reclaim is aimed at a different record. A marker a previous
/// release wrote is translated through the erased mapping its bytes
/// address, so its reclaim is carried out rather than forfeited; one that
/// resolves to nothing is still consumed; and one whose two spellings alias —
/// which decodes cleanly as a record other than its own — is reclaimed through
/// the same chain, because decoding proves nothing about a marker's spelling. The end-to-end wiring
/// (a real replayed delete writing the marker, and a real build completion running the sweep) is
/// covered by [`deferred_doc_id_reclaim_survives_across_builds`].
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn concurrent_doc_id_index_build_reclaims_deferred_mapping() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	// Two full-text indexes on one table => two consumers of the shared !di/!dd
	// space. `ia` is our builder; `ib` stands in for the concurrent sibling.
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX ib ON t FIELDS b FULLTEXT ANALYZER simple BM25;",
	)
	.await?;

	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let (_, _, _, ib) = get_table_index(&ds, "t", "ib").await?;
	let ib_ikb = IndexKeyBase::new(ns, db, table.clone(), ib.index_id);
	let docs = crate::idx::docids::TableDocIds::new(ns, db, table.clone());

	// A record that was indexed (shared mapping assigned) then deleted during the
	// concurrent build: the mapping and its pending-reclaim marker exist but the
	// record does not.
	let gone = RecordIdKey::from("gone".to_owned());
	let assigned = assign_shared_doc_id(&ds, &docs, &gone).await?;
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &gone).await?,
		Some(assigned),
		"the deleted record must start with a shared mapping"
	);
	seed_pending_reclaim(&ds, ns, db, &table, &gone).await?;

	let ia_building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;

	// (1) Sibling `ib` still Building: the sweep must leave both the mapping and
	// the durable marker in place, so `ib` can replay its own copy of the delete
	// and a later build can still complete the reclaim.
	set_durable_build_state(
		&ds,
		&ib_ikb,
		durable_build_state_for_phase(IndexBuildPhase::Building, 1, Some(Uuid::now_v7())),
	)
	.await?;
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &gone).await?,
		Some(assigned),
		"mapping must survive while a sibling doc-ID index is still building"
	);
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		1,
		"the durable marker must survive a sweep that bails on a building sibling"
	);

	// (2) Sibling `ib` now Online: no doc-ID index is building any more and the
	// record is gone, so the marker seeded above (untouched by the bailed sweep)
	// is consumed and both directions of the mapping are reclaimed (no orphan).
	set_durable_build_state(
		&ds,
		&ib_ikb,
		durable_build_state_for_phase(IndexBuildPhase::Online, 1, None),
	)
	.await?;
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &gone).await?,
		None,
		"the sweep must reclaim the forward mapping once no sibling is building"
	);
	assert_eq!(
		read_shared_record_id(&ds, &docs, assigned).await?,
		None,
		"the sweep must reclaim the reverse mapping too"
	);
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		0,
		"the sweep must consume the pending-reclaim marker"
	);

	// delete -> re-create now yields a *new* id (the invariant the reclaim
	// restores): the stale mapping is gone, so `resolve_or_assign` allocates afresh.
	let recreated = assign_shared_doc_id(&ds, &docs, &gone).await?;
	assert_ne!(recreated, assigned, "re-create after reclaim must allocate a fresh doc-ID");

	// (3) Re-creation safety: a record that exists again must keep its mapping
	// even if a stale marker names it — dropping it would strand its index
	// entries. The stale marker itself is consumed.
	execute_all(&ds, &session, "CREATE t:live SET a = 'alpha', b = 'beta';").await?;
	let live = RecordIdKey::from("live".to_owned());
	let live_id = read_shared_doc_id(&ds, &docs, &live).await?;
	assert!(live_id.is_some(), "the live record must have a shared mapping");
	seed_pending_reclaim(&ds, ns, db, &table, &live).await?;
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &live).await?,
		live_id,
		"a still-present (re-created) record must keep its live mapping"
	);
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		0,
		"a stale marker for a live record must still be consumed"
	);

	// (4) A record id holding a number in a nested value. The marker names one
	// record, so it must round-trip the id exactly: under the index format `[1]`
	// and `[1dec]` share a key, and the id read back out of it addresses the
	// other record, whose mapping the reclaim then declines to touch — leaving
	// the marked record's mapping behind while consuming its marker.
	let nested = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(1))].into());
	let nested_id = assign_shared_doc_id(&ds, &docs, &nested).await?;
	seed_pending_reclaim(&ds, ns, db, &table, &nested).await?;
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &nested).await?,
		None,
		"a nested-number id must have its forward mapping reclaimed like any other"
	);
	assert_eq!(
		read_shared_record_id(&ds, &docs, nested_id).await?,
		None,
		"and its reverse mapping too"
	);
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		0,
		"its marker must be consumed"
	);

	// (5) A marker in the spelling a previous release used. Its id does not
	// decode as an identity here, so the record it names is recovered through
	// the erased mapping the marker's own bytes address — and the reclaim it was
	// written for is carried out rather than forfeited. `REBUILD INDEX` does not
	// clear the doc-ID space, so a forfeited mapping would survive until the
	// table's last doc-ID index was dropped.
	let legacy = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(2))].into());
	let legacy_id = assign_shared_doc_id(&ds, &docs, &legacy).await?;
	seed_pending_reclaim_in_previous_encoding(&ds, ns, db, &table, &legacy).await?;
	let readable = RecordIdKey::from("also-gone".to_owned());
	let readable_id = assign_shared_doc_id(&ds, &docs, &readable).await?;
	seed_pending_reclaim(&ds, ns, db, &table, &readable).await?;
	assert_eq!(count_pending_reclaims(&ds, ns, db, &table).await?, 2);
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		0,
		"both spellings of a marker must be consumed, whichever the scan returned"
	);
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &legacy).await?,
		None,
		"a marker in the previous spelling must still get its mapping reclaimed"
	);
	assert_eq!(read_shared_record_id(&ds, &docs, legacy_id).await?, None, "in both directions");
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &readable).await?,
		None,
		"and the markers beside it are unaffected"
	);
	assert_eq!(read_shared_record_id(&ds, &docs, readable_id).await?, None);

	// A float whose exact expansion the index format cannot hold. Decoding the
	// marker's bytes rounds it to the nearest decimal, which does not encode back
	// to the key its mapping was written at, so only the bytes as they are find it.
	for float in [0.1, 0.7] {
		let id = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Float(float))].into());
		let doc_id = assign_shared_doc_id(&ds, &docs, &id).await?;
		seed_pending_reclaim_in_previous_encoding(&ds, ns, db, &table, &id).await?;
		ia_building.reclaim_deferred_doc_ids().await?;
		assert_eq!(
			read_shared_doc_id(&ds, &docs, &id).await?,
			None,
			"a float id's marker in the previous spelling must reclaim its mapping"
		);
		assert_eq!(read_shared_record_id(&ds, &docs, doc_id).await?, None, "in both directions");
		assert_eq!(count_pending_reclaims(&ds, ns, db, &table).await?, 0);
	}

	// A marker whose record has since lost the type-erased key. `[7]` is gone,
	// and `[7dec]`, which the previous spelling cannot tell from it, is live and
	// took the key over when it was indexed. The chain through that key leads to
	// the live record, so the marked one is reached only as another record the
	// same spelling stands for.
	let displaced = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(7))].into());
	let displaced_id = assign_shared_doc_id(&ds, &docs, &displaced).await?;
	execute_all(&ds, &session, "CREATE t:[7dec] SET a = 'alpha', b = 'beta';").await?;
	let twin = RecordIdKey::Array(
		vec![Value::Number(crate::val::Number::Decimal(rust_decimal::Decimal::from(7)))].into(),
	);
	let twin_id = read_shared_doc_id(&ds, &docs, &twin).await?.expect("the live twin is indexed");
	{
		let tx = ds.transaction(TransactionType::Read).await?;
		let erased = DocLookupKey::new(ns, db, Cow::Borrowed(&table), Cow::Borrowed(&displaced));
		let held = tx.get_key(&erased, None).await?;
		tx.cancel().await?;
		assert_eq!(held, Some(twin_id), "the premise: the twin holds the erased key");
	}
	seed_pending_reclaim_in_previous_encoding(&ds, ns, db, &table, &displaced).await?;
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &displaced).await?,
		None,
		"the marked record's own mapping must be reclaimed"
	);
	assert_eq!(read_shared_record_id(&ds, &docs, displaced_id).await?, None, "in both directions");
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &twin).await?,
		Some(twin_id),
		"and the live record the chain reached keeps its own"
	);
	assert_eq!(count_pending_reclaims(&ds, ns, db, &table).await?, 0);

	// A marker whose mapping is already gone resolves to no record. It must still
	// be consumed, or the sweep meets it again on every pass.
	seed_pending_reclaim_in_previous_encoding(&ds, ns, db, &table, &legacy).await?;
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		0,
		"an unresolvable marker must be consumed, not left to wedge the range"
	);

	// (6) A marker whose two spellings alias. Under the previous release
	// `[2, NONE]` encodes to the same bytes as `[2]` does under this one, so this
	// marker decodes cleanly — as a record it was not written for. Decoding is
	// therefore no proof of a marker's spelling, and the sweep has to follow both
	// readings or this record's mapping is stranded while its marker is consumed.
	let aliased =
		RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(2)), Value::None].into());
	let aliased_id = assign_shared_doc_id(&ds, &docs, &aliased).await?;
	seed_pending_reclaim_in_previous_encoding(&ds, ns, db, &table, &aliased).await?;
	// The premise: it decodes, and as a different record.
	{
		let tx = ds.transaction(TransactionType::Read).await?;
		let rng = DocPendingPrefix::new(ns, db, Cow::Borrowed(&table)).range()?;
		let keys = tx.keys(rng, u32::MAX, 0, None).await?;
		tx.cancel().await?;
		let decoded = DocPendingKey::decode_key(&keys[0]).expect("the aliased spelling decodes");
		assert!(
			!decoded.id.0.addresses_same_record(&aliased),
			"and decodes as a different record, which is what makes it dangerous"
		);
	}
	ia_building.reclaim_deferred_doc_ids().await?;
	assert_eq!(
		read_shared_doc_id(&ds, &docs, &aliased).await?,
		None,
		"an aliased marker must still reclaim the mapping of the record it names"
	);
	assert_eq!(read_shared_record_id(&ds, &docs, aliased_id).await?, None);
	assert_eq!(count_pending_reclaims(&ds, ns, db, &table).await?, 0);

	Ok(())
}

/// End-to-end wiring of the deferred doc-ID reclaim: a delete replayed by a
/// real builder while a sibling doc-ID index is (durably) Building must write
/// the `!dp` marker in the replay transaction, the builder's own end-of-build
/// sweep must leave it untouched (sibling still building), and a *later* doc-ID
/// index build — here a `REBUILD`, which never saw the delete — must complete
/// the reclaim from the durable marker alone.
///
/// This pins both halves of the production wiring (the defer branch in
/// `apply_appending` and the sweep call at the end of a build) and the
/// keys-survive-across-builds property that makes a late-starting or restarted
/// build a valid reclaimer.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn deferred_doc_id_reclaim_survives_across_builds() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	// ft1 indexes the records first, so every record has a shared doc-ID before
	// ft2 starts building; ft3 is a real Online doc-ID index whose durable build
	// state is forged to Building to stand in for a concurrent sibling.
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 CREATE t:1 SET a = 'alpha', b = 'x';
		 CREATE t:2 SET a = 'beta',  b = 'y';
		 CREATE t:3 SET a = 'gamma', b = 'z';
		 DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX ft3 ON t FIELDS b FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (3, 3));
	let (ns, db, table, _) = get_table_index(&ds, "t", "ft3").await?;
	let ft3_ikb = {
		let (_, _, _, ft3) = get_table_index(&ds, "t", "ft3").await?;
		IndexKeyBase::new(ns, db, table.clone(), ft3.index_id)
	};
	// Snapshot ft3's real (Online) build state so it can be restored below.
	let ft3_online = durable_build_state(&ds, &ft3_ikb).await?;

	// Start ft2's build and pause it; forge ft3 as still Building, then delete a
	// record. The delete is enqueued into ft2's replay queue, and when ft2's
	// build resumes, its replay sees a "building" sibling and defers the reclaim
	// through a durable marker; ft2's own end-of-build sweep bails on it too.
	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25 CONCURRENTLY",
	)
	.await?;
	set_durable_build_state(
		&ds,
		&ft3_ikb,
		durable_build_state_for_phase(
			IndexBuildPhase::Building,
			ft3_online.generation,
			Some(Uuid::now_v7()),
		),
	)
	.await?;
	execute_all_retrying_conflicts(&ds, &session, "DELETE t:2;").await?;
	drop(guard);
	wait_for_index_ready(&ds, &session, "t", "ft2").await?;

	// The mapping is retained (the "building" sibling may still need it) and the
	// deferral is durable.
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(3, 3),
		"the deleted record's mapping must be retained while a sibling builds"
	);
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		1,
		"the replayed delete must leave a durable pending-reclaim marker"
	);

	// Restore ft3 to its real Online state: no doc-ID index is building.
	set_durable_build_state(&ds, &ft3_ikb, ft3_online).await?;

	// A later build — a REBUILD that never saw the delete — completes the
	// reclaim from the durable marker alone.
	execute_all(&ds, &session, "REBUILD INDEX ft2 ON t;").await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(2, 2),
		"the next doc-ID index build must reclaim the deferred mapping"
	);
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		0,
		"the reclaiming sweep must consume the durable marker"
	);
	Ok(())
}

/// A queued delete whose builder never replays it must still be reclaimed: the
/// delete transaction itself writes the durable `!dp` marker at the moment the
/// central removal is deferred (see `doc::index`'s `defer_doc_id_removal`), so
/// the obligation survives the builder and its queues. Here the building index
/// is removed while paused — its queued copy of the delete is retired without
/// ever replaying — and the next doc-ID index build completes the reclaim from
/// the marker alone.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn deferred_doc_id_reclaim_survives_builder_removal() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 CREATE t:1 SET a = 'alpha', b = 'x';
		 CREATE t:2 SET a = 'beta',  b = 'y';
		 CREATE t:3 SET a = 'gamma', b = 'z';
		 DEFINE INDEX ft1 ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (3, 3));
	let (ns, db, table, _) = get_table_index(&ds, "t", "ft1").await?;

	// ft2's build is paused; the delete is enqueued into its replay queue and
	// the central removal is deferred. The delete transaction must leave the
	// durable marker immediately — before any replay runs.
	let guard = start_index_build_paused(
		&ds,
		&session,
		"DEFINE INDEX ft2 ON t FIELDS b FULLTEXT ANALYZER simple BM25 CONCURRENTLY",
	)
	.await?;
	execute_all_retrying_conflicts(&ds, &session, "DELETE t:2;").await?;
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		1,
		"the delete transaction must write the durable marker at deferral time"
	);
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (3, 3));

	// Remove ft2 while its build is still paused: the queued delete is retired
	// with the index and never replays. ft1 remains a consumer, so the shared
	// space is not purged — the marker must carry the reclaim obligation.
	execute_all_retrying_conflicts(&ds, &session, "REMOVE INDEX ft2 ON t;").await?;
	drop(guard);
	assert_eq!(
		count_pending_reclaims(&ds, ns, db, &table).await?,
		1,
		"the marker must survive a builder that never replayed the delete"
	);
	assert_eq!(count_doc_id_mappings(&ds, "t").await?, (3, 3));

	// The next doc-ID index build completes the reclaim from the marker alone.
	execute_all(&ds, &session, "REBUILD INDEX ft1 ON t;").await?;
	assert_eq!(
		count_doc_id_mappings(&ds, "t").await?,
		(2, 2),
		"the next doc-ID index build must reclaim the never-replayed delete's mapping"
	);
	assert_eq!(count_pending_reclaims(&ds, ns, db, &table).await?, 0);
	Ok(())
}

/// Runs a KNN query and returns the JSON-encoded result rows.
#[cfg(feature = "kv-mem")]
async fn knn_result(ds: &Datastore, session: &Session, sql: &str) -> Result<String> {
	let mut responses = ds.execute(sql, session, None).await?;
	let value = responses.remove(0).result?;
	Ok(value.into_json_value().to_string())
}

/// A record deleted and re-created before HNSW compaction must remain visible
/// to KNN search. The record-keyed pending captures the pre-delete doc-ID; the
/// delete removes that shared mapping, so a pending hit emitted under the
/// captured id could not be resolved back to a record and would be silently
/// dropped. The pending search must emit the surviving vectors under the record
/// key instead (see `search_pendings`).
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn hnsw_pending_search_returns_recreated_record() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	// The full-text index assigns the shared doc-ID at write time, so the HNSW
	// record pending captures it (`doc_id: Some(..)`).
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 4 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET a = 'alpha', vec = [1.0, 0.0, 0.0, 0.0];",
	)
	.await?;

	// Delete (drops the shared mapping) then re-create before any compaction:
	// the coalesced record pending still carries the stale captured doc-ID.
	// NB: no KNN query runs before this point — resolving the captured id while
	// its mapping is still live would warm the process-local doc-ID cache and
	// mask the stale-mapping resolution this test pins down.
	execute_all(
		&ds,
		&session,
		"DELETE t:1;
		 CREATE t:1 SET a = 'alpha', vec = [1.0, 0.0, 0.0, 0.0];",
	)
	.await?;
	let knn = "SELECT id FROM t WHERE vec <|1,40|> [1.0, 0.0, 0.0, 0.0];";
	assert!(
		knn_result(&ds, &session, knn).await?.contains("t:1"),
		"a record re-created before compaction must remain visible to KNN"
	);
	Ok(())
}

/// DiskANN counterpart of
/// [`hnsw_pending_search_returns_recreated_record`]: the sharded pending search
/// must emit a re-created record's vectors under the record key, not the stale
/// captured doc-ID.
#[cfg(all(feature = "kv-mem", diskann))]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn diskann_pending_search_returns_recreated_record() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ft ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 DEFINE INDEX dx ON t FIELDS vec DISKANN DIMENSION 4 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET a = 'alpha', vec = [1.0, 0.0, 0.0, 0.0];",
	)
	.await?;
	// NB: no KNN query runs before the delete — see the HNSW counterpart for
	// why (a warm doc-ID cache would mask the stale-mapping resolution).
	execute_all(
		&ds,
		&session,
		"DELETE t:1;
		 CREATE t:1 SET a = 'alpha', vec = [1.0, 0.0, 0.0, 0.0];",
	)
	.await?;
	let knn = "SELECT id FROM t WHERE vec <|1,40|> [1.0, 0.0, 0.0, 0.0];";
	assert!(
		knn_result(&ds, &session, knn).await?.contains("t:1"),
		"a record re-created before compaction must remain visible to KNN"
	);
	Ok(())
}

/// A shutdown-class commit failure must not poison the durable build state.
///
/// Reproduces the incident behind the PR #553 regression report: the storage
/// engine begins graceful shutdown while a build is mid-scan, the batch
/// commit fails with the engines' shutdown error, and the builder task dies.
/// Durable state must stay `Building` — with no durable error — so the
/// periodic resume scan adopts the build after restart and finishes it.
/// Before this fix the state was durably `Error`, the resume scan skipped it
/// forever, and every write to the table failed on admission with the stale
/// shutdown message.
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_error_does_not_poison_durable_build_state() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
			",
	)
	.await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	// Fail the rebuild's first initial-scan batch commit with the error the
	// storage engines return once graceful shutdown has begun.
	let _guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexInitialBatchShutdown,
		ds.id(),
	);
	// A blocking REBUILD surfaces the builder task's failure synchronously.
	let err = ds
		.execute("REBUILD INDEX test ON user", &session, None)
		.await?
		.remove(0)
		.result
		.expect_err("rebuild should fail with the injected shutdown error");
	assert!(err.to_string().contains("shutting down"), "unexpected rebuild error: {err}");

	// The interrupted generation stays adoptable: still `Building`, no
	// durable error, no error report status.
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Building);
	assert_eq!(state.error, None);
	assert_eq!(state.report_status, Some(IndexBuildReportStatus::Indexing));

	// Writes are still admitted (queued) while the build awaits adoption.
	execute_all_retrying_conflicts(
		&ds,
		&session,
		"CREATE user:three SET email = 'three@example.com' RETURN NONE",
	)
	.await?;

	// Expire the dead builder's lease; the periodic resume scan must adopt
	// the generation and drive the build to `Online`.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let mut stranded = durable_build_state(&ds, &ikb).await?;
	stranded.updated_at = expired;
	stranded.owner_heartbeat_at = Some(expired);
	set_durable_build_state(&ds, &ikb, stranded).await?;
	let resumed = ds
		.resume_stalled_index_builds(
			Duration::from_secs(30),
			tokio_util::sync::CancellationToken::new(),
		)
		.await?;
	assert_eq!(resumed, 1, "the interrupted build should be adopted");
	wait_for_index_ready(&ds, &session, "user", "test").await?;
	Ok(())
}

/// A genuine (non-shutdown) build failure must still publish a durable error:
/// the shutdown classification must not swallow real failures.
#[tokio::test(flavor = "multi_thread")]
async fn non_shutdown_build_error_still_publishes_durable_error() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
			",
	)
	.await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	let _guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexInitialBatchCommit,
		ds.id(),
	);
	let err = ds
		.execute("REBUILD INDEX test ON user", &session, None)
		.await?
		.remove(0)
		.result
		.expect_err("rebuild should fail with the injected error");
	assert!(err.to_string().contains("injected non-retryable error"), "unexpected error: {err}");

	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Error);
	assert_eq!(state.report_status, Some(IndexBuildReportStatus::Error));
	assert!(
		state.error.as_deref().is_some_and(|e| e.contains("injected non-retryable error")),
		"durable error should carry the failure reason: {:?}",
		state.error
	);

	// A failed build must not block user writes: the mutation queues under
	// the errored generation instead of failing the statement.
	execute_all_retrying_conflicts(
		&ds,
		&session,
		"CREATE user:three SET email = 'three@example.com' RETURN NONE",
	)
	.await?;

	// A `REBUILD INDEX` recovers from the durable error state by starting a
	// fresh generation (the documented operator remediation), and its rescan
	// indexes the write that was admitted while the build was errored.
	execute_all(&ds, &session, "REBUILD INDEX test ON user").await?;
	assert_eq!(index_building_status(&ds, &session, "user", "test").await?, "ready");
	assert_eq!(
		index_prefix_key_count(&ds, ns, db, &table, ix.index_id).await?,
		3,
		"the rebuild rescan must index the write admitted during the error state"
	);
	Ok(())
}

#[test]
fn shutdown_error_classification() {
	use crate::kvs::is_shutdown_error;
	let direct: anyhow::Error = crate::kvs::Error::Shutdown.into();
	assert!(is_shutdown_error(&direct));
	let wrapped: anyhow::Error = Error::Kvs(crate::kvs::Error::Shutdown).into();
	assert!(is_shutdown_error(&wrapped));
	let internal: anyhow::Error = crate::kvs::Error::Internal("boom".to_string()).into();
	assert!(!is_shutdown_error(&internal));
	let conflict: anyhow::Error = crate::kvs::Error::TransactionConflict("busy".to_string()).into();
	assert!(!is_shutdown_error(&conflict));
}

/// A memory-threshold failure must not poison the durable build state.
///
/// On memory-constrained instances the builder can cross the process memory
/// threshold mid-scan (`Building::is_beyond_threshold`). That is a
/// load-transient condition, so — like a shutdown — it must leave the build
/// adoptable: durable state stays `Building` with its checkpoint, and the
/// resume scan retries the build once the owner lease expires (typically
/// after the pressure has receded or the instance was resized). Before this
/// fix the build was durably `Error` and every write to the table failed on
/// admission.
#[tokio::test(flavor = "multi_thread")]
async fn memory_threshold_error_does_not_poison_durable_build_state() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			CREATE user:two SET email = 'two@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email CONCURRENTLY;
			",
	)
	.await?;
	wait_for_index_ready(&ds, &session, "user", "test").await?;

	// Fail the rebuild's first initial-scan batch commit with the error the
	// builder raises when the process crosses the memory threshold.
	let _guard = inject_non_retryable_error(
		NonRetryableErrorSite::ConcurrentIndexInitialBatchMemoryThreshold,
		ds.id(),
	);
	let err = ds
		.execute("REBUILD INDEX test ON user", &session, None)
		.await?
		.remove(0)
		.result
		.expect_err("rebuild should fail with the injected memory threshold error");
	assert!(err.to_string().contains("memory threshold"), "unexpected rebuild error: {err}");

	// The interrupted generation stays adoptable: still `Building`, no
	// durable error, no error report status.
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Building);
	assert_eq!(state.error, None);
	assert_eq!(state.report_status, Some(IndexBuildReportStatus::Indexing));

	// Expire the dead builder's lease; the resume scan retries the build.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let mut stranded = durable_build_state(&ds, &ikb).await?;
	stranded.updated_at = expired;
	stranded.owner_heartbeat_at = Some(expired);
	set_durable_build_state(&ds, &ikb, stranded).await?;
	let resumed = ds
		.resume_stalled_index_builds(
			Duration::from_secs(30),
			tokio_util::sync::CancellationToken::new(),
		)
		.await?;
	assert_eq!(resumed, 1, "the interrupted build should be adopted");
	wait_for_index_ready(&ds, &session, "user", "test").await?;
	Ok(())
}

/// The resume scan recovers several stranded builds one at a time.
///
/// A restart with multiple stalled builds (the incident shape: two FULLTEXT
/// indexes on a small instance) must not start every initial scan at once:
/// a pass adopts at most one build, and no pass adopts anything while a
/// local builder task is still running. Every stalled build is still
/// recovered — one scan pass after the previous build finishes.
#[tokio::test(flavor = "multi_thread")]
async fn resume_scan_adopts_one_stalled_build_at_a_time() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com', name = 'One' RETURN NONE;
			CREATE user:two SET email = 'two@example.com', name = 'Two' RETURN NONE;
			DEFINE INDEX test_email ON user FIELDS email;
			DEFINE INDEX test_name ON user FIELDS name;
			",
	)
	.await?;

	// Strand both indexes as expired `Building` generations, as a crash mid
	// build of both would leave them.
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let mut ikbs = Vec::new();
	for index in ["test_email", "test_name"] {
		let (ns, db, table, ix) = get_table_index(&ds, "user", index).await?;
		let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
		let tx = ds.transaction(TransactionType::Write).await?;
		tx.del_prefix_key(&IdxRoot {
			ns,
			db,
			tb: Cow::Borrowed(&table),
			ix: ix.index_id,
		})
		.await?;
		tx.set_key(
			&ikb.new_bs_key(),
			&IndexBuildState {
				generation: 2,
				phase: IndexBuildPhase::Building,
				owner: Some(Uuid::new_v4()),
				next_ticket: 0,
				initial_complete: false,
				updated_at: expired,
				owner_heartbeat_at: Some(expired),
				error: None,
				report_status: Some(IndexBuildReportStatus::Indexing),
				initial: Some(0),
				updated: None,
				pending: None,
				initial_cursor: None,
			},
		)
		.await?;
		tx.commit().await?;
		ikbs.push(ikb);
	}

	// Park whichever build gets adopted in its batch-commit retry loop, so
	// the deferral while a build is running can be observed deterministically.
	let guard = inject_retryable_conflicts(
		RetryableConflictSite::ConcurrentIndexInitialBatch,
		ds.id(),
		REPEATED_RETRY_CONFLICTS,
	);

	// The first pass adopts exactly one of the two stranded builds.
	let resumed = ds
		.resume_stalled_index_builds(
			Duration::from_secs(30),
			tokio_util::sync::CancellationToken::new(),
		)
		.await?;
	assert_eq!(resumed, 1, "a pass must adopt at most one stalled build");

	// Wait until the adopted build is demonstrably mid-scan (it consumed an
	// injected conflict), then verify a pass adopts nothing while it runs.
	timeout(Duration::from_secs(10), async {
		while retryable_conflict_count(RetryableConflictSite::ConcurrentIndexInitialBatch, ds.id())
			== REPEATED_RETRY_CONFLICTS
		{
			sleep(Duration::from_millis(5)).await;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("adopted build never reached its batch commit"))?;
	let resumed_while_running = ds
		.resume_stalled_index_builds(
			Duration::from_secs(30),
			tokio_util::sync::CancellationToken::new(),
		)
		.await?;
	assert_eq!(resumed_while_running, 0, "no adoption while a local build is running");

	// Un-park the running build and let recovery converge: a later pass
	// adopts the second build, and both indexes come back ready.
	drop(guard);
	let deadline = Instant::now() + Duration::from_secs(30);
	loop {
		let mut online = 0;
		for ikb in &ikbs {
			if durable_build_state(&ds, ikb).await?.phase == IndexBuildPhase::Online {
				online += 1;
			}
		}
		if online == 2 {
			break;
		}
		assert!(Instant::now() < deadline, "stranded builds were not recovered sequentially");
		let _ = ds
			.resume_stalled_index_builds(
				Duration::from_secs(30),
				tokio_util::sync::CancellationToken::new(),
			)
			.await?;
		sleep(Duration::from_millis(20)).await;
	}
	assert_eq!(index_building_status(&ds, &session, "user", "test_email").await?, "ready");
	assert_eq!(index_building_status(&ds, &session, "user", "test_name").await?, "ready");
	Ok(())
}

/// A new-generation takeover installs the next generation BEFORE it waits
/// for prior-generation reservations, and wipes the stale queues after.
///
/// With `Error` builds admitting writers like `Building`, draining before
/// the flip would race a writer that reserves a ticket between the drain and
/// the state commit: its queued mutation would be wiped while its main-table
/// write could land after the new initial scan had already passed the
/// record. Installing the generation first fences those admissions (ticket
/// allocation CASes `!bs` and the fence rejects generation mismatches), so
/// the drain's empty state is stable.
#[tokio::test(flavor = "multi_thread")]
async fn takeover_installs_generation_before_draining_reservations() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Seed an errored generation 1 with a live writer reservation (TTL in the
	// future, so the drain must wait) and a stale queue entry.
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 1,
			phase: IndexBuildPhase::Error,
			owner: None,
			next_ticket: 1,
			initial_complete: false,
			updated_at: Utc::now(),
			owner_heartbeat_at: None,
			error: Some("seeded test failure".to_string()),
			report_status: Some(IndexBuildReportStatus::Error),
			initial: None,
			updated: None,
			pending: None,
			initial_cursor: None,
		},
	)
	.await?;
	let br_key = ikb.new_br_key(1, 0);
	tx.set_key(
		&br_key,
		&IndexBuildReservation {
			node: ds.id(),
			expires_at: Utc::now() + chrono::Duration::seconds(BUILD_RESERVATION_TTL_SECS),
		},
	)
	.await?;
	// A different ticket than the live reservation: a queue entry under the
	// same ticket would mark that writer as already committed and let the
	// drain retire the reservation instead of blocking on it.
	tx.set_key(
		&ikb.new_bg_key(1, 5, 0),
		&Appending {
			old_values: None,
			new_values: None,
			id: RecordIdKey::from("one".to_string()),
			count_cond_match: None,
		},
	)
	.await?;
	tx.commit().await?;

	// The takeover must block draining the live reservation...
	let building =
		Arc::new(new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?);
	let acquire = {
		let building = Arc::clone(&building);
		tokio::spawn(async move { building.acquire_build_state().await })
	};
	// ...but only after the next generation is already installed, fencing
	// off further old-generation admissions while it waits.
	timeout(Duration::from_secs(5), async {
		while durable_build_state(&ds, &ikb).await?.generation != 2 {
			sleep(Duration::from_millis(10)).await;
		}
		Ok::<_, anyhow::Error>(())
	})
	.await
	.map_err(|_| anyhow::anyhow!("takeover never installed the next generation"))??;
	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Building);
	sleep(Duration::from_millis(200)).await;
	assert!(
		!acquire.is_finished(),
		"acquire must keep draining the live prior-generation reservation"
	);

	// Releasing the writer's reservation lets the takeover finish, and the
	// stale generation-1 queue entries are wiped.
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_key(&br_key).await?;
	tx.commit().await?;
	let acquired = timeout(Duration::from_secs(5), acquire)
		.await
		.map_err(|_| {
			anyhow::anyhow!("acquire did not finish after the reservation was released")
		})???
		.expect("takeover should acquire the new generation");
	assert_eq!(acquired.generation, 2);
	let tx = ds.transaction(TransactionType::Read).await?;
	let stale_bg = tx.keys(ikb.new_bg_all_generations_range()?, u32::MAX, 0, None).await?;
	let stale_br = tx.keys(ikb.new_br_all_generations_range()?, u32::MAX, 0, None).await?;
	tx.cancel().await?;
	assert!(stale_bg.is_empty(), "stale generation-1 queue entries should be wiped");
	assert!(stale_br.is_empty(), "no reservations should remain after the takeover");
	Ok(())
}

/// Budget for the under-load phase of [`concurrent_build_under_table_writes`].
///
/// Every arm shares it: a control given a larger budget than the arms it is a
/// control for stops establishing that the harness completes a build at this
/// write rate. Unstarved runs finish the scan in a couple of seconds, so the
/// margin is for loaded CI. These are liveness tests, not throughput tests.
const BUILD_UNDER_WRITES_TIMEOUT: Duration = Duration::from_secs(45);

/// Budget for publishing once the writer has stopped.
const BUILD_PUBLISH_TIMEOUT: Duration = Duration::from_secs(30);

/// Outcome of a [`concurrent_build_under_table_writes`] run.
struct BuildUnderWritesOutcome {
	/// Whether the scan covered every seeded record while the writer ran.
	scan_progressed: bool,
	/// Whether the index published `Online` once the writer stopped.
	published: bool,
	/// Highest `initial` counter the durable state reported.
	max_initial: u64,
	/// Highest writer ticket allocated while the build was still `Building`.
	/// Zero means the writes never produced an index mutation, so they never
	/// entered admission. Sampling stops at `Closing`, whose transition
	/// advances the counter itself to fence in-flight allocations.
	max_ticket: u64,
	/// Writes the writer committed while the build ran.
	committed: u64,
}

/// Drive a concurrent FULLTEXT build while the table it indexes takes writes at
/// a sustained rate, and report whether the initial scan ever completes.
///
/// `writer_sql` decides the shape of the concurrent write. The build is only
/// defined once the writer is demonstrably committing, so the scan starts
/// against established load instead of racing the writer's ramp-up. The writer
/// runs for the whole build and is stopped before the assertions.
async fn concurrent_build_under_table_writes(
	writer_sql: fn(u64) -> String,
	scan_timeout: Duration,
) -> Result<BuildUnderWritesOutcome> {
	/// Records seeded before the build starts. An unstarved build indexes
	/// these in a couple of seconds, so the timeout is a wide margin.
	const RECORDS: usize = 4000;
	/// Writes the writer must commit before the build is defined.
	const WRITES_BEFORE_BUILD: u64 = 50;

	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE doc SCHEMALESS;
			DEFINE ANALYZER simple TOKENIZERS blank,class FILTERS lowercase;
			",
	)
	.await?;
	execute_all(
		&ds,
		&session,
		&format!(
			"CREATE |doc:1..{RECORDS}| SET text = string::repeat('lorem ipsum dolor sit amet \
			 consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore ', 4) + \
			 <string>id RETURN NONE"
		),
	)
	.await?;

	let stop = Arc::new(AtomicBool::new(false));
	let committed = Arc::new(AtomicU64::new(0));
	let writer = {
		let ds = Arc::clone(&ds);
		let session = session.clone();
		let stop = Arc::clone(&stop);
		let committed = Arc::clone(&committed);
		tokio::spawn(async move {
			let mut n = 0u64;
			while !stop.load(Ordering::Relaxed) {
				n += 1;
				// Statement-level conflicts are expected under this load and are
				// not what these tests are about; only committed writes count as
				// pressure the builder has to make progress against.
				if execute_all(&ds, &session, &writer_sql(n)).await.is_ok() {
					committed.fetch_add(1, Ordering::Relaxed);
				}
				sleep(Duration::from_millis(1)).await;
			}
		})
	};

	timeout(Duration::from_secs(10), async {
		while committed.load(Ordering::Relaxed) < WRITES_BEFORE_BUILD {
			sleep(Duration::from_millis(5)).await;
		}
	})
	.await
	.map_err(|_| anyhow::anyhow!("the writer never reached the pre-build write threshold"))?;

	// The writer touches the table definition's cached index list, so the
	// schema statement can hit statement-level conflicts under this load.
	execute_all_retrying_conflicts(
		&ds,
		&session,
		"DEFINE INDEX ft ON doc FIELDS text FULLTEXT ANALYZER simple BM25(1.2,0.75) HIGHLIGHTS \
		 CONCURRENTLY",
	)
	.await?;

	let (ns, db, table, ix) = get_table_index(&ds, "doc", "ft").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);

	// Phase one, the starvation check: with the writer at full rate the scan
	// must cover at least every seeded record. A starved build sits at zero.
	//
	// The threshold is a count rather than completion because an insert writer
	// keeps extending the scanned range, so "the scan finished" is not a fixed
	// target and a fast enough writer can outrun it indefinitely on slower
	// hardware. Covering the seeded records is bounded and is what
	// distinguishes progress from starvation.
	let mut max_initial = 0u64;
	let mut max_ticket = 0u64;
	let progressed = timeout(scan_timeout, async {
		loop {
			let (state, ticket) = durable_build_state_with_ticket_counter(&ds, &ikb).await?;
			max_initial = max_initial.max(state.initial.unwrap_or(0));
			// Tickets are allocated from the generation's `!bt` counter;
			// `next_ticket` only advances for a generation that predates it.
			// Reading the build state alone would report zero for every
			// admission and make the control assertion below vacuous.
			//
			// Only sample while the build is still `Building`: the transition
			// out of it advances the counter itself, to fence allocations in
			// flight, and that bump is not a writer admission. Phase and
			// counter therefore have to come from one snapshot, which `state`
			// above provides — the fence writes both keys in a single
			// transaction, so two reads can pair a `Building` phase with the
			// post-fence counter and report that bump as an admission.
			if state.phase == IndexBuildPhase::Building {
				max_ticket = max_ticket.max(ticket.unwrap_or(state.next_ticket));
			}
			if max_initial >= RECORDS as u64 || state.phase == IndexBuildPhase::Online {
				return Ok::<_, anyhow::Error>(());
			}
			sleep(Duration::from_millis(20)).await;
		}
	})
	.await;

	stop.store(true, Ordering::Relaxed);
	let _ = writer.await;

	// `timeout` nests the polling result inside its own, so only the outer
	// error means "it did not happen in time". A failure reading durable state
	// is a broken test rather than a starved build, and collapsing the two
	// would let these tests pass without ever observing progress.
	let scan_progressed = match progressed {
		Ok(Ok(())) => true,
		Ok(Err(err)) => return Err(err),
		Err(_elapsed) => false,
	};

	// Phase two: with the writer stopped the build must reach `Online`. The
	// writer is stopped first so the target is bounded — `Closing` under live
	// write pressure is covered deterministically by
	// `closing_transition_fences_in_flight_ticket_allocation`, and folding both
	// into one timing-sensitive test is what made this one fragile on slower
	// runners.
	let published = timeout(BUILD_PUBLISH_TIMEOUT, async {
		loop {
			let state = durable_build_state(&ds, &ikb).await?;
			max_initial = max_initial.max(state.initial.unwrap_or(0));
			if state.phase == IndexBuildPhase::Online {
				return Ok::<_, anyhow::Error>(());
			}
			sleep(Duration::from_millis(20)).await;
		}
	})
	.await;
	let published = match published {
		Ok(Ok(())) => true,
		Ok(Err(err)) => return Err(err),
		Err(_elapsed) => false,
	};

	let committed = committed.load(Ordering::Relaxed);
	assert!(
		committed > 100,
		"the writer only committed {committed} writes — too little load for this test to mean \
		 anything"
	);
	Ok(BuildUnderWritesOutcome {
		scan_progressed,
		published,
		max_initial,
		max_ticket,
		committed,
	})
}

/// Control for the two starvation tests below: writes that do not touch an
/// indexed field must not disturb the build.
///
/// Such a write produces no index mutation, so it never enters writer
/// admission and never allocates a ticket — asserted here, so the test cannot
/// silently become a vacuous "writes are harmless" claim. It establishes that
/// the harness drives a build to completion at this write rate, which is what
/// makes the two failures below attributable to admission rather than to load.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_build_is_unaffected_by_writes_that_miss_the_index() -> Result<()> {
	let outcome = concurrent_build_under_table_writes(
		|n| format!("UPDATE doc:{} SET untracked = {n} RETURN NONE", n % 25 + 1),
		BUILD_UNDER_WRITES_TIMEOUT,
	)
	.await?;
	assert_eq!(
		outcome.max_ticket, 0,
		"writes that miss the index must not enter admission (allocated {} tickets)",
		outcome.max_ticket
	);
	assert!(
		outcome.scan_progressed,
		"the scan stalled under {} writes that miss the index: {}/4000 records",
		outcome.committed, outcome.max_initial
	);
	assert!(outcome.published, "the build did not publish after the writer stopped");
	Ok(())
}

/// A concurrent index build must keep making progress while the table it is
/// indexing takes writes that mutate the indexed field.
///
/// Every write that produces an index mutation allocates a durable admission
/// ticket, and that allocation is a compare-and-swap on the index's single
/// `!bs` build-state key. The builder's initial-scan batch reads and
/// CAS-writes that same key twice in one transaction — the ownership heartbeat
/// before the batch and the progress checkpoint after it — and holds that
/// transaction open across the whole batch, analysis included. Any admitted
/// write committing inside that window invalidates the builder's CAS, so the
/// entire batch is discarded and retried after a fixed backoff.
///
/// Once a batch is long relative to the write inter-arrival time the builder
/// loses every race: the initial scan never commits, the durable counter never
/// advances, and each failed attempt still pays the full analysis and
/// write-set cost for the batch. The stall also makes the generation look
/// abandoned, because the heartbeat rides on the discarded transaction — a
/// starved builder never refreshes `owner_heartbeat_at`, so its lease expires
/// while the task is still running, leaving the generation open to a takeover
/// that restarts the scan from its last committed checkpoint, or from zero
/// when no batch of that generation ever committed.
///
/// Asserted in two phases. With the writer at full rate the scan must cover
/// every seeded record — a starved build sits at zero, which is the defect.
/// The writer is then stopped and the build must reach `Online`, which covers
/// `Closing`, the reservation drain and the publish.
///
/// Progress is a count rather than "the scan finished" because an insert writer
/// keeps extending the scanned range, so completion is not a fixed target and a
/// fast writer can outrun it indefinitely on slower hardware.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_build_publishes_under_indexed_updates() -> Result<()> {
	let outcome = concurrent_build_under_table_writes(
		|n| format!("UPDATE doc:{} SET text = 'changed payload {n}' RETURN NONE", n % 25 + 1),
		BUILD_UNDER_WRITES_TIMEOUT,
	)
	.await?;
	assert!(
		outcome.max_ticket > 0,
		"indexed updates must enter writer admission, otherwise this test exercises nothing"
	);
	assert!(
		outcome.scan_progressed,
		"the scan stalled under {} indexed updates ({} tickets allocated): it indexed {}/4000 \
		 records",
		outcome.committed, outcome.max_ticket, outcome.max_initial
	);
	assert!(outcome.published, "the build did not publish after the writer stopped");
	Ok(())
}

/// The insert-shaped counterpart of
/// [`concurrent_build_publishes_under_indexed_updates`], and the
/// shape reported from production: `RELATE` inserts new edge records, so a
/// RELATION table under normal traffic starves any build against it.
///
/// Kept separate because an insert also extends the scanned key range and
/// creates a fresh doc-ID mapping, so it exercises more of the write path than
/// an in-place update of an indexed field.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_build_publishes_under_indexed_inserts() -> Result<()> {
	let outcome = concurrent_build_under_table_writes(
		|n| format!("CREATE doc:w{n} SET text = 'writer payload {n}' RETURN NONE"),
		BUILD_UNDER_WRITES_TIMEOUT,
	)
	.await?;
	assert!(
		outcome.max_ticket > 0,
		"indexed inserts must enter writer admission, otherwise this test exercises nothing"
	);
	assert!(
		outcome.scan_progressed,
		"the scan stalled under {} indexed inserts ({} tickets allocated): it indexed {}/4000 \
		 records",
		outcome.committed, outcome.max_ticket, outcome.max_initial
	);
	assert!(outcome.published, "the build did not publish after the writer stopped");
	Ok(())
}

/// Read the ticket counter of one build generation, if it exists.
async fn durable_ticket_counter(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	generation: BuildGeneration,
) -> Result<Option<BuildTicket>> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let counter = catch!(tx, tx.get_key(&ikb.new_bt_key(generation), None).await);
	tx.cancel().await?;
	Ok(counter)
}

/// The active generation always owns a `!bt` ticket counter, and installing the
/// next generation removes the previous one.
///
/// Writer admission compare-and-swaps this counter, so both halves matter: the
/// key must exist for a writer to CAS, and the flip must remove it under a
/// conditional delete so an in-flight allocation conflicts instead of landing a
/// reservation against a generation that is no longer current.
#[tokio::test(flavor = "multi_thread")]
async fn generation_flip_rotates_the_ticket_counter() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);

	let first = durable_build_state(&ds, &ikb).await?.generation;
	assert!(
		durable_ticket_counter(&ds, &ikb, first).await?.is_some(),
		"the active generation must own a ticket counter for admission to CAS"
	);

	execute_all(&ds, &session, "REBUILD INDEX test ON user").await?;

	let second = durable_build_state(&ds, &ikb).await?.generation;
	assert_eq!(second, first.saturating_add(1));
	assert!(
		durable_ticket_counter(&ds, &ikb, second).await?.is_some(),
		"the rebuilt generation must own a ticket counter"
	);
	assert!(
		durable_ticket_counter(&ds, &ikb, first).await?.is_none(),
		"the flip must remove the previous generation's counter, which is what fences writers \
		 still admitting under it"
	);

	// Retiring the index clears every generation's counter along with the
	// rest of the durable build state.
	execute_all(&ds, &session, "REMOVE INDEX test ON user").await?;
	assert!(durable_ticket_counter(&ds, &ikb, second).await?.is_none());
	Ok(())
}

/// A generation that predates the `!bt` counter keeps allocating tickets from
/// `!bs.next_ticket`.
///
/// This is the upgrade path: a build already in flight when the node restarts
/// on a version that owns a counter has no `!bt`, and must keep issuing tickets
/// exactly as before rather than restarting the sequence from zero and reusing
/// reservations. Such a build only moves to the counter at its next generation.
#[tokio::test(flavor = "multi_thread")]
async fn admission_falls_back_to_build_state_ticket_without_a_counter() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table, ix.index_id);

	// Recreate a pre-counter build: `Building` with a ticket sequence already
	// part-way through, and no `!bt` for the generation.
	let generation = durable_build_state(&ds, &ikb).await?.generation;
	let mut legacy = durable_build_state_for_phase(IndexBuildPhase::Building, generation, None);
	legacy.next_ticket = 7;
	set_durable_build_state(&ds, &ikb, legacy).await?;
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_key(&ikb.new_bt_key(generation)).await?;
	tx.commit().await?;

	execute_all_retrying_conflicts(
		&ds,
		&session,
		"UPDATE user:one SET email = 'changed@example.com' RETURN NONE",
	)
	.await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(
		state.next_ticket, 8,
		"a generation without a counter must advance the build state's own ticket"
	);
	assert!(
		durable_ticket_counter(&ds, &ikb, generation).await?.is_none(),
		"the legacy path must not create a counter mid-generation: nodes still running the \
		 previous version would keep allocating from `!bs.next_ticket` and collide with it"
	);
	Ok(())
}

/// Entering `Closing` must invalidate a ticket allocation that is already in
/// flight.
///
/// Admission reads the phase, allocates from the generation's counter, and
/// commits its `!br` reservation. If `Closing` could commit in between, the
/// reservation could land after the drain that follows had already seen an
/// empty range, and the writer's fence — which queues on `Closing` — would
/// write a `!bg` entry after the final replay pass. The build would then
/// publish `Online` having never applied that mutation.
///
/// The phase transition therefore rewrites the counter in its own transaction,
/// so the in-flight allocation loses the race and retries against `Closing`.
#[tokio::test(flavor = "multi_thread")]
async fn closing_transition_fences_in_flight_ticket_allocation() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// Strand a `Building` generation with an expired lease and a counter that
	// has already issued tickets, then take it over so the transition below is
	// owned by this builder.
	const GENERATION: BuildGeneration = 9;
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let mut state = durable_build_state_for_phase(IndexBuildPhase::Building, GENERATION, None);
	state.updated_at = expired;
	state.owner_heartbeat_at = Some(expired);
	set_durable_build_state(&ds, &ikb, state).await?;
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(&ikb.new_bt_key(GENERATION), &5u64).await?;
	tx.commit().await?;

	let build = new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("the expired generation should be available for takeover");
	assert_eq!(acquired.generation, GENERATION);

	// A writer mid-admission: it has allocated ticket 5 but not yet committed.
	let writer = ds.transaction(TransactionType::Write).await?;
	let bt = ikb.new_bt_key(GENERATION);
	let ticket = catch!(writer, writer.get_key(&bt, None).await).expect("counter should exist");
	assert_eq!(ticket, 5);
	catch!(writer, writer.put_compare_key(&bt, &(ticket + 1), Some(&ticket)).await);

	// The build closes while that allocation is still open.
	build.mark_durable_closing(GENERATION).await?;
	assert_eq!(durable_build_state(&ds, &ikb).await?.phase, IndexBuildPhase::Closing);

	assert!(
		writer.commit().await.is_err(),
		"a ticket allocation in flight across the `Closing` transition must not commit: its \
		 reservation could land after the drain and be missed"
	);
	Ok(())
}

/// Drive a takeover of a fabricated `Building` generation to completion and
/// return the result, so the publish-time checks can be exercised directly.
#[allow(clippy::too_many_arguments)]
async fn run_takeover_of_generation(
	ds: &Datastore,
	session: &Session,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
	ix: Arc<IndexDefinition>,
	generation: BuildGeneration,
	next_ticket: BuildTicket,
	counter: Option<BuildTicket>,
) -> Result<Result<()>> {
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let mut state = durable_build_state_for_phase(IndexBuildPhase::Building, generation, None);
	state.next_ticket = next_ticket;
	state.initial_complete = false;
	state.updated_at = expired;
	state.owner_heartbeat_at = Some(expired);
	set_durable_build_state(ds, &ikb, state).await?;

	let tx = ds.transaction(TransactionType::Write).await?;
	match counter {
		Some(counter) => tx.set_key(&ikb.new_bt_key(generation), &counter).await?,
		None => tx.del_key(&ikb.new_bt_key(generation)).await?,
	}
	tx.commit().await?;

	let build = new_building_for_index(ds, session, ns, db, table, ix).await?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("the expired generation should be available for takeover");
	assert_eq!(acquired.generation, generation);
	Ok(build.run_acquired(acquired).await)
}

/// A generation whose tickets were issued by two different allocators must not
/// be published.
///
/// A `!bt` counter alongside a non-zero `next_ticket` is proof that a node
/// predating the counter allocated against this generation. The two sequences
/// both start at zero and never conflict, so they can issue the same ticket and
/// one writer's queued mutation silently overwrites the other's. Publishing
/// would leave an index reporting `ready` while missing writes, so the build
/// fails and points at `REBUILD INDEX` instead.
#[tokio::test(flavor = "multi_thread")]
async fn cross_version_ticket_allocation_blocks_publishing() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	let result =
		run_takeover_of_generation(&ds, &session, ns, db, &table, ix, 4, 3, Some(7)).await?;

	let err = result.expect_err("a generation with two ticket allocators must not publish");
	let message = err.to_string();
	assert!(
		message.contains("REBUILD INDEX test ON user"),
		"the failure must tell the operator how to recover, got: {message}"
	);
	assert_ne!(
		durable_build_state(&ds, &ikb).await?.phase,
		IndexBuildPhase::Online,
		"the index must not be queryable when its queue may have lost mutations"
	);
	Ok(())
}

/// A generation that predates the counter still publishes normally.
///
/// Such a build legitimately advances `next_ticket`, and has no `!bt`. Treating
/// that as a cross-version collision would fail every build that was already
/// running when the node was upgraded.
#[tokio::test(flavor = "multi_thread")]
async fn legacy_generation_with_advanced_ticket_still_publishes() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	run_takeover_of_generation(&ds, &session, ns, db, &table, ix, 4, 3, None).await??;

	assert_eq!(durable_build_state(&ds, &ikb).await?.phase, IndexBuildPhase::Online);
	Ok(())
}

/// Installing a new generation must invalidate a ticket allocation that is
/// already in flight against the previous one.
///
/// The flip removes the previous generation's counter under a conditional
/// delete, in the same transaction that installs the new state. That is the
/// whole fence: allocation compare-and-swaps that counter, so a writer holding
/// an open allocation loses and retries against the new generation.
///
/// Without it the writer's `!br` can commit *after* the flip — in the window
/// while `wait_for_prior_generation_reservations` is draining — so the drain
/// can return on an empty range that the late reservation then repopulates.
/// The stale-queue wipe that follows destroys the writer's `!bg` while its
/// main-table write survives, and the new scan may already have passed that
/// record.
///
/// The later sweep in `delete_stale_build_queues` also removes the counter, so
/// a test that only checks it is eventually gone passes either way. This one
/// asserts the timing: gone *by the time the flip commits*.
#[tokio::test(flavor = "multi_thread")]
async fn generation_flip_fences_in_flight_ticket_allocation() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"
			DEFINE TABLE user SCHEMALESS;
			CREATE user:one SET email = 'one@example.com' RETURN NONE;
			DEFINE INDEX test ON user FIELDS email;
			",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "user", "test").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);

	// An errored generation 1 that still owns its counter, plus a live
	// reservation so the takeover's drain blocks after the flip. That pause is
	// the window a late allocation would otherwise slip through.
	let br_key = ikb.new_br_key(1, 0);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 1,
			phase: IndexBuildPhase::Error,
			owner: None,
			next_ticket: 0,
			initial_complete: false,
			updated_at: Utc::now(),
			owner_heartbeat_at: None,
			error: Some("seeded test failure".to_string()),
			report_status: Some(IndexBuildReportStatus::Error),
			initial: None,
			updated: None,
			pending: None,
			initial_cursor: None,
		},
	)
	.await?;
	tx.set_key(&ikb.new_bt_key(1), &5u64).await?;
	tx.set_key(
		&br_key,
		&IndexBuildReservation {
			node: ds.id(),
			expires_at: Utc::now() + chrono::Duration::seconds(BUILD_RESERVATION_TTL_SECS),
		},
	)
	.await?;
	tx.commit().await?;

	// A writer mid-admission against generation 1: ticket read, CAS staged,
	// not yet committed.
	let writer = ds.transaction(TransactionType::Write).await?;
	let bt = ikb.new_bt_key(1);
	let ticket = catch!(writer, writer.get_key(&bt, None).await).expect("counter should exist");
	catch!(writer, writer.put_compare_key(&bt, &(ticket + 1), Some(&ticket)).await);

	// The takeover installs generation 2 and then blocks draining the live
	// reservation.
	let building =
		Arc::new(new_building_for_index(&ds, &session, ns, db, &table, Arc::clone(&ix)).await?);
	let acquire = {
		let building = Arc::clone(&building);
		tokio::spawn(async move { building.acquire_build_state().await })
	};
	timeout(Duration::from_secs(5), async {
		while durable_build_state(&ds, &ikb).await?.generation != 2 {
			sleep(Duration::from_millis(10)).await;
		}
		Ok::<_, anyhow::Error>(())
	})
	.await
	.map_err(|_| anyhow::anyhow!("takeover never installed the next generation"))??;
	assert!(
		!acquire.is_finished(),
		"the takeover should still be draining, which is the window under test"
	);

	assert!(
		writer.commit().await.is_err(),
		"an allocation in flight across the generation flip must not commit: its reservation \
		 would land after the drain and its queued mutation would be wiped"
	);

	// Let the takeover finish so the task does not outlive the test.
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_key(&br_key).await?;
	tx.commit().await?;
	timeout(Duration::from_secs(5), acquire)
		.await
		.map_err(|_| {
			anyhow::anyhow!("takeover did not finish after the reservation was released")
		})???
		.expect("takeover should acquire the new generation");
	Ok(())
}

/// A compaction plan prepared before an index's data was wiped must never
/// apply, however faithfully the wiped state is recreated afterwards.
///
/// This is what the generation guard in `bump_compaction_generation` exists to
/// enforce, and a rebuild's clean phase is the one caller that can defeat it.
/// The generation key lives inside the subspace the wipe clears, so clearing it
/// returns the index to the state a never-compacted index is in — which is
/// exactly the state a plan prepared before the wipe expects, so its
/// conditional write matches again. The per-key guards behind it match too,
/// because a rebuild re-indexes the same records and an HNSW pending is derived
/// wholly from the record and the graph state, carrying no writer identity. The
/// stale plan would then consume the rebuild's pendings and fold them into a
/// graph loaded from the pre-wipe snapshot, leaving the index `Online` and
/// empty.
///
/// The pendings are restored from their own bytes rather than by running a
/// rebuild, because the contract under test is that a pre-wipe plan cannot
/// apply — not that a rebuild happens to reproduce those bytes exactly.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_compaction_plan_prepared_before_a_wipe_cannot_apply() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE INDEX hx ON t FIELDS vec HNSW DIMENSION 2 DIST EUCLIDEAN TYPE F32;
		 CREATE t:1 SET vec = [1.0, 0.0];
		 CREATE t:2 SET vec = [0.0, 1.0];",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "hx").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let Index::Hnsw(params) = &ix.index else {
		panic!("the fixture must define an HNSW index");
	};

	// Read phase, over the pendings the writes above left behind. Nothing has
	// compacted this index, so the plan's expected generation is absent — the
	// value a wipe restores.
	let tx = Arc::new(ds.transaction(TransactionType::Read).await?);
	let pendings = catch!(tx, tx.scan_raw(ikb.new_hr_range()?, u32::MAX, 0, None).await);
	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let plan = IndexOperation::prepare_hnsw_compaction(&ctx, &ikb).await?;
	tx.cancel().await?;
	assert!(plan.has_work(), "the fixture must leave pendings for the plan to capture");
	assert_eq!(pendings.len(), 2, "one pending per indexed record");

	// A rebuild's clean phase, followed by the pendings it would rewrite.
	let tx = ds.transaction(TransactionType::Write).await?;
	catch!(tx, crate::idx::wipe_index_data(&tx, &ikb, &ix.index).await);
	for (key, value) in &pendings {
		catch!(tx, tx.set(Key::from(key.clone()), value.clone()).await);
	}
	tx.commit().await?;

	// Write phase of the stale plan.
	let tx = Arc::new(ds.transaction(TransactionType::Write).await?);
	let mut ctx = ds.setup_ctx()?;
	ctx.set_transaction(Arc::clone(&tx));
	let ctx = ctx.freeze();
	let applied = IndexOperation::apply_hnsw_compaction(
		&ctx,
		ctx.get_index_stores(),
		&ikb,
		params,
		crate::catalog::DOC_IDS_FORMAT_VERSION,
		plan,
	)
	.await?;
	tx.cancel().await?;
	assert!(!applied.applied(), "a plan prepared before the wipe must be rejected, not applied");

	// The pendings must survive for whoever compacts next.
	let tx = ds.transaction(TransactionType::Read).await?;
	let surviving = catch!(tx, tx.count(ikb.new_hr_range()?, None).await);
	tx.cancel().await?;
	assert_eq!(surviving, pendings.len(), "the rejected plan must leave every pending in place");
	Ok(())
}

/// A pre-filtered KNN search (#548) whose WHERE is fully index-coverable
/// performs zero record fetches inside the ANN search, on both the exact and
/// the graph tier: EXPLAIN ANALYZE (unredacted under `Session::owner()`)
/// reports the chosen `prefilter_tier` and no in-traversal `fetched:`
/// counter. The contrast query filters on an indexed column with no declared
/// field kind — not provably exact, so it stays an in-traversal residual and
/// reports its per-candidate record fetches.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn knn_prefilter_performs_zero_in_traversal_fetches() -> Result<()> {
	use surrealdb_types::Value as PublicValue;

	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE FIELD category ON t TYPE string;
		 DEFINE INDEX idx_category ON t FIELDS category;
		 DEFINE INDEX idx_rawcat ON t FIELDS rawcat;
		 DEFINE INDEX hn_pt ON t FIELDS point HNSW DIMENSION 1;",
	)
	.await?;
	// 2200 category-'a' rows push that allow-list over the exact-tier
	// threshold (default 2000) onto the graph tier; the 200 'b' rows stay on
	// the exact tier.
	execute_all(
		&ds,
		&session,
		"FOR $i IN 0..2400 {
			CREATE type::record('t', $i) SET
				point = [ <float> $i ],
				category = IF $i % 12 < 11 { 'a' } ELSE { 'b' },
				rawcat = IF $i % 12 < 11 { 'a' } ELSE { 'b' };
		};",
	)
	.await?;

	let explain = |sql: &'static str| {
		let ds = &ds;
		let session = &session;
		async move {
			let mut results = ds.execute(sql, session, None).await?;
			let value = results.remove(0).result?;
			match value {
				PublicValue::String(plan) => Ok::<String, anyhow::Error>(plan),
				other => anyhow::bail!("unexpected EXPLAIN result: {other:?}"),
			}
		}
	};

	// Exact tier (200 members): zero in-traversal fetches.
	let plan =
		explain("EXPLAIN ANALYZE SELECT id FROM t WHERE category = 'b' AND point <|3,40|> [0f]")
			.await?;
	assert!(plan.contains("prefilter_tier: exact"), "expected exact tier:\n{plan}");
	assert!(!plan.contains("fetched:"), "no in-traversal fetches expected:\n{plan}");

	// Graph tier (2200 members): admission is pure bitmap membership — still
	// zero in-traversal fetches.
	let plan =
		explain("EXPLAIN ANALYZE SELECT id FROM t WHERE category = 'a' AND point <|3,40|> [0f]")
			.await?;
	assert!(plan.contains("prefilter_tier: graph"), "expected graph tier:\n{plan}");
	assert!(!plan.contains("fetched:"), "no in-traversal fetches expected:\n{plan}");

	// Contrast: `rawcat` has no declared field kind, so its equality is not
	// provably exact and remains an in-traversal residual — the filter
	// fetches candidate records and says so.
	let plan =
		explain("EXPLAIN ANALYZE SELECT id FROM t WHERE rawcat = 'b' AND point <|3,40|> [0f]")
			.await?;
	assert!(!plan.contains("prefilter_tier"), "no prefilter expected:\n{plan}");
	assert!(plan.contains("fetched:"), "in-traversal fetches expected:\n{plan}");
	Ok(())
}

/// The bytes a previous release wrote a `!bp` marker at: this release's key up
/// to the record id, then the id under the index format — which is what `!di`
/// still spells, so that key supplies the suffix.
fn primary_append_key_in_previous_encoding(
	ikb: &IndexKeyBase,
	generation: BuildGeneration,
	id: &RecordIdKey,
) -> Result<Vec<u8>> {
	use crate::key::schema::BuildPrimaryGenerationPrefix;
	let (ns, db, table) = (ikb.ns(), ikb.db(), ikb.table());
	let head = BuildPrimaryGenerationPrefix {
		ns,
		db,
		tb: Cow::Borrowed(table),
		ix: ikb.index(),
		generation,
	}
	.encode_bound()?
	.to_vec();
	let erased = DocLookupPrefix::new(ns, db, Cow::Borrowed(table)).encode_bound()?.to_vec();
	let di = DocLookupKey::new(ns, db, Cow::Borrowed(table), Cow::Borrowed(id)).encode_key()?;
	let mut key = head;
	key.extend_from_slice(&di[erased.len()..]);
	Ok(key)
}

/// A `!bp` marker written by a previous release must sit at this release's key
/// for its record before the initial scan reads it.
///
/// That release encoded the record id under the index format, which drops a
/// nested value's numeric variant. The scan looks a marker up by the key it
/// builds for the record, so one left in the old spelling is missed and its
/// queued mutation baselined as though it did not exist. A build taken over
/// from an owner on that release keeps its generation, and with it these keys.
///
/// Also covers a queue wider than one page, because the rebuild carries its
/// cursor across commits and a page stepped past uncommitted leaves records
/// without a marker, and a key whose two spellings alias — which decodes
/// cleanly as a record other than its own.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn primary_append_markers_from_a_previous_release_are_rebuilt() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let ix_id = ia.index_id;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix_id);
	let building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;

	// A queued mutation for a record whose id holds a nested number, with its
	// marker in the spelling the previous release used.
	let generation: BuildGeneration = 1;
	let id = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(1))].into());
	let (ticket, mutation_seq) = (7, 0);
	{
		let tx = ds.transaction(TransactionType::Write).await?;
		tx.set_key(
			&ikb.new_bg_key(generation, ticket, mutation_seq),
			&Appending {
				old_values: None,
				new_values: None,
				id: id.clone(),
				count_cond_match: None,
			},
		)
		.await?;
		let legacy = primary_append_key_in_previous_encoding(&ikb, generation, &id)?;
		tx.set(
			Key::from(legacy),
			PrimaryAppendingTicket {
				ticket,
				mutation_seq,
			}
			.kv_encode_value()?,
		)
		.await?;
		tx.commit().await?;
	}

	// The scan cannot see it: the key it builds for this record is this
	// release's spelling, which is not the key on disk.
	{
		let tx = ds.transaction(TransactionType::Read).await?;
		assert!(
			tx.get_key(&ikb.new_bp_key(generation, &id), None).await?.is_none(),
			"the marker must start out invisible to a lookup by record"
		);
		tx.cancel().await?;
	}

	building.build_generation.store(generation, Ordering::Release);
	own_build(&ds, &ikb, &building, generation).await?;
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let ptr = tx.get_key(&ikb.new_bp_key(generation, &id), None).await?;
	let ptr = ptr.expect("the marker must now be found by a lookup for its own record");
	assert_eq!(
		(ptr.ticket, ptr.mutation_seq),
		(ticket, mutation_seq),
		"and still point at the same queued mutation"
	);
	let all = tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?;
	assert_eq!(all.len(), 1, "the old spelling must not be left beside the new one");
	tx.cancel().await?;

	// More queued mutations than one page holds, so the rebuild has to carry its
	// cursor across commits. A page it steps past without committing would leave
	// its records without a marker, which is the failure the scan cannot see.
	let span = surrealdb_kvs::consts::INDEXING_BATCH_SIZE as usize + 50;
	{
		let tx = ds.transaction(TransactionType::Write).await?;
		for i in 0..span {
			let id = RecordIdKey::Array(
				vec![Value::Number(crate::val::Number::Int(1000 + i as i64))].into(),
			);
			let (ticket, mutation_seq) = (1000 + i as u64, 0);
			tx.set_key(
				&ikb.new_bg_key(generation, ticket, mutation_seq),
				&Appending {
					old_values: None,
					new_values: None,
					id: id.clone(),
					count_cond_match: None,
				},
			)
			.await?;
			tx.set(
				Key::from(primary_append_key_in_previous_encoding(&ikb, generation, &id)?),
				PrimaryAppendingTicket {
					ticket,
					mutation_seq,
				}
				.kv_encode_value()?,
			)
			.await?;
		}
		tx.commit().await?;
	}
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	for i in 0..span {
		let id = RecordIdKey::Array(
			vec![Value::Number(crate::val::Number::Int(1000 + i as i64))].into(),
		);
		assert!(
			tx.get_key(&ikb.new_bp_key(generation, &id), None).await?.is_some(),
			"marker {i} must be found by a lookup for its own record"
		);
	}
	let all = tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?;
	assert_eq!(
		all.len(),
		span + 1,
		"every marker must end up in exactly one spelling, across page boundaries"
	);
	tx.cancel().await?;

	// A marker whose two spellings alias. Under the previous release `[3, NONE]`
	// encodes to the same bytes as `[3]` does under this one — the `NONE` tag
	// lands where the number's kind would have been — so this key decodes
	// cleanly, as the wrong record. Decoding is therefore no evidence of which
	// spelling a key is in, and only the queued mutation settles it. `[3]` has
	// no queued mutation, so it must come out of the rebuild with no marker.
	let three = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(3))].into());
	let aliased =
		RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(3)), Value::None].into());
	let (ticket, mutation_seq) = (99, 0);
	{
		let tx = ds.transaction(TransactionType::Write).await?;
		tx.set_key(
			&ikb.new_bg_key(generation, ticket, mutation_seq),
			&Appending {
				old_values: None,
				new_values: None,
				id: aliased.clone(),
				count_cond_match: None,
			},
		)
		.await?;
		let legacy = primary_append_key_in_previous_encoding(&ikb, generation, &aliased)?;
		// The premise: it decodes, and not as the record it was written for.
		let decoded = crate::key::schema::BuildPrimaryKey::decode_key(&legacy)
			.expect("the aliased spelling decodes cleanly");
		assert!(
			!decoded.id.0.addresses_same_record(&aliased),
			"and decodes as a different record, which is what makes it dangerous"
		);
		tx.set(
			Key::from(legacy),
			PrimaryAppendingTicket {
				ticket,
				mutation_seq,
			}
			.kv_encode_value()?,
		)
		.await?;
		tx.commit().await?;
	}
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let ptr = tx.get_key(&ikb.new_bp_key(generation, &aliased), None).await?;
	let ptr = ptr.expect("an aliased marker must be rebuilt at its own record's key");
	assert_eq!((ptr.ticket, ptr.mutation_seq), (ticket, mutation_seq));
	// Left where it was, the old key would read as a marker for `[3]`, and the
	// scan would baseline `[3]` against `[3, NONE]`'s queued mutation.
	assert!(
		tx.get_key(&ikb.new_bp_key(generation, &three), None).await?.is_none(),
		"the record the old key decodes as has no queued mutation, so no marker"
	);
	let all = tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?;
	assert_eq!(all.len(), span + 2, "one marker per record with a queued mutation");
	tx.cancel().await?;
	Ok(())
}

/// Two markers in the previous spelling whose keys alias must both survive.
///
/// The key `[1]`'s marker belongs at is the key `[1, NONE]`'s marker occupies,
/// so writing `[1]`'s marker while that one is still there destroys the second
/// record's marker — and the scan then baselines that record as though it had
/// no queued mutation. Reachable on a single-node upgrade.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn aliasing_markers_from_a_previous_release_both_survive_the_rebuild() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let ix_id = ia.index_id;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix_id);
	let building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;
	let generation: BuildGeneration = 1;

	let one = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(1))].into());
	let one_none =
		RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(1)), Value::None].into());
	// The premise: one record's target key is the other's current key.
	assert_eq!(
		*ikb.new_bp_key(generation, &one).encode_key()?,
		*primary_append_key_in_previous_encoding(&ikb, generation, &one_none)?,
		"the two spellings must alias, or this test guards nothing"
	);

	for (id, ticket) in [(&one, 7u64), (&one_none, 9u64)] {
		let tx = ds.transaction(TransactionType::Write).await?;
		tx.set_key(
			&ikb.new_bg_key(generation, ticket, 0),
			&Appending {
				old_values: None,
				new_values: None,
				id: id.clone(),
				count_cond_match: None,
			},
		)
		.await?;
		tx.set(
			Key::from(primary_append_key_in_previous_encoding(&ikb, generation, id)?),
			PrimaryAppendingTicket {
				ticket,
				mutation_seq: 0,
			}
			.kv_encode_value()?,
		)
		.await?;
		tx.commit().await?;
	}

	building.build_generation.store(generation, Ordering::Release);
	own_build(&ds, &ikb, &building, generation).await?;
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	assert_eq!(
		tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?.len(),
		2,
		"neither marker may be lost"
	);
	for (id, ticket) in [(&one, 7u64), (&one_none, 9u64)] {
		let ptr = tx
			.get_key(&ikb.new_bp_key(generation, id), None)
			.await?
			.expect("each record keeps a marker at its own key");
		assert_eq!(ptr.ticket, ticket, "and it still names that record's own mutation");
	}
	tx.cancel().await?;
	Ok(())
}

/// A record with two queued mutations gets a marker naming the earlier one.
///
/// A marker names a record's *first* queued mutation and the scan baselines
/// against it, so naming the later one would apply a delta the baseline already
/// includes. Here the later one already sits at this release's key — as a write
/// admitted after the markers are cleared leaves it — and the earlier one is in
/// the previous spelling.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn the_rebuild_keeps_the_earlier_of_two_markers_for_one_record() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let ix_id = ia.index_id;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix_id);
	let building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;
	let generation: BuildGeneration = 1;
	let id = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(5))].into());

	let tx = ds.transaction(TransactionType::Write).await?;
	for ticket in [5u64, 9u64] {
		tx.set_key(
			&ikb.new_bg_key(generation, ticket, 0),
			&Appending {
				old_values: None,
				new_values: None,
				id: id.clone(),
				count_cond_match: None,
			},
		)
		.await?;
	}
	// The later mutation already sits at this release's key; the earlier one is
	// still in the previous spelling.
	tx.set_key(
		&ikb.new_bp_key(generation, &id),
		&PrimaryAppendingTicket {
			ticket: 9,
			mutation_seq: 0,
		},
	)
	.await?;
	tx.set(
		Key::from(primary_append_key_in_previous_encoding(&ikb, generation, &id)?),
		PrimaryAppendingTicket {
			ticket: 5,
			mutation_seq: 0,
		}
		.kv_encode_value()?,
	)
	.await?;
	tx.commit().await?;

	building.build_generation.store(generation, Ordering::Release);
	own_build(&ds, &ikb, &building, generation).await?;
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let ptr = tx
		.get_key(&ikb.new_bp_key(generation, &id), None)
		.await?
		.expect("the record keeps a marker");
	assert_eq!(ptr.ticket, 5, "the earlier queued mutation is the one a marker must name");
	assert_eq!(
		tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?.len(),
		1,
		"and the other spelling is consumed"
	);
	tx.cancel().await?;

	// The same with the two mutations a page apart, so the later one is met in a
	// transaction of its own, after the earlier one's marker has been committed.
	let far = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(6))].into());
	let page = surrealdb_kvs::consts::INDEXING_BATCH_SIZE as u64;
	let tx = ds.transaction(TransactionType::Write).await?;
	for (ticket, id) in
		[(20, far.clone()), (21 + page, far.clone())].into_iter().chain((0..page).map(|i| {
			(21 + i, RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(7))].into()))
		})) {
		tx.set_key(
			&ikb.new_bg_key(generation, ticket, 0),
			&Appending {
				old_values: None,
				new_values: None,
				id,
				count_cond_match: None,
			},
		)
		.await?;
	}
	tx.commit().await?;
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	let ptr = tx
		.get_key(&ikb.new_bp_key(generation, &far), None)
		.await?
		.expect("the record keeps a marker");
	assert_eq!(ptr.ticket, 20, "a later page must not replace an earlier page's marker");
	tx.cancel().await?;
	Ok(())
}

/// Publishes `building` as the owner of `generation` in the `Building` phase,
/// which the marker rebuild renews as it goes.
async fn own_build(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	building: &Building,
	generation: BuildGeneration,
) -> Result<()> {
	set_durable_build_state(
		ds,
		ikb,
		durable_build_state_for_phase(IndexBuildPhase::Building, generation, Some(building.owner)),
	)
	.await
}

/// Queues a mutation of `id` at `ticket`, and a marker for it in the spelling a
/// previous release used.
async fn queue_with_marker_in_previous_encoding(
	tx: &crate::kvs::Transaction,
	ikb: &IndexKeyBase,
	generation: BuildGeneration,
	ticket: BuildTicket,
	id: &RecordIdKey,
	old_values: Option<Vec<Value>>,
	marker: bool,
) -> Result<()> {
	let appending = Appending {
		old_values,
		new_values: None,
		id: id.clone(),
		count_cond_match: None,
	};
	queue_in_previous_encoding(tx, ikb, generation, ticket, appending, marker).await
}

/// Queues `appending` at `ticket`, and a marker for it in the spelling a
/// previous release used.
async fn queue_in_previous_encoding(
	tx: &crate::kvs::Transaction,
	ikb: &IndexKeyBase,
	generation: BuildGeneration,
	ticket: BuildTicket,
	appending: Appending,
	marker: bool,
) -> Result<()> {
	if marker {
		tx.set(
			Key::from(primary_append_key_in_previous_encoding(ikb, generation, &appending.id)?),
			PrimaryAppendingTicket {
				ticket,
				mutation_seq: 0,
			}
			.kv_encode_value()?,
		)
		.await?;
	}
	tx.set_key(&ikb.new_bg_key(generation, ticket, 0), &appending).await
}

/// The ids `[1]`, `[1, NONE]`, … with `len` links, each of whose keys under this
/// release is the next one's key under the previous release.
fn aliasing_chain(len: usize) -> Vec<RecordIdKey> {
	(0..len)
		.map(|nones| {
			let mut id = vec![Value::Number(crate::val::Number::Int(1))];
			id.extend(std::iter::repeat_n(Value::None, nones));
			RecordIdKey::Array(id.into())
		})
		.collect()
}

/// A chain of markers in the previous spelling, each occupying the key the one
/// before it belongs at, all come out of the rebuild at their own keys.
///
/// No marker is moved, so the chain's length bounds nothing: the markers are
/// cleared and each is written afresh from its queued mutation.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_chain_of_aliasing_markers_is_rebuilt() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let ix_id = ia.index_id;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix_id);
	let building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;
	let generation: BuildGeneration = 1;

	let chain = aliasing_chain(5);
	for link in chain.windows(2) {
		assert_eq!(
			*ikb.new_bp_key(generation, &link[0]).encode_key()?,
			*primary_append_key_in_previous_encoding(&ikb, generation, &link[1])?,
			"each link must occupy the key the one before it belongs at"
		);
	}
	let tx = ds.transaction(TransactionType::Write).await?;
	for (ticket, id) in chain.iter().enumerate() {
		queue_with_marker_in_previous_encoding(
			&tx,
			&ikb,
			generation,
			ticket as BuildTicket + 1,
			id,
			None,
			true,
		)
		.await?;
	}
	tx.commit().await?;

	building.build_generation.store(generation, Ordering::Release);
	own_build(&ds, &ikb, &building, generation).await?;
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	for (ticket, id) in chain.iter().enumerate() {
		let ptr = tx
			.get_key(&ikb.new_bp_key(generation, id), None)
			.await?
			.expect("every link keeps a marker at its own key");
		assert_eq!(ptr.ticket, ticket as BuildTicket + 1, "naming its own mutation");
	}
	assert_eq!(
		tx.keys(ikb.new_bp_range(generation)?, u32::MAX, 0, None).await?.len(),
		chain.len(),
		"and nothing else is left behind"
	);
	tx.cancel().await?;
	Ok(())
}

/// A record whose queued mutation has no marker gets one from the rebuild.
///
/// A write on this release admitted while an older marker for another record
/// occupied its key found the key taken and recorded no marker of its own. Only
/// its queued mutation still says the record has one.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_record_left_without_a_marker_gets_one_from_its_queued_mutation() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;",
	)
	.await?;
	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let ix_id = ia.index_id;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix_id);
	let building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;
	let generation: BuildGeneration = 1;
	let [one, one_none] = <[RecordIdKey; 2]>::try_from(aliasing_chain(2)).expect("two links");

	let tx = ds.transaction(TransactionType::Write).await?;
	// `[1, NONE]`'s marker in the previous spelling, at the key `[1]`'s belongs at.
	queue_with_marker_in_previous_encoding(&tx, &ikb, generation, 9, &one_none, None, true).await?;
	// `[1]` was written after it and found that key taken.
	queue_with_marker_in_previous_encoding(&tx, &ikb, generation, 11, &one, None, false).await?;
	tx.commit().await?;

	building.build_generation.store(generation, Ordering::Release);
	own_build(&ds, &ikb, &building, generation).await?;
	building.rebuild_primary_appendings().await?;

	let tx = ds.transaction(TransactionType::Read).await?;
	for (id, ticket) in [(&one, 11), (&one_none, 9)] {
		let ptr = tx
			.get_key(&ikb.new_bp_key(generation, id), None)
			.await?
			.expect("each record with a queued mutation has a marker");
		assert_eq!(ptr.ticket, ticket, "naming its own mutation");
	}
	tx.cancel().await?;
	Ok(())
}

/// Reads every record of `table` as the initial scan pages them.
async fn scan_records(
	ds: &Datastore,
	ns: NamespaceId,
	db: DatabaseId,
	table: &TableName,
) -> Result<Vec<(Vec<u8>, crate::kvs::Val)>> {
	let tx = ds.transaction(TransactionType::Read).await?;
	let rng = RecordPrefix {
		ns,
		db,
		tb: Cow::Borrowed(table),
	}
	.range()?;
	let values = catch!(tx, tx.batch_keys_vals_raw(rng, u32::MAX, None).await).result;
	tx.cancel().await?;
	Ok(values)
}

/// A queued mutation of `id` from one state to another, each present or
/// absent, which is all a COUNT index without a predicate reads of them.
fn mutation(id: &RecordIdKey, old: bool, new: bool) -> Appending {
	Appending {
		old_values: old.then(Vec::new),
		new_values: new.then(Vec::new),
		id: id.clone(),
		count_cond_match: None,
	}
}

/// The ids `[n, s]` the COUNT tests mark: the older spelling of each sorts
/// after the keys of every `[n, …]` record under this release.
fn number_then_string(n: i64, s: &str) -> RecordIdKey {
	RecordIdKey::Array(vec![Value::Number(crate::val::Number::Int(n)), Value::from(s)].into())
}

/// The generation the COUNT tests' builds own.
const COUNT_GENERATION: BuildGeneration = 1;

/// A build of the COUNT index `ic` on table `t`, owning [`COUNT_GENERATION`],
/// over what `sql` defined and wrote.
struct CountBuild {
	ds: Arc<Datastore>,
	session: Session,
	ikb: IndexKeyBase,
	building: Building,
}

impl CountBuild {
	async fn new(sql: &str) -> Result<Self> {
		let (ds, session) = new_index_test_ds().await?;
		execute_all(&ds, &session, sql).await?;
		let (ns, db, table, ic) = get_table_index(&ds, "t", "ic").await?;
		let ikb = IndexKeyBase::new(ns, db, table.clone(), ic.index_id);
		let building = new_building_for_index(&ds, &session, ns, db, &table, ic).await?;
		building.build_generation.store(COUNT_GENERATION, Ordering::Release);
		Ok(Self {
			ds,
			session,
			ikb,
			building,
		})
	}

	/// The key this release marks `id` at.
	fn own_key(&self, id: &RecordIdKey) -> Result<Vec<u8>> {
		Ok(self.ikb.new_bp_key(COUNT_GENERATION, id).encode_key()?.to_vec())
	}

	/// The key an older node marks `id` at.
	fn older_key(&self, id: &RecordIdKey) -> Result<Vec<u8>> {
		primary_append_key_in_previous_encoding(&self.ikb, COUNT_GENERATION, id)
	}

	/// Queues `appending` at `ticket`, marked the way an older node marks it.
	async fn queue_older(
		&self,
		tx: &crate::kvs::Transaction,
		ticket: BuildTicket,
		appending: Appending,
	) -> Result<()> {
		queue_in_previous_encoding(tx, &self.ikb, COUNT_GENERATION, ticket, appending, true).await
	}

	/// Queues `appending` at `ticket`, marked at its record's own key.
	async fn queue_own(
		&self,
		tx: &crate::kvs::Transaction,
		ticket: BuildTicket,
		appending: Appending,
	) -> Result<()> {
		let ptr = PrimaryAppendingTicket {
			ticket,
			mutation_seq: 0,
		};
		tx.set_key(&self.ikb.new_bp_key(COUNT_GENERATION, &appending.id), &ptr).await?;
		self.queue_unmarked(tx, ticket, appending).await
	}

	/// Queues `appending` at `ticket` unmarked, as a writer queues a later
	/// mutation of a record that already has a marker.
	async fn queue_unmarked(
		&self,
		tx: &crate::kvs::Transaction,
		ticket: BuildTicket,
		appending: Appending,
	) -> Result<()> {
		tx.set_key(&self.ikb.new_bg_key(COUNT_GENERATION, ticket, 0), &appending).await
	}

	/// The table's live records, as the initial scan pages them.
	async fn records(&self) -> Result<Vec<(Vec<u8>, crate::kvs::Val)>> {
		scan_records(&self.ds, self.ikb.ns(), self.ikb.db(), self.ikb.table()).await
	}

	/// Runs the initial scan over `batches` of the table's records, in order,
	/// returning what each batch and the tail after them indexed, and the
	/// count they baselined.
	async fn scan_in_batches(
		&self,
		batches: &[&[(Vec<u8>, crate::kvs::Val)]],
	) -> Result<(Vec<usize>, i64)> {
		let mut scan = CountScan::start(&self.building).await?;
		let mut indexed = Vec::new();
		for values in batches {
			indexed.push(scan.batch(values).await?);
		}
		indexed.push(scan.tail().await?);
		let baseline = scan.baseline();
		scan.cancel().await?;
		Ok((indexed, baseline))
	}
}

/// A COUNT build's initial scan and its merge of queued old states, driven a
/// batch at a time in one transaction, as the builder drives them.
struct CountScan<'a> {
	building: &'a Building,
	ctx: crate::ctx::FrozenContext,
	progress: Option<super::replay::CountPrimaryProgress>,
	indexed: usize,
}

impl<'a> CountScan<'a> {
	async fn start(building: &'a Building) -> Result<Self> {
		Ok(Self {
			building,
			ctx: building.new_write_tx_ctx().await?,
			progress: Some(super::replay::CountPrimaryProgress::default()),
			indexed: 0,
		})
	}

	/// Scans `values`, the next batch of records, returning what it indexed.
	async fn batch(&mut self, values: &[(Vec<u8>, crate::kvs::Val)]) -> Result<usize> {
		let tx = self.ctx.tx();
		let n = self
			.building
			.index_initial_batch(
				&self.ctx,
				&tx,
				values,
				self.indexed,
				&mut false,
				&mut self.progress,
			)
			.await?;
		self.indexed += n;
		Ok(n)
	}

	/// Merges the queued old states past the last batch, returning what it
	/// indexed.
	async fn tail(&mut self) -> Result<usize> {
		let tx = self.ctx.tx();
		let n = self
			.building
			.index_remaining_count_primary_appendings(
				&self.ctx,
				&tx,
				&mut self.progress,
				self.indexed,
			)
			.await?;
		self.indexed += n;
		Ok(n)
	}

	/// The count the scan has baselined so far.
	fn baseline(&self) -> i64 {
		let building = self.building;
		self.ctx.tx().pending_count_delta(
			building.ix_key.ns,
			building.ix_key.db,
			building.ikb.table(),
			building.ix.index_id,
		)
	}

	async fn cancel(self) -> Result<()> {
		self.ctx.tx().cancel().await
	}
}

/// The key a COUNT build reads an older node's marker at is the one that node
/// writes it at, and there is one only for an id holding a number.
#[test]
fn a_markers_older_spelling_is_the_key_an_older_node_writes() -> Result<()> {
	let ikb = IndexKeyBase::new(NamespaceId(1), DatabaseId(2), TableName::from("t"), IndexId(3));
	let older = |id: &RecordIdKey| -> Result<Option<Vec<u8>>> {
		let key = ikb.new_bp_key_in_previous_spelling(COUNT_GENERATION, id)?;
		Ok(key.map(|key| key.as_bytes().to_vec()))
	};
	for id in [&aliasing_chain(1)[0], &aliasing_chain(2)[1], &number_then_string(42, "intro")] {
		let written = primary_append_key_in_previous_encoding(&ikb, COUNT_GENERATION, id)?;
		assert_eq!(older(id)?, Some(written), "{id:?}");
	}
	// The bytes v3.2.4 writes for this marker, whose `Bp` key encodes every
	// field under the index format: a change to how that format spells a number
	// would otherwise move the key the scan reads and the helper above alike.
	assert_eq!(
		older(&number_then_string(42, "intro"))?,
		Some(
			b"/*\x00\x00\x00\x01*\x00\x00\x00\x02*t\x00!bp\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\
			  \x05\x05\xa0\x19\x1aS\x0f\x01\x00\x00\x06intro\x00\x00"
				.to_vec()
		)
	);
	let plain = [
		RecordIdKey::String("plain".into()),
		RecordIdKey::Number(7),
		RecordIdKey::Array(vec![Value::from("a"), Value::None].into()),
	];
	for id in &plain {
		assert_eq!(older(id)?, None, "{id:?}");
	}
	Ok(())
}

/// A COUNT build merges a marker an older node wrote by the record its queued
/// mutation names, whatever its key decodes as or whether it decodes at all.
///
/// The merge counts the queued old state of records the live scan does not see.
/// An older node spells the id under the index format: `[42, 'intro']` does not
/// decode under this release's spelling at all, and `[1, NONE]` decodes as
/// `[1]`, a live record, which would drop a deleted record from the baseline.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_merges_older_markers_by_their_queued_mutation() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[1] SET a = 1;",
	)
	.await?;
	let (one_none, intro) =
		(aliasing_chain(2).pop().expect("two links"), number_then_string(42, "intro"));
	// The premise: the aliasing key is the live record's, and sorts in its span.
	assert_eq!(b.own_key(&aliasing_chain(1)[0])?, b.older_key(&one_none)?);

	// Both records were deleted during the build, and neither is live.
	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 9, mutation(&one_none, true, false)).await?;
	b.queue_older(&tx, 10, mutation(&intro, true, false)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 1, "only `t:[1]` is live");
	let mut scan = CountScan::start(&b.building).await?;
	assert_eq!(
		scan.batch(&values).await?,
		1,
		"the live record only: `[1, NONE]`'s marker reads as `[1]` but waits for its own span"
	);
	assert_eq!(
		scan.tail().await?,
		2,
		"the deleted `[1, NONE]` in its own span, and the deleted `[42, 'intro']`, whose key \
		 does not decode"
	);
	assert_eq!(scan.baseline(), 3);
	scan.cancel().await
}

/// A marker an older node wrote in a span before its record's is taken up in
/// the record's own span.
///
/// `[1, NONE]`'s marker in the older spelling sits at `[1]`'s key, in the span
/// of the batch that scans `[1]`. `[1, NONE]` is live, and baselined from that
/// marker's queued old state when a batch later scans it: counting that state
/// with `[1]`'s batch as well would count the record twice.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_takes_an_early_marker_up_in_its_records_span() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[1] SET a = 1;
		 CREATE t:[1, NONE] SET a = 1;",
	)
	.await?;
	let one_none = aliasing_chain(2).pop().expect("two links");

	// An update of the live `[1, NONE]`, queued by an older node.
	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 9, mutation(&one_none, true, true)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 2, "`[1]` and `[1, NONE]` are both live");
	let (indexed, baseline) = b.scan_in_batches(&[&values[..1], &values[1..]]).await?;
	assert_eq!(indexed, vec![1, 1, 0], "each live record once, and the marker not at all");
	assert_eq!(baseline, 2);
	Ok(())
}

/// A marker an older node wrote in a span after its record's counts only for a
/// record that is gone.
///
/// The older spelling of `[42, 'intro']` sorts after the keys of every
/// `[42, …]` record, so with `[42, 'k']` ending a batch the markers of
/// `[42, 'intro']` and `[42, 'b']` fall in the next span, after their records'
/// own span. The scan baselined `[42, 'intro']` there from its marker's queued
/// old state, so the marker counts for nothing where it sorts; `[42, 'b']` is
/// gone, so its queued old state is what the baseline needs.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_counts_a_late_marker_only_for_a_record_that_is_gone() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[42, 'intro'] SET a = 1;
		 CREATE t:[42, 'k'] SET a = 1;
		 CREATE t:[43, 'x'] SET a = 1;",
	)
	.await?;
	let (live, gone) = (number_then_string(42, "intro"), number_then_string(42, "b"));
	// The premise: both older keys land after `[42, 'k']` and before `[43, 'x']`.
	for marked in [&live, &gone] {
		let old = b.older_key(marked)?;
		assert!(old > b.own_key(&number_then_string(42, "k"))?);
		assert!(old < b.own_key(&number_then_string(43, "x"))?);
	}

	// An update of the live record and a delete of the other, queued by an older node.
	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 9, mutation(&live, true, true)).await?;
	b.queue_older(&tx, 10, mutation(&gone, true, false)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 3);
	let (indexed, baseline) = b.scan_in_batches(&[&values[..2], &values[2..]]).await?;
	assert_eq!(
		indexed,
		vec![2, 2, 0],
		"the two live `[42, …]`, then `[43, 'x']` and the gone `[42, 'b']`, and nothing twice"
	);
	assert_eq!(baseline, 4);
	Ok(())
}

/// A marker an older node wrote is ignored for a record whose own key holds a
/// marker for it, and only then.
///
/// `[42, 'b']` has both, and must be counted once. The key `[1]`'s marker would
/// sit at holds `[1, NONE]`'s marker in the older spelling instead, which names
/// another record: `[1]`'s own marker, in the older spelling elsewhere, is still
/// the one that counts it.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_trusts_an_own_key_marker_only_for_its_own_record() -> Result<()> {
	let b = CountBuild::new("DEFINE TABLE t SCHEMALESS; DEFINE INDEX ic ON t COUNT;").await?;
	let [one, one_none] = <[RecordIdKey; 2]>::try_from(aliasing_chain(2)).expect("two links");
	let both = number_then_string(42, "b");

	// Every record was deleted during the build; none is live.
	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&one, true, false)).await?;
	b.queue_older(&tx, 2, mutation(&one_none, true, false)).await?;
	// `[42, 'b']`'s own marker, and a later mutation marked in the older spelling.
	b.queue_own(&tx, 3, mutation(&both, true, false)).await?;
	b.queue_older(&tx, 4, mutation(&both, true, false)).await?;
	tx.commit().await?;

	let (indexed, baseline) = b.scan_in_batches(&[]).await?;
	assert_eq!(indexed, vec![3], "`[1]`, `[1, NONE]` and `[42, 'b']`, each once");
	assert_eq!(baseline, 3);
	Ok(())
}

/// A COUNT WHERE build baselines a record an older node changed from the
/// predicate state its queued mutation carries, not from the record as scanned.
///
/// Every record matched until an older node updated it to stop matching, and
/// this release then deleted `[42, 'e']` and `[44, 'd']`, marking that at their
/// own keys. Replay subtracts each of them once, so each has to be in the
/// baseline. The older markers sort in a span before their record's
/// (`[1, NONE]`), after it (`[42, 'intro']`, `[42, 'e']`) or in it
/// (`[44, 'd']`); the deleted records' own markers are the later of their two.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_where_build_baselines_a_changed_record_from_its_queued_state() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT WHERE a = 1;
		 CREATE t:[1] SET a = 1;
		 CREATE t:[1, NONE] SET a = 2;
		 CREATE t:[42, 'intro'] SET a = 2;
		 CREATE t:[42, 'k'] SET a = 1;
		 CREATE t:[43, 'x'] SET a = 1;
		 CREATE t:[45, 'z'] SET a = 1;",
	)
	.await?;
	let one_none = aliasing_chain(2).pop().expect("two links");
	let intro = number_then_string(42, "intro");
	let (late, in_span) = (number_then_string(42, "e"), number_then_string(44, "d"));
	let stopped_matching = |id: &RecordIdKey| Appending {
		count_cond_match: Some((true, false)),
		..mutation(id, true, true)
	};
	let deleted = |id: &RecordIdKey| Appending {
		count_cond_match: Some((false, false)),
		..mutation(id, true, false)
	};

	let tx = b.ds.transaction(TransactionType::Write).await?;
	for (ticket, changed) in [(1, &one_none), (2, &intro), (3, &late), (5, &in_span)] {
		b.queue_older(&tx, ticket, stopped_matching(changed)).await?;
	}
	b.queue_own(&tx, 4, deleted(&late)).await?;
	b.queue_own(&tx, 6, deleted(&in_span)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 6, "every record but `[42, 'e']` and `[44, 'd']` is live");
	let (indexed, baseline) =
		b.scan_in_batches(&[&values[..1], &values[1..4], &values[4..]]).await?;
	assert_eq!(baseline, 8, "each record, as it stood before its queued mutations");
	assert_eq!(
		indexed,
		vec![1, 4, 3, 0],
		"`[1]`; `[1, NONE]`, `[42, 'intro']`, `[42, 'k']` and the gone `[42, 'e']`; \
		 `[43, 'x']`, `[45, 'z']` and the gone `[44, 'd']`"
	);
	Ok(())
}

/// A COUNT build baselines a record from the first of its queued mutations when
/// both an older node and this release marked one.
///
/// An older node deleted `[42, 'b']` and this release recreated it; this release
/// created `[42, 'c']` and an older node then updated it. Each record's own
/// marker is this release's, which is the later mutation for `[42, 'b']` only.
/// `t:plain`, which both releases spell alike, shares their batch.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_baselines_from_the_first_of_two_markers() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:plain SET a = 1;
		 CREATE t:[42, 'b'] SET a = 1;
		 CREATE t:[42, 'c'] SET a = 1;
		 CREATE t:[42, 'k'] SET a = 1;",
	)
	.await?;
	let (recreated, created) = (number_then_string(42, "b"), number_then_string(42, "c"));

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&recreated, true, false)).await?;
	b.queue_own(&tx, 2, mutation(&recreated, false, true)).await?;
	b.queue_own(&tx, 3, mutation(&created, false, true)).await?;
	b.queue_older(&tx, 4, mutation(&created, true, true)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 4);
	let (indexed, baseline) = b.scan_in_batches(&[&values]).await?;
	assert_eq!(baseline, 3, "all but `[42, 'c']`, which did not exist yet");
	assert_eq!(indexed, vec![4, 0], "the live records once, and the older markers not at all");
	Ok(())
}

/// A COUNT build baselines a record an older node created as absent.
///
/// The older node's marker for `[42, 'n']` sorts after the record's span, so
/// the scan finds it only by reading the older spelling; indexing the record as
/// it stands would count the create twice, once there and once in replay.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_baselines_a_record_an_older_node_created_as_absent() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[42, 'k'] SET a = 1;
		 CREATE t:[42, 'n'] SET a = 1;",
	)
	.await?;

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&number_then_string(42, "n"), false, true)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 2);
	let (indexed, baseline) = b.scan_in_batches(&[&values]).await?;
	assert_eq!(baseline, 1, "`[42, 'k']` only");
	assert_eq!(indexed, vec![2, 0]);
	Ok(())
}

/// A marker an older node wrote that sorts after its record's span is skipped
/// when that span settled the record, whatever became of the record since.
///
/// `[42, 'a']`'s span baselined it from its older marker, and `[42, 'c']`'s
/// from the record as it stood; both records are then deleted before the merge
/// reaches their older markers. `[42, 'c']` was first updated by this release,
/// which marked it at its own key before the older node's delete.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_skips_a_late_marker_its_records_span_settled() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[42, 'a'] SET a = 1;
		 CREATE t:[42, 'c'] SET a = 1;
		 CREATE t:[42, 'k'] SET a = 1;",
	)
	.await?;
	let (taken, updated) = (number_then_string(42, "a"), number_then_string(42, "c"));

	// An older node's update of `[42, 'a']`, before the scan.
	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&taken, true, true)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 3);
	let mut scan = CountScan::start(&b.building).await?;
	assert_eq!(scan.batch(&values).await?, 3);

	// After the batch: the older node deletes `[42, 'a']`, whose older key
	// already holds its marker; this release updates `[42, 'c']` and an older
	// node deletes it.
	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_unmarked(&tx, 2, mutation(&taken, true, false)).await?;
	b.queue_own(&tx, 3, mutation(&updated, true, true)).await?;
	b.queue_older(&tx, 4, mutation(&updated, true, false)).await?;
	tx.commit().await?;
	execute_all(&b.ds, &b.session, "DELETE t:[42, 'a']; DELETE t:[42, 'c'];").await?;

	assert_eq!(scan.tail().await?, 0, "neither older marker counts where it sorts");
	assert_eq!(scan.baseline(), 3, "each record once, as its span had it");
	scan.cancel().await
}

/// A marker an older node wrote that sorts after its record's span still counts
/// when the record's own key marks only a later mutation.
///
/// An older node deleted `[42, 'g']` before its span, which found nothing to
/// count. This release then recreated and deleted it, marking the recreate at
/// the record's own key: that marker stands for nothing before the delete.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_counts_a_late_marker_whose_own_marker_came_after() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[42, 'k'] SET a = 1;",
	)
	.await?;
	let gone = number_then_string(42, "g");

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&gone, true, false)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 1, "only `[42, 'k']` is live");
	let mut scan = CountScan::start(&b.building).await?;
	assert_eq!(scan.batch(&values).await?, 1);

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_own(&tx, 2, mutation(&gone, false, true)).await?;
	b.queue_unmarked(&tx, 3, mutation(&gone, true, false)).await?;
	tx.commit().await?;

	assert_eq!(scan.tail().await?, 1, "`[42, 'g']`, as it stood before the older node's delete");
	assert_eq!(scan.baseline(), 2);
	scan.cancel().await
}

/// A marker an older node wrote in a span before its record's is not counted
/// when, by the record's span, the record's own key marks a mutation of it.
///
/// An older node deleted `[1, NONE]`, marking that at `[1]`'s key, which the
/// merge meets with `[1]`'s batch and sets aside. This release then recreated
/// and deleted the record, marking it at its own key, which the merge meets in
/// the record's span and takes up together with the older marker.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_takes_an_early_marker_up_once_its_record_has_its_own() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[1] SET a = 1;",
	)
	.await?;
	let one_none = aliasing_chain(2).pop().expect("two links");

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&one_none, true, false)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 1, "only `[1]` is live");
	let mut scan = CountScan::start(&b.building).await?;
	assert_eq!(scan.batch(&values).await?, 1, "`[1]`, with `[1, NONE]`'s marker set aside");

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_own(&tx, 2, mutation(&one_none, false, true)).await?;
	b.queue_unmarked(&tx, 3, mutation(&one_none, true, false)).await?;
	tx.commit().await?;

	assert_eq!(scan.tail().await?, 1, "`[1, NONE]` once");
	assert_eq!(scan.baseline(), 2);
	scan.cancel().await
}

/// A marker an older node wrote after its record's span is skipped while the
/// record is there, since that span baselined the record as it stood.
///
/// The scan baselines `[42, 'a']` live, and an older node's update of it is
/// marked only afterwards, at a key that sorts after the span.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_build_skips_a_late_marker_written_after_its_records_span() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[42, 'a'] SET a = 1;
		 CREATE t:[42, 'k'] SET a = 1;",
	)
	.await?;
	let values = b.records().await?;
	let mut scan = CountScan::start(&b.building).await?;
	assert_eq!(scan.batch(&values).await?, 2);

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&number_then_string(42, "a"), true, true)).await?;
	tx.commit().await?;

	assert_eq!(scan.tail().await?, 0, "`[42, 'a']` was there when its span was scanned");
	assert_eq!(scan.baseline(), 2);
	scan.cancel().await
}

/// A marker set aside for its record's span defers only to a marker at the
/// record's own key that names the record.
///
/// `[1, NONE]`'s older marker sits at `[1]`'s key, and `[1, NONE]`'s own key
/// holds the older marker of `[1, NONE, NONE]`. Both records are gone.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_set_aside_marker_defers_only_to_its_own_records_marker() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[1] SET a = 1;",
	)
	.await?;
	let [_, one_none, one_none_none] =
		<[RecordIdKey; 3]>::try_from(aliasing_chain(3)).expect("three links");
	// The premise: the two older markers sit at `[1]`'s and `[1, NONE]`'s keys.
	assert_eq!(b.older_key(&one_none_none)?, b.own_key(&one_none)?);

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&one_none, true, false)).await?;
	b.queue_older(&tx, 2, mutation(&one_none_none, true, false)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 1, "only `[1]` is live");
	let (indexed, baseline) = b.scan_in_batches(&[&values]).await?;
	assert_eq!(indexed, vec![1, 2], "`[1]`, then `[1, NONE]` and `[1, NONE, NONE]`");
	assert_eq!(baseline, 3);
	Ok(())
}

/// A marker met after its record's span defers only to an earlier marker at the
/// record's own key that names the record.
///
/// `[42, 'a']`'s own key holds the older marker of `[42, NONE, 'a']`, another
/// record's earlier mutation, and `[42, 'a']`'s own older marker sorts after
/// the span. Both records are gone.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_late_marker_defers_only_to_its_own_records_marker() -> Result<()> {
	let b = CountBuild::new(
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE INDEX ic ON t COUNT;
		 CREATE t:[42, 'k'] SET a = 1;",
	)
	.await?;
	let late = number_then_string(42, "a");
	let alias = RecordIdKey::Array(
		vec![Value::Number(crate::val::Number::Int(42)), Value::None, Value::from("a")].into(),
	);
	// The premise: the other record's older marker sits at `[42, 'a']`'s key.
	assert_eq!(b.older_key(&alias)?, b.own_key(&late)?);

	let tx = b.ds.transaction(TransactionType::Write).await?;
	b.queue_older(&tx, 1, mutation(&alias, true, false)).await?;
	b.queue_older(&tx, 2, mutation(&late, true, false)).await?;
	tx.commit().await?;

	let values = b.records().await?;
	assert_eq!(values.len(), 1, "only `[42, 'k']` is live");
	let (indexed, baseline) = b.scan_in_batches(&[&values]).await?;
	assert_eq!(indexed, vec![2, 1], "`[42, 'k']` and `[42, NONE, 'a']`, then `[42, 'a']`");
	assert_eq!(baseline, 3);
	Ok(())
}

/// Leaves a generation-2 build of `ikb`'s index `Building` under an expired
/// owner with no index data, checkpointed after `cursor` if one is given, so
/// that a takeover picks it up.
async fn strand_count_build(
	ds: &Datastore,
	ikb: &IndexKeyBase,
	cursor: Option<RecordIdKey>,
) -> Result<()> {
	let expired = Utc::now() - chrono::Duration::seconds(BUILD_OWNER_LEASE_SECS + 5);
	let tx = ds.transaction(TransactionType::Write).await?;
	tx.del_prefix_key(&IdxRoot {
		ns: ikb.ns(),
		db: ikb.db(),
		tb: Cow::Borrowed(ikb.table()),
		ix: ikb.index(),
	})
	.await?;
	tx.set_key(
		&ikb.new_bs_key(),
		&IndexBuildState {
			generation: 2,
			phase: IndexBuildPhase::Building,
			owner: Some(Uuid::new_v4()),
			next_ticket: 0,
			initial_complete: false,
			updated_at: expired,
			owner_heartbeat_at: Some(expired),
			error: None,
			report_status: Some(IndexBuildReportStatus::Indexing),
			initial: cursor.as_ref().map(|_| 1),
			updated: None,
			pending: None,
			initial_cursor: cursor,
		},
	)
	.await?;
	tx.commit().await
}

/// Takes over the build of `ix` on `table` and runs it to the end.
async fn take_over_build(
	ds: &Datastore,
	session: &Session,
	(ns, db, table, ix): (NamespaceId, DatabaseId, &TableName, &Arc<IndexDefinition>),
) -> Result<()> {
	let build = new_building_for_index(ds, session, ns, db, table, Arc::clone(ix)).await?;
	let acquired = build
		.acquire_build_state()
		.await?
		.expect("expired build state should be available for takeover");
	build.run_acquired(acquired).await
}

/// A COUNT build taken over from a checkpoint rescans when resuming would leave
/// an older node's marker unmet.
///
/// An older node deleted `[42, 'intro']` before the scan, and its marker sorts
/// after `[42, 'k']`, where the previous owner's last batch ended: the next span
/// would have counted the record. A resume rebuilds that marker at the
/// record's own key, behind the checkpoint, where nothing meets it again.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_takeover_rescans_rather_than_leave_an_older_marker_unmet() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 CREATE t:[42, 'k'] SET a = 1;
		 CREATE t:[43, 'x'] SET a = 1;
		 DEFINE INDEX ic ON t COUNT;",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "ic").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	strand_count_build(&ds, &ikb, Some(number_then_string(42, "k"))).await?;
	let tx = ds.transaction(TransactionType::Write).await?;
	let delete = mutation(&number_then_string(42, "intro"), true, false);
	queue_in_previous_encoding(&tx, &ikb, 2, 1, delete, true).await?;
	tx.commit().await?;

	take_over_build(&ds, &session, (ns, db, &table, &ix)).await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	// A resume would report 1 checkpointed and `[43, 'x']`.
	assert_eq!(state.initial, Some(3), "both live records and `[42, 'intro']`, rescanned");
	assert_eq!(count_query_value(&ds, &session, "SELECT count() FROM t GROUP ALL").await?, 2);
	Ok(())
}

/// A COUNT takeover of a checkpoint a previous release's owner wrote rescans
/// when one of its markers names a record at or before the cursor.
///
/// That owner's merge covered its markers in the index format's order, which
/// puts the gone `[1, 'z']`'s marker after `[1f]`'s key under this release,
/// although the record sorts before `[1f]`. Resuming after `[1f]` would never
/// count it.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_count_takeover_rescans_a_checkpoint_that_would_lose_a_record() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 CREATE t:[1, 'a'] SET a = 1;
		 CREATE t:[1f] SET a = 1;
		 CREATE t:[2] SET a = 1;
		 DEFINE INDEX ic ON t COUNT;",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "ic").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	let float = RecordIdKey::Array(vec![Value::Number(crate::val::Number::Float(1.0))].into());
	let gone = RecordIdKey::Array(
		vec![Value::Number(crate::val::Number::Int(1)), Value::from("z")].into(),
	);
	// The premise: the gone record sorts before the cursor, its older key after.
	assert!(RecordIdentity(gone.clone()) < RecordIdentity(float.clone()));
	assert!(
		primary_append_key_in_previous_encoding(&ikb, 2, &gone)?
			> ikb.new_bp_key(2, &float).encode_key()?.to_vec()
	);
	strand_count_build(&ds, &ikb, Some(float)).await?;
	let tx = ds.transaction(TransactionType::Write).await?;
	queue_in_previous_encoding(&tx, &ikb, 2, 1, mutation(&gone, true, false), true).await?;
	tx.commit().await?;

	take_over_build(&ds, &session, (ns, db, &table, &ix)).await?;

	let state = durable_build_state(&ds, &ikb).await?;
	assert_eq!(state.phase, IndexBuildPhase::Online);
	assert_eq!(state.initial, Some(4), "the three live records and `[1, 'z']`, rescanned");
	assert_eq!(count_query_value(&ds, &session, "SELECT count() FROM t GROUP ALL").await?, 3);
	Ok(())
}

/// A COUNT build's batch that fails to commit is retried from the merge's
/// progress before it, so the retry merges the same span.
///
/// `t:b` is deleted while the build is in flight, marked at its own key in the
/// batch's span, and the batch's first commit is refused.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_retried_count_batch_merges_its_span_again() -> Result<()> {
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 CREATE t:b SET a = 1;
		 CREATE t:k SET a = 1;
		 DEFINE INDEX ic ON t COUNT;",
	)
	.await?;
	let (ns, db, table, ix) = get_table_index(&ds, "t", "ic").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix.index_id);
	strand_count_build(&ds, &ikb, None).await?;
	execute_all_retrying_conflicts(&ds, &session, "DELETE t:b RETURN NONE").await?;

	let site = RetryableConflictSite::ConcurrentIndexInitialBatch;
	let _guard = inject_retryable_conflict(site, ds.id());
	take_over_build(&ds, &session, (ns, db, &table, &ix)).await?;

	assert_eq!(retryable_conflict_count(site, ds.id()), 0, "the batch was retried");
	assert_eq!(count_query_value(&ds, &session, "SELECT count() FROM t GROUP ALL").await?, 1);
	Ok(())
}

/// A build of any kind baselines a record from the queued old state an older
/// node marked under its spelling.
///
/// An older node updated `[42, 'intro']` from 'old' to 'new', marking it at a
/// key only that spelling gives the record. Indexing the record as it stands
/// would leave replay removing an 'old' that was never indexed.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_build_of_any_kind_baselines_from_an_older_marker() -> Result<()> {
	use surrealdb_types::Value as PublicValue;
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 CREATE t:[42, 'intro'] SET a = 'new';",
	)
	.await?;
	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ia.index_id);
	let building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;
	let generation: BuildGeneration = 1;

	let tx = ds.transaction(TransactionType::Write).await?;
	let update = Appending {
		old_values: Some(vec![Value::from("old")]),
		new_values: Some(vec![Value::from("new")]),
		..mutation(&number_then_string(42, "intro"), true, true)
	};
	queue_in_previous_encoding(&tx, &ikb, generation, 9, update, true).await?;
	tx.commit().await?;
	building.build_generation.store(generation, Ordering::Release);

	let values = scan_records(&ds, ns, db, &table).await?;
	let ctx = building.new_write_tx_ctx().await?;
	let tx = ctx.tx();
	building.index_initial_batch(&ctx, &tx, &values, 0, &mut false, &mut None).await?;
	tx.commit().await?;

	let res = ds.execute("SELECT VALUE id FROM t WHERE a @@ 'old'", &session, None).await?;
	let PublicValue::Array(rows) = res.into_iter().next().expect("one result").result? else {
		anyhow::bail!("unexpected result shape");
	};
	assert_eq!(rows.len(), 1, "`[42, 'intro']` is baselined from its queued old state");
	Ok(())
}

/// The scan baselines a record against a marker only when the marker's queued
/// mutation names that record.
///
/// An older node's marker for `[1, NONE]` sits at the key this release builds
/// for `[1]`. Taking it as `[1]`'s would index `[1]` with another record's
/// queued old state.
#[cfg(feature = "kv-mem")]
#[tokio::test(flavor = "multi_thread")]
#[test_log::test]
async fn a_marker_naming_another_record_is_not_the_scanned_records_baseline() -> Result<()> {
	use surrealdb_types::Value as PublicValue;
	let (ds, session) = new_index_test_ds().await?;
	execute_all(
		&ds,
		&session,
		"DEFINE TABLE t SCHEMALESS;
		 DEFINE ANALYZER simple TOKENIZERS blank;
		 DEFINE INDEX ia ON t FIELDS a FULLTEXT ANALYZER simple BM25;
		 CREATE t:[1] SET a = 'live';",
	)
	.await?;
	let (ns, db, table, ia) = get_table_index(&ds, "t", "ia").await?;
	let ix_id = ia.index_id;
	let ikb = IndexKeyBase::new(ns, db, table.clone(), ix_id);
	let building = new_building_for_index(&ds, &session, ns, db, &table, ia).await?;
	let generation: BuildGeneration = 1;
	let one_none = aliasing_chain(2).pop().expect("two links");

	let tx = ds.transaction(TransactionType::Write).await?;
	queue_with_marker_in_previous_encoding(
		&tx,
		&ikb,
		generation,
		9,
		&one_none,
		Some(vec![Value::from("queued")]),
		true,
	)
	.await?;
	tx.commit().await?;
	building.build_generation.store(generation, Ordering::Release);

	let values = scan_records(&ds, ns, db, &table).await?;
	let ctx = building.new_write_tx_ctx().await?;
	let tx = ctx.tx();
	building.index_initial_batch(&ctx, &tx, &values, 0, &mut false, &mut None).await?;
	tx.commit().await?;

	let matches = |sql: &'static str| {
		let ds = &ds;
		let session = &session;
		async move {
			match ds.execute(sql, session, None).await?.remove(0).result? {
				PublicValue::Array(rows) => Ok(rows.len()),
				other => anyhow::bail!("unexpected result: {other:?}"),
			}
		}
	};
	assert_eq!(
		matches("SELECT VALUE id FROM t WHERE a @@ 'queued'").await?,
		0,
		"`t:[1]` must not be indexed with `[1, NONE]`'s queued state"
	);
	assert_eq!(matches("SELECT VALUE id FROM t WHERE a @@ 'live'").await?, 1);
	Ok(())
}