mahbot 0.11.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! The store layer: the two physical databases this product keeps (`core.db` for every domain
//! store, `logs.db`), the single connection discipline every caller shares — `Connection`,
//! `TxGuard`, `ReaderPool`, `Maintenance` — the transaction helpers, the timestamp and column
//! conventions, the store-facing pragmas, and [`format_cell`], the one display rule every pipe
//! table prints its cells by. The schema lives in `migrations`, the change stream in `cdc`.
//! Not the place to build a store handle: a database opened outside `store` has neither the
//! experimental feature flags nor the per-statement timeout, and the timeout would be silently
//! disarmed.

use anyhow::Context;
use chrono::{DateTime, Utc};
use futures_util::FutureExt;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tracing::{debug, error, info, warn};

use crate::util::UnwrapPoison;

pub(crate) use crate::db::store::Row;
pub(crate) use turso::{IntoParams, Value, params};

pub(crate) mod cdc;
pub mod checkpoint;
pub(crate) mod checkpoint_cause;
pub mod debug;
pub(crate) mod failure_record;
pub mod ipc;
pub(crate) mod migrations;
pub(crate) mod read_limit;
pub(crate) mod shrink_gate;
pub(crate) mod store;
#[cfg(all(unix, test))]
mod store_lock_check;
pub mod wal_guard;

#[must_use]
pub fn now() -> String {
    Utc::now().to_rfc3339()
}

/// Parse an RFC 3339 timestamp into [`DateTime<Utc>`], normalising whatever
/// offset the string carries (all database timestamps are written by [`now`]).
///
/// # Errors
///
/// [`chrono::ParseError`] when the input is not a valid RFC 3339 timestamp.
pub(crate) fn parse_utc_timestamp(s: &str) -> Result<DateTime<Utc>, chrono::ParseError> {
    DateTime::parse_from_rfc3339(s).map(|dt| dt.with_timezone(&Utc))
}

/// Feature names for the experimental Turso features that must be enabled consistently by the
/// running instance and the debug CLI.
///
/// The **single source** for which features are active: `crate::db::store` turns it into the SDK's
/// feature string, [`experimental_database_opts`] is the typed form the read-only debug path opens
/// with, and `db::store::tests::feature_string_matches_the_debug_paths_typed_opts` asserts they
/// agree (also catching a typo — the SDK ignores an unknown name).
///
/// A feature needs the `with_*()` call there and the name here; the two forms do not always spell
/// the same (`with_views()` is `"views"`), and `autovacuum`/`unsafe_testing` are typed-only.
pub(crate) const EXPERIMENTAL_FEATURES: &[&str] = &["index_method"];

/// Name (file stem) of the one consolidated domain database file — board, sessions, workspaces,
/// users, config, chat_history, automations, custom_roles and telegram_intake. They share it (and
/// one [`Connection`]: one writing connection, one transaction domain, one reader pool) so
/// cross-store integrity is enforceable with real foreign keys and phase+stage updates are atomic.
/// The logs store remains a separate file ([`LOG_DB_NAME`]).
pub(crate) const CONSOLIDATED_DB_NAME: &str = "core";

/// Logical store names consolidated into [`CONSOLIDATED_DB_NAME`] via [`store_db_path`]. A subset
/// of the names `mahbot debug --db` accepts ([`debug_db_names`] adds the physical `core`). The logs
/// store is NOT here.
const DOMAIN_STORE_NAMES: &[&str] = &[
    "board",
    "sessions",
    "workspaces",
    "users",
    "config",
    "chat_history",
    "automations",
    "custom_roles",
    "telegram_intake",
];

/// Name (file stem) of the logs store — the one store that stays a separate
/// file/connection. Opened manually in [`crate::logs::init_tracing`] before the
/// other stores; its schema is owned by the catalog ([`crate::db::migrations`]).
pub(crate) const LOG_DB_NAME: &str = "logs";

/// The single shared consolidated domain connection, set once by [`init_all_stores`]. Every domain
/// store struct holds a clone of this handle: one writing connection (the one transaction domain)
/// and one reader pool. The logs store does NOT use it.
pub(crate) static DOMAIN_CONN: tokio::sync::OnceCell<Connection> =
    tokio::sync::OnceCell::const_new();

/// An iterator over all **physical, checkpointable** stores: `(name, connection or `None` while
/// uninitialized)`. The single source of truth for which files exist — after consolidation exactly
/// two ([`CONSOLIDATED_DB_NAME`] and [`LOG_DB_NAME`]). Deliberately not [`store_names`], which
/// lists logical names several of which share one physical file.
pub(crate) fn iter_checkpoint_stores()
-> impl Iterator<Item = (&'static str, Option<&'static crate::db::Connection>)> {
    [
        (CONSOLIDATED_DB_NAME, DOMAIN_CONN.get()),
        (LOG_DB_NAME, crate::logs::LOG_STORE.get().map(|s| &s.conn)),
    ]
    .into_iter()
}

/// All canonical **logical** store names accepted by `mahbot debug --db`: the domain names plus
/// `logs`, each mapping to a physical file via [`store_db_path`]. Not derived from
/// [`iter_checkpoint_stores`] (which enumerates physical files): adding a domain store extends
/// [`DOMAIN_STORE_NAMES`] alone.
pub(crate) fn store_names() -> Vec<&'static str> {
    let mut names: Vec<&'static str> = DOMAIN_STORE_NAMES.to_vec();
    names.push(LOG_DB_NAME);
    names
}

/// Every accepted `--db` selector for the read-only surface (the CLI argument and the
/// `mahbot_debug` tool's `db`): [`store_names`] plus the physical [`CONSOLIDATED_DB_NAME`]. The
/// single derivation of that set, so the validator, the CLI usage text and the tool's schema cannot
/// drift.
pub(crate) fn debug_db_names() -> Vec<&'static str> {
    let mut names = store_names();
    names.push(CONSOLIDATED_DB_NAME);
    names
}

/// Initialize all domain stores: the canonical init path.
///
/// The `logs` store is **not** here: it must be initialized earlier via
/// [`crate::logs::init_tracing`] and holds the stats tables. All domain stores share ONE file
/// ([`CONSOLIDATED_DB_NAME`]) and ONE [`Connection`] ([`DOMAIN_CONN`]), so `begin_tx` on any store
/// takes the same mutex. The schema is applied once by [`open_consolidated_store`], and the
/// idempotent post-open hooks (tickets FTS index, admin-user seed) run in a defined order first.
pub async fn init_all_stores() -> anyhow::Result<()> {
    // Idempotent: the consolidated connection is set once. Re-entering (e.g.
    // a test that calls init_test_stores twice) must not re-open / re-migrate.
    if DOMAIN_CONN.get().is_some() {
        return Ok(());
    }

    let root = crate::config::CONFIG.global_storage_root();
    let conn = open_consolidated_store(&root).await?;

    // Run the idempotent per-store post-open hooks on the shared connection, in a defined order,
    // before exposing the store cells.
    let board = crate::pipeline::board::BoardStore { conn: conn.clone() };
    board.after_open().await?;
    let users = crate::users::UserStore { conn: conn.clone() };
    users.ensure_admin_user().await?;

    let session = crate::session::SessionStore { conn: conn.clone() };
    let workspace = crate::workspace::WorkspaceStore { conn: conn.clone() };
    let config = crate::config_db::ConfigStore { conn: conn.clone() };
    let chat_history = crate::channels::chat_history::ChatHistoryStore { conn: conn.clone() };
    let telegram_intake =
        crate::channels::telegram_intake::TelegramIntakeStore { conn: conn.clone() };
    let automations = crate::automations::AutomationStore { conn: conn.clone() };
    let custom_roles = crate::custom_role::CustomRoleStore { conn: conn.clone() };

    // Record the shared connection before setting any cell so a concurrent re-entry observes it and
    // short-circuits.
    let _ = DOMAIN_CONN.set(conn.clone());

    // Start the CDC drain loop once (it broadcasts ticket changes to the GUI and
    // the chronicle); a reopen re-enables capture in open_consolidated_store.
    crate::db::cdc::spawn_drainer(conn.clone());

    init_cell(&crate::pipeline::board::BOARD, board, "BOARD")?;
    init_cell(&crate::session::SESSIONS, session, "SESSIONS")?;
    init_cell(&crate::workspace::WORKSPACES, workspace, "WORKSPACES")?;
    init_cell(&crate::users::USER_STORE, users, "USER_STORE")?;
    init_cell(&crate::config_db::CONFIG_STORE, config, "CONFIG_STORE")?;
    init_cell(
        &crate::channels::chat_history::CHAT_HISTORY,
        chat_history,
        "CHAT_HISTORY",
    )?;
    init_cell(
        &crate::channels::telegram_intake::TELEGRAM_INTAKE,
        telegram_intake,
        "TELEGRAM_INTAKE",
    )?;
    init_cell(&crate::automations::AUTOMATIONS, automations, "AUTOMATIONS")?;
    init_cell(
        &crate::custom_role::CUSTOM_ROLES,
        custom_roles,
        "CUSTOM_ROLES",
    )?;

    Ok(())
}

/// Set a store's global cell exactly once, failing with the store's canonical
/// "already initialized" error otherwise (`name` is the cell's literal name).
fn init_cell<T>(cell: &tokio::sync::OnceCell<T>, value: T, name: &str) -> anyhow::Result<()> {
    cell.set(value)
        .map_err(|_| anyhow::anyhow!("{name} already initialized"))
}

/// [`turso::core::DatabaseOpts`] with every experimental feature enabled — the typed form of
/// [`EXPERIMENTAL_FEATURES`], used by the read-only debug path.
///
/// Every engine experimental field is a deliberate decision: one the engine adds later defaults
/// off, and a field is only really active if its name is also in [`EXPERIMENTAL_FEATURES`]. The
/// instance runs in default single-process mode (no `multiprocess_wal`). Forensic-family reads use
/// these same opts, since the snapshots come from stores created with `index_method`.
///
/// Adding a feature: the `with_*()` call here plus the name there.
#[must_use]
pub(crate) fn experimental_database_opts() -> turso::core::DatabaseOpts {
    turso::core::DatabaseOpts::new().with_index_method(true)
}

/// Characters Tantivy's query grammar treats as syntax operators, so FTS queries must strip them.
/// Others (`.`, `@`, `#`, `_`, `/`, `$`, `%`, `!`, `,`, `?`) are safe word characters and stay,
/// which is what keeps search precision. Source: Tantivy's `query_grammar.rs`.
static TANTIVY_SPECIAL: &[char] = &[
    '+', // Must (term must be present)
    '^', // Boost modifier
    '~', // Proximity / fuzzy — conservative guard; Tantivy only treats ~ as
    // a modifier when it appears after a term/phrase, but stripping it in other positions is
    // harmless.
    ':', // Field specifier
    '{', '}', // Exclusive range
    '"', '\'', // Phrase query delimiters
    '`',  // ESCAPE_IN_WORD — strict parser rejects backtick at any position
    '[', ']', // Inclusive range
    '(', ')',  // Grouping / sub-query
    '\\', // Escape character
    '*',  // Wildcard / prefix operator
    '-',  // MustNot (negation) at word start; word boundary elsewhere
];

/// Sanitize a user-supplied query for Tantivy FTS, stripping syntax operators.
///
/// Required because turso's FTS parses with Tantivy, whose parser errors on user text — a Tantivy
/// design decision, not a turso version bug, so upgrading turso will not remove the need. The
/// `ngram` tokenizer indexes character substrings, so stripping loses no search quality, and
/// non-special punctuation (emails, `my_function`, `feature/x`) is preserved.
///
/// A leading `/` is stripped too (Tantivy's lenient parser would read a regex), and a query of
/// nothing but specials yields an empty string for callers to short-circuit on.
#[must_use]
pub(crate) fn sanitize_fts_query(query: &str) -> String {
    query
        .split(|c: char| c.is_whitespace() || TANTIVY_SPECIAL.contains(&c))
        .map(|word| word.trim_start_matches('/'))
        .filter(|word| !word.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Comma-separated `?` placeholders for SQL IN-clauses; empty for `count == 0`, so callers MUST
/// guard an empty list (`WHERE id IN ()` is invalid SQL). Turso binds `Vec<Value>` positionally for
/// `?` and `?N` alike, so numbered placeholders are never needed — use this helper everywhere.
#[must_use]
pub(crate) fn sql_in_placeholders(count: usize) -> String {
    vec!["?"; count].join(", ")
}

/// A handle to one store's connections: the one **writing connection** every change and the store's
/// own upkeep (see [`Upkeep`]) run on, under a mutex; the [`ReaderPool`] that serves reads without
/// touching it; and [`Maintenance`], what the periodic round makes.
///
/// The engine takes many reads per connection but does **not** queue a second *write* behind the
/// first: one starting while another is in progress is rejected outright (a busy error), because a
/// write can suspend for async I/O. The one-at-a-time sequencing is therefore our own queue.
///
/// A transaction left open is rolled back before the connection is reused (a [`TxGuard`] dropped
/// without commit/rollback arms the flag the next write acts on), and the mutex is NOT reentrant
/// across a clone: a path holding a [`TxGuard`] MUST use `tx.query()` / `tx.execute()` /
/// `tx.begin_tx()`. A read issued by the very task holding the transaction is refused
/// ([`Connection::run_read`]); any other task's read is unrelated and sees committed state.
#[derive(Clone, Debug)]
pub(crate) struct Connection {
    conn: Arc<tokio::sync::Mutex<store::Connection>>,
    has_dangling_tx: Arc<AtomicBool>,
    /// The task that opened the transaction on `conn`, cleared on commit or
    /// rollback: its own reads are refused on the read entry (see [`Self::run_read`]).
    tx_task: Arc<std::sync::Mutex<Option<tokio::task::Id>>>,
    /// The store's main-file path, stamped at open: the pre-shrink gate's stat
    /// source (main and `-wal` sizes), never opened — wal_guard's lock rule.
    db_path: Arc<std::path::Path>,
    /// The open store every connection here is made from — the writing one, the readers and
    /// [`Maintenance`] — never a second open of its file (wal_guard's lock rule).
    db: Arc<store::Database>,
    /// The reader connections; handed the already-open store, created only once the
    /// store is final and a read needs one (see [`Connection::enable_readers`]).
    readers: Arc<ReaderPool>,
}

pub(crate) struct ReadonlyRows {
    pub columns: Vec<String>,
    pub rows: Vec<Vec<Value>>,
    pub truncated: bool,
}

/// A cell as the debug pipe tables print it — display only, never a serialisation: NULL empty,
/// integer decimal, real in the default float spelling, text verbatim, blob lowercase hex.
///
/// Text is not escaped, so a pipe or a newline inside a value breaks the row shape;
/// that and the empty cell are both visible through the `mahbot_debug` output.
///
/// Model control tokens are masked out of text cells: the debug surface hands stored text back
/// verbatim to whoever asked, and a refusal body recorded before the mask existed still carries
/// the token that kills a session which reads it. Masking on read is the only cure that does not
/// rewrite the live store.
pub(crate) fn format_cell(v: &Value) -> String {
    match v {
        Value::Null => String::new(),
        Value::Integer(i) => i.to_string(),
        Value::Real(f) => f.to_string(),
        Value::Text(t) => crate::util::control_token::neutralize_owned(t.clone()),
        Value::Blob(b) => crate::util::hex_string(b),
    }
}

/// Message prefix of a Turso quick_check false positive, kept as a narrow exact-message guard.
///
/// Turso's FTS keeps tantivy chunks in an internal backing index while the dir table stays empty
/// (upstream tursodatabase/turso#7611). Since 0.8.0 the engine skips that cardinality comparison
/// for its own backing-btree indexes, so the row is not emitted and this mask is a no-op. It stays
/// because it is exact and one-directional — other rows naming that index mean real corruption and
/// stay reported, and the never-REINDEX-the-FTS guard leans on the same prefix.
const KNOWN_FTS_DIR_COUNT_FALSE_POSITIVE: &str =
    "wrong # of entries in index __turso_internal_fts_dir_";

/// Name prefix of the internal FTS backing index — never a class-B repair target
/// (FTS rebuild is out of scope); the repair guard matches this, not the message.
const FTS_INTERNAL_INDEX_PREFIX: &str = "__turso_internal_fts_dir_";

/// `sqlite_master` filter for user-owned objects: excludes the engine's own `sqlite_%`, turso's
/// protected `__turso_internal_%` (AUTOINCREMENT seq backing, FTS dir) and the engine-managed CDC
/// tables (they reject user writes and the DDL replay recreates them). Shared by the rebuild's
/// counts, the DDL replay and the debug schema dump so the three cannot drift.
pub(crate) const USER_OBJECT_FILTER: &str = "name NOT LIKE 'sqlite_%' AND name NOT LIKE '__turso_internal_%' \
     AND name NOT IN ('turso_cdc', 'turso_cdc_version')";

/// Best-effort removal of a rebuild temp family (main + `-wal`, paths built by [`wal_path`]).
fn remove_rebuild_temp(temp: &Path) {
    let _ = std::fs::remove_file(temp);
    let _ = std::fs::remove_file(wal_path(temp));
}

/// RAII cleanup of the rebuild temp family: every exit — including a turso panic
/// mid-copy (the documented pager-OOB class) — removes the temp main + `-wal`.
/// `open_store` absorbs the panic as a refusal, so the data is discarded either way.
struct TempCleanup<'a>(&'a Path);
impl Drop for TempCleanup<'_> {
    fn drop(&mut self) {
        remove_rebuild_temp(self.0);
    }
}

/// True when a `quick_check` message names the internal FTS backing index — the broader
/// never-REINDEX-the-FTS guard (the row scan masks only the exact count-mismatch message).
#[must_use]
fn known_fts_dir_false_positive(message: &str) -> bool {
    message.contains(FTS_INTERNAL_INDEX_PREFIX)
}

/// Map each row through a fallible closure into a `Vec<turso::Result<T>>`; shared by
/// [`Connection::query_map`], `query_map_strict`, `query_map_strict_cached`, [`Upkeep::query_map`]
/// and [`TxGuard::query_map_strict`].
fn map_rows<T, E>(
    rows: &[Row],
    mut map: impl FnMut(&Row) -> std::result::Result<T, E>,
) -> Vec<turso::Result<T>>
where
    E: std::fmt::Display,
{
    rows.iter()
        .map(|row| map(row).map_err(|e| turso::Error::Error(e.to_string())))
        .collect()
}

/// Fold [`turso::Error::QueryReturnedNoRows`] into `Ok(None)` and any other error into
/// `anyhow::Error`.
fn optional_row<T>(r: turso::Result<T>) -> anyhow::Result<Option<T>> {
    match r {
        Ok(val) => Ok(Some(val)),
        Err(::turso::Error::QueryReturnedNoRows) => Ok(None),
        Err(e) => Err(e.into()),
    }
}
/// Map the first row of a stream (empty → `QueryReturnedNoRows`), per-row errors to
/// `turso::Error::Error`; shared by [`Connection::query_row_impl`] and `query_row_cached`.
async fn map_first_row<T, E>(
    mut rows: store::Rows,
    map: impl FnOnce(&Row) -> std::result::Result<T, E>,
) -> turso::Result<T>
where
    E: std::fmt::Display,
{
    let row = rows
        .next()
        .await?
        .ok_or(turso::Error::QueryReturnedNoRows)?;
    map(&row).map_err(|e| turso::Error::Error(e.to_string()))
}

fn strict_collect<T>(rows: Vec<turso::Result<T>>) -> anyhow::Result<Vec<T>> {
    rows.into_iter()
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(Into::into)
}

/// Drain a turso row stream into a `Vec` of [`Row`]s (unbounded — callers know the query shape).
async fn drain_rows(mut rows: store::Rows) -> turso::Result<Vec<Row>> {
    let mut result = Vec::new();
    while let Some(row) = rows.next().await? {
        result.push(row);
    }
    Ok(result)
}

/// Await a detached statement op — shared by [`Connection::run_detached_capturing`],
/// [`Maintenance::run_statement`] and a reader ([`ReaderLease::run`]), so the places cannot drift
/// in what they do with the outcome.
///
/// A panicking op propagates the ORIGINAL payload (only the message survives, not the location). A
/// cancelled task means runtime shutdown, not a DB failure.
fn join_detached<T>(
    joined: std::result::Result<turso::Result<T>, tokio::task::JoinError>,
) -> turso::Result<T> {
    match joined {
        Ok(inner) => inner,
        Err(joined) => match joined.try_into_panic() {
            Ok(payload) => std::panic::resume_unwind(payload),
            Err(_) => Err(turso::Error::Error(
                "database op cancelled (runtime shutdown)".to_string(),
            )),
        },
    }
}

/// Drive `task` to completion in a detached runtime task, with `cause` armed for its polls when
/// given (see [`checkpoint_cause`]). See [`Connection::run_detached`] for why a statement must
/// never be driven by a caller's future.
async fn spawn_detached<T: Send + 'static>(
    task: impl Future<Output = turso::Result<T>> + Send + 'static,
    cause: Option<checkpoint_cause::CauseSink>,
) -> turso::Result<T> {
    let joined = match cause {
        Some(cause) => tokio::spawn(cause.scoped(task)).await,
        None => tokio::spawn(task).await,
    };
    join_detached(joined)
}

/// Lock the writing connection and roll back any dangling transaction; every caller on the
/// writing connection uses this — one left active affects read visibility in WAL mode.
async fn run_readonly_query(
    conn: &store::Connection,
    sql: &str,
    params: impl IntoParams + Send + 'static,
    row_limit: usize,
) -> turso::Result<ReadonlyRows> {
    let mut rows = conn.query(sql, params)?;
    let columns = rows.column_names();
    let col_count = columns.len();
    let mut result_rows = Vec::new();
    let mut count = 0usize;
    let mut truncated = false;
    while let Some(row) = rows.next().await? {
        if count >= row_limit {
            truncated = true;
            break;
        }
        let mut values = Vec::with_capacity(col_count);
        for idx in 0..col_count {
            values.push(row.get_value(idx)?);
        }
        result_rows.push(values);
        count += 1;
    }
    Ok(ReadonlyRows {
        columns,
        rows: result_rows,
        truncated,
    })
}

const OPEN_LOCK_RETRY_ATTEMPTS: usize = 10;

const OPEN_LOCK_RETRY_DELAY: Duration = Duration::from_millis(500);

/// Step prefix of [turso_core]'s locking-error variant as it survives into the message: the
/// variant's `Display` prefix (`Locking error:`) plus the failing step. It covers the two steps
/// that take the open-time lock and excludes the variant's other uses, which take no lock.
/// `turso_sdk_kit` collapses the typed variant into a plain string, so a step prefix is the most a
/// predicate can key on. [turso_core]: https://github.com/tursodatabase/turso
const LOCK_STEP_PREFIX: &str = "Locking error: Failed locking";

/// The engine's wording for a lock contended by another process, where the conflict reaches it as
/// `ErrorKind::WouldBlock` (`F_SETLK` → `EAGAIN`).
const LOCK_CONTENTION_MARKER: &str = "File is locked by another process";

/// Windows' contention code, as it reaches us inside the engine's message.
/// `LockFileEx` reports `ERROR_LOCK_VIOLATION` (33), which std maps to `Uncategorized` rather than
/// `WouldBlock`, so the engine echoes the OS text: `"Failed locking file, <localised OS text> (os
/// error 33)"`. The text is localised and the code is not — and 33 is what std's `try_lock`
/// matches.
const WINDOWS_LOCK_VIOLATION_CODE: &str = "(os error 33)";

/// Whether an error is the transient open-time store lock from
/// [turso_core](https://github.com/tursodatabase/turso).
///
/// [`store::Database::open`] takes a whole-file fcntl `F_SETLK` `F_WRLCK` record lock on the files
/// it opens read-write — main and `-wal` (wal_guard's lock rule) — and `busy_timeout` does **not**
/// cover it: that governs per-statement waits only.
///
/// The conjunction of [`LOCK_STEP_PREFIX`] and one contention token is load-bearing both ways: the
/// step alone would retry uncontended lock failures and call them contention, the `WouldBlock`
/// wording alone would never match on Windows. `Busy("database is locked")` and table-level locks
/// are never this.
///
/// Guarded asymmetrically: `db::store_lock_check` drives a real contended open, so the Unix half
/// fails loudly on a wording change while the Windows token has no witness. The opt-in IOCP backend
/// is covered only half-way — its main-file path emits a localised message with neither prefix nor
/// code — so that vfs would disable the retry.
fn is_open_time_lock_error(err: &turso::Error) -> bool {
    let turso::Error::Error(msg) = err else {
        return false;
    };
    msg.contains(LOCK_STEP_PREFIX)
        && (msg.contains(LOCK_CONTENTION_MARKER) || msg.contains(WINDOWS_LOCK_VIOLATION_CODE))
}

/// True when `e` or any cause beneath it is the open-time store lock — another
/// instance holds a store this process is trying to open. Store bring-up records its
/// refusal through this; the repair path decides through [`is_actionable_signal`].
pub(crate) fn is_store_lock_error(e: &anyhow::Error) -> bool {
    e.chain().any(|cause| {
        cause
            .downcast_ref::<turso::Error>()
            .is_some_and(is_open_time_lock_error)
    })
}

/// True when `e` or any cause beneath it is a store (Turso) failure — the database
/// itself could not serve the operation, as opposed to a verdict about the data.
pub(crate) fn is_store_error(e: &anyhow::Error) -> bool {
    e.chain()
        .any(|cause| cause.downcast_ref::<turso::Error>().is_some())
}

/// A store that exists but is not positively recognised as usable: the service
/// refuses to start and leaves its files exactly as they are — nothing created,
/// modified, renamed or deleted, no schema, migration or admin account built.
#[derive(Debug)]
pub(crate) struct StoreRefusal {
    pub store: &'static str,
    pub db_path: std::path::PathBuf,
    pub reason: String,
    /// True when the refusal is an environment condition (unreadable file, resource exhaustion,
    /// permissions) rather than evidence about the store's contents: it is recorded as
    /// environment-caused, never as damage.
    pub environment: bool,
}

impl StoreRefusal {
    #[must_use]
    pub(crate) fn new(store: &'static str, db_path: &Path, reason: impl Into<String>) -> Self {
        Self {
            store,
            db_path: db_path.to_path_buf(),
            reason: reason.into(),
            environment: false,
        }
    }

    #[must_use]
    pub(crate) fn with_environment(mut self, environment: bool) -> Self {
        self.environment = environment;
        self
    }
}

impl std::fmt::Display for StoreRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "refusing to start: store '{}' is not usable — {}",
            self.store, self.reason
        )
    }
}

impl std::error::Error for StoreRefusal {}

/// Retries `attempt` only for the transient open-time store lock ([`is_open_time_lock_error`] is
/// the sole test): the previous process still holds the store locks briefly during a self-update
/// restart, and this bounded retry absorbs that race without masking any other open failure.
/// `attempts` counts retries *after* the first try, so total tries are `attempts + 1`.
async fn with_open_lock_retry<T, F, Fut>(
    attempts: usize,
    delay: Duration,
    mut attempt: F,
) -> Result<T, turso::Error>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, turso::Error>>,
{
    let mut remaining = attempts;
    loop {
        match attempt().await {
            Ok(value) => return Ok(value),
            Err(err) if is_open_time_lock_error(&err) => {
                warn!(
                    attempt = attempts - remaining + 1,
                    total_attempts = attempts + 1,
                    error = ?err,
                    "database open blocked by another process (open-time store lock)"
                );
                if remaining == 0 {
                    return Err(err);
                }
                tokio::time::sleep(delay).await;
                remaining -= 1;
            }
            Err(err) => return Err(err),
        }
    }
}

/// Which connection an access runs on. The two places differ in that and nothing else: the same
/// detached task, the same panic propagation, the same handling of a cancelled task (see
/// [`join_detached`]) — one runner keeps a read and an upkeep read from drifting apart.
enum Place {
    Read,
    Writer,
}

impl Connection {
    pub async fn open(path: &Path) -> anyhow::Result<Self> {
        let path_str = path
            .to_str()
            .with_context(|| format!("database path must be UTF-8: {}", path.display()))?;
        // The store handle comes from the connection layer, which opens with the
        // string form of EXPERIMENTAL_FEATURES (see `experimental_database_opts`).
        let db = with_open_lock_retry(OPEN_LOCK_RETRY_ATTEMPTS, OPEN_LOCK_RETRY_DELAY, || async {
            store::Database::open(path_str).await
        })
        .await
        .context("failed to open local database")?;
        let db = Arc::new(db);
        let conn = db.connect()?;
        conn.busy_timeout(BUSY_TIMEOUT);
        // In-memory temp storage (turso's TempStore::Memory): every intermediate query structure —
        // RETURNING buffers, ORDER BY/LIMIT heap sorts, DISTINCT, IN-subqueries, compound SELECTs,
        // window functions, CREATE INDEX, sorter/hash-join spills — stays in RAM and never touches
        // a temp dir. turso_core's tempdir creation has no parent-creation and no fallback, and
        // resolves through $TMPDIR, which the instance pins to its private root: a missing root
        // used to fail every eager-temp statement with "I/O error (tempdir): entity not found". An
        // engine that rejects the PRAGMA fails this open loudly instead of regressing to
        // disk-backed temp.
        conn.execute("PRAGMA temp_store = MEMORY;", ())
            .await
            .context("failed to set in-memory temp storage (PRAGMA temp_store = MEMORY)")?;
        Ok(Self {
            conn: Arc::new(tokio::sync::Mutex::new(conn)),
            has_dangling_tx: Arc::new(AtomicBool::new(false)),
            tx_task: Arc::new(std::sync::Mutex::new(None)),
            db_path: Arc::from(path),
            // The store handle is kept so every connection of this store is made from
            // this one open store — never a second open of its file (wal_guard's rule).
            db: Arc::clone(&db),
            readers: Arc::new(ReaderPool::new(db)),
        })
    }

    pub(crate) fn db_path(&self) -> &std::path::Path {
        &self.db_path
    }

    pub(crate) async fn maintenance(&self) -> anyhow::Result<Maintenance> {
        let conn = read_only_connection(&self.db, "the store's maintenance connection")
            .await
            .map_err(anyhow::Error::msg)?;
        Ok(Maintenance {
            conn: Arc::new(conn),
            db_path: Arc::clone(&self.db_path),
        })
    }

    /// Let this store's connections serve reads.
    ///
    /// Called once the store is final — after anything that can replace or rebuild its file — and
    /// never for a store a reader must not be made from (the log store has no reader pool). Costs
    /// nothing: readers are created by the first read that needs one.
    ///
    /// Later maintenance that rebuilds a schema object takes the readers out of service itself
    /// ([`Self::quiet_readers`]) rather than resting on no read having happened yet.
    fn enable_readers(&self) {
        self.readers.enable();
    }

    /// Take the readers out of service for work that must not run while one is in use — a schema
    /// object dropped and recreated under a reader's own snapshot — returning `None` when they did
    /// not fall idle within [`READERS_IDLE_WAIT`] or the shortened wait a check sets; the caller
    /// then leaves that work for a later round. While the guard is held reads are served by the
    /// writing connection and the readers are closed. Dropping it puts them back — unless the store
    /// released them for good ([`Self::release_readers`]), which a late guard must not undo.
    async fn quiet_readers(&self) -> Option<QuietReaders> {
        self.readers.quiet().await
    }

    /// Release the readers for good, before the exit round's checkpoint runs on the writing
    /// connection. The writing connection is never dropped, so this is what makes sure no reader
    /// holds a reading position when that checkpoint tries to truncate the WAL. A reader that
    /// misses [`READERS_IDLE_WAIT`] is left to the runtime: the checkpoint then answers "blocked",
    /// which the exit round expects rather than a failure.
    pub(crate) async fn release_readers(&self) {
        self.readers.release().await;
    }

    /// Lock the writing connection and roll back any dangling transaction — the entry both read and
    /// write callers on it use.
    async fn lock_and_cleanup(&self) -> tokio::sync::MutexGuard<'_, store::Connection> {
        Self::lock_and_cleanup_owned(&self.conn, &self.has_dangling_tx, &self.tx_task).await
    }

    /// Owned-handle variant of [`Self::lock_and_cleanup`] for the detached task in
    /// [`Self::run_detached`].
    ///
    /// A transaction left open MUST be rolled back before the connection is reused: the engine
    /// keeps its written pages in that connection's page cache, and a WAL checkpoint refuses to
    /// clear a cache with dirty pages (`Failed to clear page cache: Dirty { pgno: … }`) — every
    /// later write then fails. Both sources are covered: the deferred arm ([`TxGuard::drop`],
    /// [`Self::begin_tx`]) and the connection's autocommit state. A failed rollback keeps the arm
    /// set so the next access retries it; `tx_task` is cleared whenever nothing is left open.
    async fn lock_and_cleanup_owned<'a>(
        conn: &'a tokio::sync::Mutex<store::Connection>,
        has_dangling_tx: &'a AtomicBool,
        tx_task: &'a std::sync::Mutex<Option<tokio::task::Id>>,
    ) -> tokio::sync::MutexGuard<'a, store::Connection> {
        let guard = conn.lock().await;
        let armed = has_dangling_tx.swap(false, Ordering::SeqCst);
        // The engine's autocommit state decides: `true` means nothing is open, so a
        // stale arm is only cleared — a doomed ROLLBACK would keep the arm set for every
        // later access. The same rule the `query_only` reset in `query_readonly` uses.
        if guard.is_autocommit() {
            *tx_task.lock().unwrap_poison() = None;
        } else {
            match guard.execute("ROLLBACK", ()).await {
                Ok(_) => {
                    *tx_task.lock().unwrap_poison() = None;
                    tracing::warn!(
                        armed,
                        "rolled back a transaction left open on the writing connection"
                    );
                }
                Err(e) => {
                    // Keep the arm: one failed rollback must not lose the orphan.
                    has_dangling_tx.store(true, Ordering::SeqCst);
                    tracing::warn!(
                        error = %e,
                        armed,
                        "failed to roll back a transaction left open on the writing connection — \
                         the next access retries it"
                    );
                }
            }
        }
        guard
    }

    /// Drive a statement op to completion even if the caller's future is dropped mid-await (a
    /// `select!` shutdown cut, a task abort, a timeout): the op runs in a DETACHED task, so a
    /// dropped caller abandons only the RESULT.
    ///
    /// Mandatory: dropping a future mid-statement leaves the writing connection's pager state
    /// inconsistent — a cache-published page whose read never completes makes every later read of
    /// that page wait on a yield nothing will wake (turso's yields assume a fiber scheduler; the
    /// tokio wrapper has none), hanging every later op process-wide.
    async fn run_detached<T, F>(&self, op: F) -> turso::Result<T>
    where
        T: Send + 'static,
        F: for<'a> FnOnce(
                &'a store::Connection,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = turso::Result<T>> + Send + 'a>,
            > + Send
            + 'static,
    {
        self.run_detached_capturing(op, None).await
    }

    /// [`Self::run_detached`] with an engine-cause sink: the sink arms the engine-cause capture for
    /// the op's own polls (see [`checkpoint_cause`]), so the captured reason belongs to this call
    /// and no other.
    async fn run_detached_capturing<T, F>(
        &self,
        op: F,
        cause: Option<&checkpoint_cause::CauseSink>,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        F: for<'a> FnOnce(
                &'a store::Connection,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = turso::Result<T>> + Send + 'a>,
            > + Send
            + 'static,
    {
        let conn = self.conn.clone();
        let dangling = self.has_dangling_tx.clone();
        let tx_task = self.tx_task.clone();
        let task = async move {
            let guard = Self::lock_and_cleanup_owned(&conn, &dangling, &tx_task).await;
            op(&guard).await
        };
        spawn_detached(task, cause.cloned()).await
    }

    /// Upsert one row without the engine's `INSERT ... ON CONFLICT ... DO UPDATE` form:
    /// `update_sql` runs first, and when it matched no row `insert_sql` creates one.
    ///
    /// `insert_sql` must be an `INSERT ... ON CONFLICT ... DO NOTHING`, so a row created by another
    /// writer in between is not an error; that insert reports zero rows and the update runs once
    /// more, so the caller's values win. `update_params` is a closure because the update can run
    /// twice. For an atomic pair use [`TxGuard::upsert_row`], never this — it would re-lock the
    /// mutex the guard holds.
    ///
    /// The engine's own upsert form is unusable under change capture (`PRAGMA
    /// capture_data_changes_conn`): its `DO UPDATE` branch aborts with a record-decode error, and
    /// the precise condition is not isolated. A caller wrapping this error must render the whole
    /// `anyhow` chain (`?e`, `{:#}`) — `%e` hides it.
    pub async fn upsert_row<U, I>(
        &self,
        update_sql: &str,
        update_params: impl Fn() -> U,
        insert_sql: &str,
        insert_params: I,
    ) -> turso::Result<()>
    where
        U: IntoParams + Send + 'static,
        I: IntoParams + Send + 'static,
    {
        if self.execute(update_sql, update_params()).await? > 0 {
            return Ok(());
        }
        if self.execute(insert_sql, insert_params).await? == 0 {
            self.execute(update_sql, update_params()).await?;
        }
        Ok(())
    }

    pub async fn execute(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<u64> {
        let sql = sql.to_owned();
        self.run_detached(move |conn| Box::pin(async move { conn.execute(&sql, params).await }))
            .await
    }

    /// Execute a write through the engine's prepared-statement cache (turso re-parses SQL per
    /// call); see [`Self::query_cached`] for the cache contract.
    pub(crate) async fn execute_cached(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<u64> {
        let sql = sql.to_owned();
        self.run_detached(move |conn| {
            Box::pin(async move {
                let mut stmt = conn.prepare_cached(&sql)?;
                stmt.execute(params).await
            })
        })
        .await
    }

    pub(crate) async fn execute_batch(&self, sql: &str) -> turso::Result<()> {
        let sql = sql.to_owned();
        self.run_detached(move |conn| Box::pin(async move { conn.execute_batch(&sql).await }))
            .await
    }

    /// Execute a **change** that reads its own result back — an `INSERT` or `UPDATE ... RETURNING`,
    /// or a change whose result the caller needs. This is the change entry that hands rows back:
    /// the direction of a call is never inferred from its name, so a change through [`Self::query`]
    /// is a bug (a reader refuses it loudly) while a read through this one takes the writing
    /// connection. The engine's `execute` discards rows, and reading a change's own result in the
    /// same statement settles a read-then-act sequence. The statement is prepared per call;
    /// [`Self::execute_rows_cached`] is for invariant SQL text.
    pub(crate) async fn execute_rows(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        self.query_at(Place::Writer, sql, params).await
    }

    /// [`Self::execute_rows`] through the prepared-statement cache (see [`Self::query_cached`] for
    /// the contract).
    pub(crate) async fn execute_rows_cached(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        self.query_cached_at(Place::Writer, sql, params).await
    }

    /// Execute a **change** that reads its own result back and must produce exactly one
    /// row — [`Self::execute_rows`] with [`Self::query_row`]'s no-row semantics.
    pub(crate) async fn execute_one<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        self.query_row_at(Place::Writer, sql, params, map).await
    }

    /// Execute a **change** that reads its own result back and may produce no row —
    /// [`Self::execute_one`] with [`Self::query_optional`]'s `Ok(None)` semantics.
    pub(crate) async fn execute_optional<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> anyhow::Result<Option<T>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        optional_row(self.execute_one(sql, params, map).await)
    }

    /// Begin a transaction and return a guard that keeps the writing connection locked until the
    /// transaction is committed or rolled back.
    pub async fn begin_tx(&self) -> turso::Result<TxGuard<'_>> {
        let conn = self.lock_and_cleanup().await;
        // Arm the flag BEFORE `BEGIN` is awaited: this statement runs in the caller's
        // future, so an error, a dropped future (cancel, timeout, shutdown cut) or a
        // panic would otherwise leave the transaction open with nothing armed.
        self.has_dangling_tx.store(true, Ordering::SeqCst);
        conn.execute("BEGIN", ()).await?;
        // Only now is this task the holder of a transaction, and no await separates the
        // successful `BEGIN` from this store — so a failure, dropped future or panic
        // before this point cannot record a task as holding one. Unchanged until the
        // guard clears it, so this task's reads are refused for as long as the
        // transaction is open instead of being served by a reader behind its back.
        *self.tx_task.lock().unwrap_poison() = tokio::task::try_id();
        self.has_dangling_tx.store(false, Ordering::SeqCst);
        Ok(TxGuard {
            conn,
            has_dangling_tx: Some(self.has_dangling_tx.clone()),
            tx_task: Some(self.tx_task.clone()),
        })
    }

    /// Execute a read, returning all matching rows: on a reader when the store has one
    /// free, on the writing connection otherwise (see [`Self::run_read`]).
    pub async fn query(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        self.query_at(Place::Read, sql, params).await
    }

    async fn query_at(
        &self,
        place: Place,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        let owned = sql.to_owned();
        self.run_at(place, sql, move |conn| {
            Box::pin(async move { Self::query_impl(conn, &owned, params).await })
        })
        .await
    }

    /// Run an op on the connection `place` names: [`Self::run_read`] or the writing connection.
    /// Everything else — detached task, panic propagation, cancelled-task handling — is shared, so
    /// the two cannot drift. `sql` is the statement as written: the read entry needs it for its
    /// guard ([`reader_refusal`]), the writing connection does not look at it.
    async fn run_at<T, F>(&self, place: Place, sql: &str, op: F) -> turso::Result<T>
    where
        T: Send + 'static,
        F: for<'a> FnOnce(
                &'a store::Connection,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = turso::Result<T>> + Send + 'a>,
            > + Send
            + 'static,
    {
        match place {
            Place::Read => self.run_read(sql, op).await,
            Place::Writer => self.run_detached(op).await,
        }
    }

    /// Run a read on whichever connection serves reads. A read that belongs to a transaction is
    /// served by that transaction: when the calling task holds the open transaction here the read
    /// is refused ([`TRANSACTION_READ_REFUSAL`]) — it must go through the transaction's own
    /// [`TxGuard`], or a reader would serve it and miss what the transaction wrote. Any other
    /// task's read is unrelated and served. Otherwise a reader serves it when one is free, falling
    /// back to the writing connection when the store has no readers, when they could not be
    /// created, and while they are out of service: the fallback is deliberate, readers being a
    /// latency optimisation and never a new failure mode.
    async fn run_read<T, F>(&self, sql: &str, op: F) -> turso::Result<T>
    where
        T: Send + 'static,
        F: for<'a> FnOnce(
                &'a store::Connection,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = turso::Result<T>> + Send + 'a>,
            > + Send
            + 'static,
    {
        self.refuse_transaction_read()?;
        if let Some(lease) = self.readers.lease().await {
            return lease.run(sql, op).await;
        }
        self.run_detached(op).await
    }

    /// Refuse a read issued by the task holding the open transaction on this connection — that is
    /// the transaction's own work and must be read through its [`TxGuard`].
    ///
    /// Reads from any other task are unrelated, and the transaction's work cannot be served any
    /// other way: its uncommitted writes are visible only on it.
    ///
    /// The hole this leaves: a read issued by a task the transaction's work *spawned* is not the
    /// same task, so it is served as an unrelated read (committed state only).
    fn refuse_transaction_read(&self) -> turso::Result<()> {
        // `try_id`: a caller outside a task (`block_on` — the debug CLI, a test body) has no id,
        // and its reads are not the transaction's own work.
        let holder = *self.tx_task.lock().unwrap_poison();
        if holder.is_some() && holder == tokio::task::try_id() {
            return Err(turso::Error::Error(TRANSACTION_READ_REFUSAL.to_string()));
        }
        Ok(())
    }

    /// Execute a read-only query with engine-level write enforcement.
    ///
    /// On a reader the enforcement is the connection's own state: created `PRAGMA query_only = 1`
    /// for its whole life, and the reader entry refuses the forms that switch does not cover, so
    /// nothing is set, reset or carried over between uses.
    ///
    /// On the writing connection (the log store, or the reader fallback) the pragma is set, the
    /// query runs and it is reset to `0` under one hold of the connection mutex, on every outcome
    /// (including an engine panic) and panic-guarded. A panic there, or a failure to roll a leaked
    /// transaction back, flags `has_dangling_tx` so the next access retries; a plain `query_only=0`
    /// failure only surfaces an error. Either way the connection keeps `query_only=1` — loud, never
    /// auto-recovered.
    ///
    /// The result is bounded to `row_limit` rows using LIMIT+1 semantics (exactly `row_limit` rows
    /// is NOT truncated). Forms are refused identically on either connection ([`reader_refusal`]),
    /// so a raw client cannot do on the fallback what a reader turns away.
    pub(crate) async fn query_readonly(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        row_limit: usize,
    ) -> turso::Result<ReadonlyRows> {
        self.refuse_transaction_read()?;
        // Checked before the path is chosen, so a statement a reader refuses is refused
        // at once; the reader entry applies the same guard for reads that do not come
        // through here ([`ReaderLease::run`]), which keeps the verdict identical.
        if let Some(refusal) = reader_refusal(sql) {
            return Err(turso::Error::Error(refusal));
        }
        if let Some(lease) = self.readers.lease().await {
            let owned = sql.to_owned();
            return lease
                .run(sql, move |conn| {
                    Box::pin(
                        async move { run_readonly_query(conn, &owned, params, row_limit).await },
                    )
                })
                .await;
        }
        let owned = sql.to_owned();
        let dangling = self.has_dangling_tx.clone();
        self.run_detached(move |conn| {
            Box::pin(async move {
                conn.execute("PRAGMA query_only = 1;", ()).await?;
                let result =
                    AssertUnwindSafe(run_readonly_query(conn, &owned, params, row_limit))
                        .catch_unwind()
                        .await;
                // Always restore the writing connection (query_only off, autocommit) so instance
                // writes are never left disabled: the `query_only` reset first, then a
                // transaction-control statement a raw IPC client could send — not re-validated
                // instance-side — is rolled back, since an open transaction here would poison
                // subsequent writes. Panic-guarded: an engine panic must not unwind leaving
                // query_only=1.
                let (reset, tx_reset) = match AssertUnwindSafe(async {
                    let reset = conn.execute("PRAGMA query_only = 0;", ()).await;
                    let tx_reset = if conn.is_autocommit() {
                        Ok(())
                    } else {
                        conn.execute("ROLLBACK;", ()).await.map(|_| ())
                    };
                    (reset, tx_reset)
                })
                .catch_unwind()
                .await
                {
                    Ok(ok) => ok,
                    Err(payload) => {
                        // The reset panicked: connection state unknown. Flag it so the next
                        // `lock_and_cleanup` attempts a rollback, and surface the error rather than
                        // leaving instance writes silently blocked.
                        dangling.store(true, Ordering::SeqCst);
                        return Err(turso::Error::Error(format!(
                            "the database engine panicked while resetting the read-only query state: {}",
                            crate::util::panic_message(&*payload)
                        )));
                    }
                };
                if let Err(e) = &reset {
                    tracing::error!(
                        error = %e,
                        "query_readonly: failed to reset PRAGMA query_only on the writing \
                         connection — instance writes may be left disabled"
                    );
                }
                if let Err(e) = &tx_reset {
                    // Flag the leaked transaction so the next `lock_and_cleanup` retries the
                    // rollback before an instance write reuses the connection.
                    dangling.store(true, Ordering::SeqCst);
                    tracing::error!(
                        error = %e,
                        "query_readonly: failed to roll back a leaked transaction — instance writes \
                         may be left disabled on the writing connection"
                    );
                }
                reset?;
                tx_reset?;
                match result {
                    Ok(Ok(rows)) => Ok(rows),
                    Ok(Err(e)) => Err(e),
                    Err(payload) => Err(turso::Error::Error(format!(
                        "the database engine panicked while executing the query: {}",
                        crate::util::panic_message(&*payload)
                    ))),
                }
            })
        })
        .await
    }

    /// Core query logic shared by [`Connection::query`] and [`TxGuard::query`].
    /// Operates on an already-locked connection. Collects all rows into a `Vec`.
    async fn query_impl(
        conn: &store::Connection,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        let rows = conn.query(sql, params)?;
        drain_rows(rows).await
    }

    /// Execute a read-only query, mapping each row: a `Vec` of results, so callers
    /// handle per-row errors individually. Operates on an already-locked connection.
    pub async fn query_map<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnMut(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<Vec<turso::Result<T>>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        let rows = self.query(sql, params).await?;
        Ok(map_rows(&rows, map))
    }

    /// Map every row, failing on the first per-row error (unlike [`Self::query_map`], which returns
    /// per-row results).
    pub async fn query_map_strict<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnMut(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> anyhow::Result<Vec<T>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        strict_collect(self.query_map(sql, params, map).await?)
    }

    /// Execute a read that returns exactly one row, on a reader when the store has one free (see
    /// [`Self::run_read`]).
    pub async fn query_row<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        self.query_row_at(Place::Read, sql, params, map).await
    }

    async fn query_row_at<T, E>(
        &self,
        place: Place,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        let owned = sql.to_owned();
        self.run_at(place, sql, move |conn| {
            Box::pin(async move { Self::query_row_impl(conn, &owned, params, map).await })
        })
        .await
    }

    /// Execute a query that returns zero or one row: `Ok(None)` when nothing matched (folded by
    /// [`optional_row`]), `Err` otherwise.
    pub async fn query_optional<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> anyhow::Result<Option<T>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        optional_row(self.query_row(sql, params, map).await)
    }

    /// Core row-mapping logic shared by [`Connection::query_row`], [`Connection::execute_one`] and
    /// [`TxGuard::execute_one`], on an already-locked connection;
    /// [`turso::Error::QueryReturnedNoRows`] when nothing matches.
    async fn query_row_impl<T, E>(
        conn: &store::Connection,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        let rows = conn.query(sql, params)?;
        map_first_row(rows, map).await
    }

    /// Execute a read, returning all matching rows, through the connection's prepared-statement
    /// cache. Served by a reader when the store has one free (see [`Self::run_read`]); a change
    /// with rows to hand back goes through [`Self::execute_rows_cached`].
    ///
    /// # Cache contract
    ///
    /// Only SQL whose full text is invariant across calls — string literals or compile-time
    /// constants — may be routed here. turso caches compiled programs per connection keyed by the
    /// exact text and never evicts them, so per-call-composed fragments (dynamic IN-lists,
    /// interpolated limits, user SQL) keep the plain prepare-per-call path.
    pub async fn query_cached(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        self.query_cached_at(Place::Read, sql, params).await
    }

    async fn query_cached_at(
        &self,
        place: Place,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        let owned = sql.to_owned();
        self.run_at(place, sql, move |conn| {
            Box::pin(async move { Self::query_cached_impl(conn, &owned, params).await })
        })
        .await
    }

    /// Core query logic shared by [`Connection::query_cached`]: an already-locked
    /// connection, statement from turso's per-connection cache, all rows collected.
    async fn query_cached_impl(
        conn: &store::Connection,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        let mut stmt = conn.prepare_cached(sql)?;
        let rows = stmt.query(params)?;
        drain_rows(rows).await
    }

    /// Map every row, failing on the first per-row error (unlike [`Self::query_map`]), through the
    /// cached path (see [`Self::query_cached`]).
    pub async fn query_map_strict_cached<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnMut(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> anyhow::Result<Vec<T>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        let rows = self.query_cached(sql, params).await?;
        strict_collect(map_rows(&rows, map))
    }

    /// Execute a read that returns exactly one row, through the cached path (see
    /// [`Self::query_cached`] for the contract).
    async fn query_row_cached<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        let owned = sql.to_owned();
        self.run_at(Place::Read, sql, move |conn| {
            Box::pin(async move {
                let mut stmt = conn.prepare_cached(&owned)?;
                map_first_row(stmt.query(params)?, map).await
            })
        })
        .await
    }

    /// Execute a query that returns zero or one row, through the cached path (see
    /// [`Self::query_cached`] for the contract); the no-row case folds to `Ok(None)` via
    /// [`optional_row`].
    pub async fn query_optional_cached<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> anyhow::Result<Option<T>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        optional_row(self.query_row_cached(sql, params, map).await)
    }

    /// Force a WAL checkpoint with TRUNCATE mode — the raw, UNGATED engine call.
    ///
    /// Writes all pending WAL content to the main file and truncates the WAL. Run before hard
    /// process termination (e.g. [`std::process::exit`] in self-update) for a clean handoff;
    /// committed data is already fsync-durable at COMMIT. On a non-WAL database it is a no-op (the
    /// row reports `log == checkpointed == -1`).
    ///
    /// The row is parsed into a [`CheckpointOutcome`], so a complete checkpoint is distinguishable
    /// from a partial one (`log > checkpointed`). An attempt the engine could not run (blocked or
    /// failed) never reaches that parse: it returns the engine's wordless row as an error carrying
    /// the captured reason (see [`parse_checkpoint_row`]).
    ///
    /// A reclaiming checkpoint must pass [`crate::db::shrink_gate::shrink_allowed`] first; the
    /// checkpoint rounds and the boot repair do.
    pub(crate) async fn checkpoint_ungated(&self) -> anyhow::Result<CheckpointOutcome> {
        self.run_checkpoint(CheckpointMode::Truncate).await
    }

    async fn run_checkpoint(&self, mode: CheckpointMode) -> anyhow::Result<CheckpointOutcome> {
        // The compaction is upkeep on the writing connection, never on a reader (see [`Upkeep`]) —
        // the periodic round issues its own through [`Maintenance`], and the two share this body
        // through [`wal_checkpoint`].
        wal_checkpoint(mode, |sql, cause| async move {
            self.upkeep().query_with_cause(&sql, (), Some(&cause)).await
        })
        .await
    }

    /// Run PRAGMA quick_check to verify database integrity: b-tree page structure, NOT NULL and
    /// CHECK constraints, and index cardinality. `Ok(())` or the first corruption message.
    ///
    /// Read-only, but a full scan of the store's b-trees, so its cost scales with the store. On the
    /// live installation this is what ordinary reads used to wait seconds behind — which is why
    /// reads have readers now, and why this is upkeep that runs on whichever of the store's own
    /// connections runs it ([`OwnConnection`]): [`Maintenance`] or the writing connection.
    pub async fn quick_check(&self) -> anyhow::Result<()> {
        if let Some(problem) = self.quick_check_problems().await?.into_iter().next() {
            anyhow::bail!("Database integrity check failed: {problem}");
        }
        Ok(())
    }
}

/// The store's own upkeep reads — the reads the store issues to itself.
///
/// The record of changes (CDC), the compaction the exit round and the boot repair run, the
/// search-index repair and its probes, and the pre-shrink probe are all upkeep: they judge or
/// maintain the store rather than serve a caller, and the compaction and repair must not run
/// against a reader's reading position (the repair not beside live readers at all). One entry keeps
/// those exceptions in one place, which is why the reading entries can say without exception that
/// they serve reads on a reader.
///
/// The periodic round's compaction and integrity verification are **not** here: they run
/// on [`Maintenance`] (see [`OwnConnection`]), so ordinary work never waits behind them.
///
/// Upkeep is **not** atomic with the change that follows it: each statement takes the
/// writing connection and gives it back, so another task's change can land in between.
#[derive(Clone, Copy)]
pub(crate) struct Upkeep<'a>(&'a Connection);

impl Connection {
    #[must_use]
    pub(crate) fn upkeep(&self) -> Upkeep<'_> {
        Upkeep(self)
    }
}

impl Upkeep<'_> {
    pub(crate) async fn query(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        self.0.query_at(Place::Writer, sql, params).await
    }

    /// [`Self::query`] through the writing connection's prepared-statement cache (see
    /// [`Connection::query_cached`] for the contract).
    pub(crate) async fn query_cached(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        self.0.query_cached_at(Place::Writer, sql, params).await
    }

    async fn query_optional<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> anyhow::Result<Option<T>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        optional_row(self.query_row(sql, params, map).await)
    }

    async fn query_row<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        self.0.query_row_at(Place::Writer, sql, params, map).await
    }

    async fn query_map<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnMut(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<Vec<turso::Result<T>>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        let rows = self.query(sql, params).await?;
        Ok(map_rows(&rows, map))
    }

    /// [`Self::query`] with an optional engine-cause sink armed for the read's own polls (see
    /// [`checkpoint_cause`]) — used by the checkpoint, whose failure row cannot carry the engine's
    /// reason.
    async fn query_with_cause(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        cause: Option<&checkpoint_cause::CauseSink>,
    ) -> turso::Result<Vec<Row>> {
        let sql = sql.to_owned();
        self.0
            .run_detached_capturing(
                move |conn| {
                    Box::pin(async move { Connection::query_impl(conn, &sql, params).await })
                },
                cause,
            )
            .await
    }
}

/// The store's maintenance connection — a second connection of the very store this handle has open
/// (never a second open of its file), for the upkeep that judges or compacts the store without
/// making ordinary work wait: the periodic round's checkpoint and its integrity verification (see
/// [`crate::db::checkpoint`]).
///
/// It is made for the round that uses it and dropped when that round ends, so between rounds the
/// store carries the connections it carried before and nothing a long-lived extra connection could
/// accumulate (schema, header, page cache) goes stale. Making it costs no new file descriptor and
/// takes no lock of its own.
///
/// It is `query_only` for its whole life, which keeps "only the writing connection may change the
/// store" structural rather than a discipline. Its three statements are unaffected: `PRAGMA
/// page_count`, the compaction (`PRAGMA wal_checkpoint`, which writes nothing — a checkpoint's
/// serialization is the engine's own WAL checkpoint lock, the one the writing connection's
/// compaction takes) and `PRAGMA quick_check`.
///
/// A store that cannot give the round one of these ([`Connection::maintenance`]) has the round
/// issue both statements on its writing connection instead — a fallback, not an end to its upkeep.
/// The checkpoint can still meet live readers and writers, and the engine then answers it blocked
/// exactly as it always has: retried, never a failure.
pub(crate) struct Maintenance {
    conn: Arc<store::Connection>,
    db_path: Arc<Path>,
}

impl Maintenance {
    /// Run one statement the store issues to itself on this connection: a DETACHED task, exactly as
    /// [`Connection::run_detached`] runs the writing connection's, with `cause` armed for its polls
    /// when given (see [`checkpoint_cause`]).
    ///
    /// The connection is this round's alone and carries no transaction to clean up — it is never
    /// issued a `BEGIN` and could not commit one (it is `query_only`) — so the run needs neither a
    /// lock nor the dangling-transaction step.
    async fn run_statement(
        &self,
        sql: String,
        cause: Option<checkpoint_cause::CauseSink>,
    ) -> turso::Result<Vec<Row>> {
        let conn = Arc::clone(&self.conn);
        spawn_detached(
            async move { Connection::query_impl(&conn, &sql, ()).await },
            cause,
        )
        .await
    }
}

/// A connection the store itself owns — the writing connection or [`Maintenance`] — as opposed to a
/// reader, which serves a caller's read ([`ReaderLease`]). One body then serves the exit round
/// (which owns the writing connection) and the periodic round (which owns the maintenance one).
///
/// A reader is deliberately not one of these: its snapshot could lag the frames the very next
/// statement tries to fold. The connection is shared by reference across a round's awaits on
/// spawned tasks, hence the `Send + Sync` supertrait and the `+ Send` on each returned future.
pub(crate) trait OwnConnection: Send + Sync {
    fn own_query(&self, sql: &str) -> impl Future<Output = turso::Result<Vec<Row>>> + Send;

    /// The compaction, in the mode `truncate` names (see [`crate::db::shrink_gate`]).
    fn checkpoint(
        &self,
        truncate: bool,
    ) -> impl Future<Output = anyhow::Result<CheckpointOutcome>> + Send;

    fn db_path(&self) -> &Path;

    /// `PRAGMA quick_check`'s problem rows (see [`Connection::quick_check`]). The class-B repair
    /// needs the full list: an overflow-aliasing row anywhere must veto the REINDEX even when an
    /// earlier row names an index desync.
    fn quick_check_problems(&self) -> impl Future<Output = anyhow::Result<Vec<String>>> + Send {
        async move {
            let rows = self
                .own_query("PRAGMA quick_check;")
                .await
                .context("Failed to execute PRAGMA quick_check")?;
            scan_integrity_rows(&rows)
        }
    }
}

impl OwnConnection for Connection {
    async fn own_query(&self, sql: &str) -> turso::Result<Vec<Row>> {
        self.upkeep().query(sql, ()).await
    }

    async fn checkpoint(&self, truncate: bool) -> anyhow::Result<CheckpointOutcome> {
        self.run_checkpoint(CheckpointMode::from_truncate(truncate))
            .await
    }

    fn db_path(&self) -> &Path {
        self.db_path()
    }
}

impl OwnConnection for Maintenance {
    async fn own_query(&self, sql: &str) -> turso::Result<Vec<Row>> {
        self.run_statement(sql.to_owned(), None).await
    }

    async fn checkpoint(&self, truncate: bool) -> anyhow::Result<CheckpointOutcome> {
        wal_checkpoint(CheckpointMode::from_truncate(truncate), |sql, cause| {
            self.run_statement(sql, Some(cause))
        })
        .await
    }

    fn db_path(&self) -> &Path {
        &self.db_path
    }
}

/// How many reader connections one store keeps.
///
/// The floor is two: one slow read, or one whose caller has given up, must never by itself make the
/// next read wait for a reader. The ceiling would be the engine's reading positions — the one thing
/// here that could make a read fail where it used to succeed — and the measurement settles it:
/// `readers_at_distinct_frames_are_all_admitted` holds twenty-four live, only-partly-stepped reads
/// at twenty-four distinct frames at once and all are admitted, because the engine hands a reader
/// the highest read mark at or below its snapshot instead of one position per reader.
///
/// Accepted residual: were the engine to deny a reader a position anyway, it would surface as that
/// one read's own engine error after the engine's own retry — never as a state change, never as a
/// failure of the store.
///
/// The cost is per connection and accepted: each reader carries its own page cache (2000 pages, ~8
/// MiB), its own prepared-statement cache and its own blocking connect. That is the price of reads
/// that do not wait.
const READER_CONNECTIONS: usize = 3;

/// How long a connection waits on a lock another process holds before giving up with a busy error —
/// the writing connection ([`Connection::open`]) and every read-only connection of a store
/// ([`read_only_connection`]) alike.
const BUSY_TIMEOUT: Duration = Duration::from_mins(1);

/// Connect one read-only connection of the open store `db` — a reader ([`ReaderPool`]) or
/// [`Maintenance`] — with the settings they all get: the writing connection's busy timeout,
/// in-memory temp storage (the missing-temp-root guarantee) and the read-only switch, set before
/// any statement is prepared and never reset.
///
/// The engine's connect is blocking (it reads the header and page 1 and refreshes its stats), so it
/// runs off the async worker pool. `what` names the connection in the failure text.
async fn read_only_connection(
    db: &store::Database,
    what: &str,
) -> Result<store::Connection, String> {
    let conn = crate::util::with_block_in_place(|| db.connect())
        .map_err(|e| format!("could not connect {what}: {e}"))?;
    conn.busy_timeout(BUSY_TIMEOUT);
    conn.execute("PRAGMA temp_store = MEMORY;", ())
        .await
        .map_err(|e| format!("failed to set in-memory temp storage for {what}: {e}"))?;
    conn.execute("PRAGMA query_only = 1;", ())
        .await
        .map_err(|e| format!("failed to make {what} read-only: {e}"))?;
    Ok(conn)
}

/// How long [`ReaderPool::quiet`] and [`ReaderPool::release`] wait for the readers to fall idle.
///
/// A reader serves one read at a time, so they fall idle in the time a read takes; a long wait
/// means a read was abandoned by a caller that gave up, and giving up on the wait is what keeps a
/// repair, and the exit round's checkpoint, from hanging behind it.
///
/// The pool carries it, so a check that holds a reader on purpose can shorten its own wait without
/// touching this value.
const READERS_IDLE_WAIT: Duration = Duration::from_secs(5);

const TRANSACTION_READ_REFUSAL: &str = "a read issued while this task holds an open \
     transaction on the connection must be served by the transaction itself \
     (TxGuard::query): a reader connection cannot see what the transaction has \
     written";

/// PRAGMA names a **read-only** connection may run: the read-shaped pragmas of the
/// inspection path, shared by the reader guard ([`reader_refusal`]) and the debug validator
/// ([`crate::db::debug::validate_read_only`]) so the two cannot drift.
///
/// A mutating PRAGMA is not on the list, and a bracketed or quoted name is the name inside it
/// ([`pragma_form`]) — the same one the validator's tokenizer hands over. On the inspection path
/// this is defense-in-depth on top of the engine's read-only switch; on a reader connection it is
/// what covers the pragmas that switch leaves unclassified (`PRAGMA wal_checkpoint` compacts the
/// store file, `PRAGMA journal_mode` rewrites its header — neither is refused by it).
///
/// `foreign_key_check` is listed because this product issues it as a read; the engine does not know
/// the name and answers with no rows, so it changes nothing. The engine's own foreign-key read is
/// `foreign_key_list`, listed beside it.
pub(crate) const READER_PRAGMAS: &[&str] = &[
    "quick_check",
    "integrity_check",
    "table_info",
    "table_xinfo",
    "index_info",
    "index_list",
    "index_xinfo",
    "foreign_key_check",
    "foreign_key_list",
    "database_list",
    "compile_options",
    "page_count",
    "freelist_count",
    "page_size",
    "encoding",
    "user_version",
    "schema_version",
    "collation_list",
    "function_list",
    "module_list",
    "pragma_list",
    "table_list",
    "stats",
];

/// The listed pragmas whose body is a **query** whatever it looks like: the names the engine routes
/// to its query path for both the call form and the `=` form. That is why `PRAGMA table_info =
/// tickets` reads rather than assigns, and why [`reader_refusal`] lets their assignment form
/// through; every other listed name takes a value as a setter only, and a reader refuses that.
const QUERY_BODY_PRAGMAS: &[&str] = &[
    "quick_check",
    "integrity_check",
    "table_info",
    "table_xinfo",
    "index_info",
    "index_xinfo",
    "index_list",
    "foreign_key_list",
    "database_list",
    "table_list",
];

/// The statement forms a reader connection refuses, as the reason to show, or `None` when the
/// statement may run.
///
/// A reader connection is read-only for its whole life: created with `PRAGMA query_only = 1`, never
/// turned off, so the engine refuses every change it classifies as a write at prepare time. What
/// the switch does **not** refuse is what this guard covers: transaction control
/// (`BEGIN`/`COMMIT`/`ROLLBACK`/`SAVEPOINT`/`RELEASE`), `ATTACH`/`DETACH`, and the pragmas that
/// write without being classified as writes (`PRAGMA wal_checkpoint`, `PRAGMA journal_mode`).
///
/// It is an allowlist ([`READER_PRAGMAS`]) plus a bounded prefix look at the leading form and at
/// whether a pragma's body assigns to it ([`QUERY_BODY_PRAGMAS`]), not a classification pass over
/// the SQL, so it also refuses reads it need not: a pragma absent from the list, and any assignment
/// to a name the engine does not route as a query. Refusing a read costs an error message, never a
/// guarantee, so the list errs that way on purpose.
///
/// One verdict per statement, whichever connection serves it: the reader entry applies this
/// ([`ReaderLease::run`]) and so does the inspection path's writing-connection fallback
/// ([`Connection::query_readonly`]), so a raw client cannot do on the fallback what a reader turns
/// away. The narrowing that follows (a no-op setter like `PRAGMA page_size = 8192` is now refused
/// there) is intended. The call form of a listed name is left to the engine: of the listed names
/// only `page_size`, `user_version` and `schema_version` are settable, and none can change an
/// initialized store through it.
///
/// The failure it prevents is a change that succeeds on a reader and is never recorded: change
/// capture runs on the writing connection only, and the ticket chronicle (`ticket_chronicle`) is
/// materialized from that record.
pub(crate) fn reader_refusal(sql: &str) -> Option<String> {
    let (keyword, rest) = leading_form(sql);
    let upper = keyword.to_ascii_uppercase();
    if matches!(
        upper.as_str(),
        "BEGIN" | "COMMIT" | "END" | "ROLLBACK" | "SAVEPOINT" | "RELEASE" | "ATTACH" | "DETACH"
    ) {
        return Some(format!(
            "refused on a read-only connection: '{upper}' can change state, and the store's \
             readers never change state"
        ));
    }
    if upper == "PRAGMA" {
        let (name, args) = pragma_form(rest);
        let lower = name.to_ascii_lowercase();
        if !READER_PRAGMAS.contains(&lower.as_str()) {
            // A name that resolved to nothing (`PRAGMA [wal_checkpoint`) is not one this guard can
            // clear: name what was written instead of an empty pragma.
            let shown = if name.is_empty() {
                rest.trim().trim_end_matches(';').trim_end()
            } else {
                name
            };
            return Some(format!(
                "refused on a read-only connection: PRAGMA '{shown}' is not one of the pragmas \
                 a reader may run"
            ));
        }
        // An assignment is the `=` as the first thing after the name: an argument (`PRAGMA
        // table_info('a=b')`) is not one, whatever it holds.
        if skip_leading(args).starts_with('=') && !QUERY_BODY_PRAGMAS.contains(&lower.as_str()) {
            return Some(format!(
                "refused on a read-only connection: PRAGMA '{name}' may be read, never assigned — \
                 a reader's own state never changes"
            ));
        }
    }
    None
}

/// The name a `PRAGMA …` statement runs and the text after it: a quoted or bracketed name
/// (`[table_info]`, `"table_info"`, `` `table_info` ``) is the name inside, which is how the engine
/// reads it and how the debug validator's tokenizer hands it over. An unterminated quoting resolves
/// to no name, and the allowlist then refuses the statement — as does the engine.
fn pragma_form(rest: &str) -> (&str, &str) {
    let rest = skip_leading(rest);
    let Some(open) = rest.chars().next().filter(|c| matches!(c, '[' | '"' | '`')) else {
        return leading_form(rest);
    };
    let close = if open == '[' { ']' } else { open };
    match rest[open.len_utf8()..].split_once(close) {
        Some((name, tail)) => (name, tail),
        None => ("", rest),
    }
}

/// Split a statement's leading form: the leading word and the rest after it, with
/// whitespace, statement separators and `--` / `/* */` comments skipped.
fn leading_form(sql: &str) -> (&str, &str) {
    let rest = skip_leading(sql);
    match rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_') {
        Some(end) => (&rest[..end], &rest[end..]),
        None => (rest, ""),
    }
}

/// Skip what the engine's parser skips before a statement: whitespace, statement separators and
/// comments. The separators matter: the engine runs the statement after a leading `;`, so a guard
/// that stopped at one would be bypassed by a single character.
fn skip_leading(sql: &str) -> &str {
    let mut rest = sql;
    loop {
        rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == ';');
        if let Some(after) = rest.strip_prefix("--") {
            rest = after.split_once('\n').map_or("", |(_, tail)| tail);
        } else if let Some(after) = rest.strip_prefix("/*") {
            rest = after.split_once("*/").map_or("", |(_, tail)| tail);
        } else {
            return rest;
        }
    }
}

/// A store's reader connections: a small fixed set of read-only connections to the same open store,
/// each serving one read at a time.
///
/// A read used to be issued on the writing connection and queue behind whatever else the store was
/// doing — behind the periodic integrity verification it waited seconds, against an ordinary read
/// cost of milliseconds.
///
/// # Discipline
///
/// * Every connection here comes from the already-open store
///   ([`store::Database::connect`]): a store file is never opened a second time, because the
///   engine holds a whole-file lock on it for the process's life and closing ANY descriptor
///   for that file drops every record lock the process holds on it (see
///   [`crate::db::wal_guard`]). The pool holds the store handle so it outlives them.
/// * Readers are created on the first read that needs one, and only after
///   [`Connection::enable_readers`], so opening a store pays nothing for readers it never uses.
/// * Each reader is read-only for its whole life (see [`reader_refusal`]), and change
///   capture is never enabled on one: the engine records a change on the connection that
///   commits it, so the record is complete exactly because no change may be committed
///   anywhere but the writing connection. A reader can also never be left with a
///   transaction open — transaction control is one of the refused forms.
///
/// # What is accepted
///
/// * A read waits only while every reader is busy; one abandoned read holds one reader,
///   never the pool, and a read may see the state as of just before another task's change
///   commits — never older.
/// * A reader's cache is its own and the engine clears it at the start of a read once it
///   sees the journal has moved, so a read after a commit re-reads what it needs: slower
///   than on the writing connection while the store is being written to.
/// * A reading position can be refused to a reader in the engine's own terms (see the
///   count's doc): the read then fails with the engine's own error after its own retry.
/// * The pool's steady-state memory and the one-time cost of creating it.
struct ReaderPool {
    db: Arc<store::Database>,
    inner: tokio::sync::Mutex<ReaderPoolInner>,
    freed: tokio::sync::Notify,
    /// Whether the readers are in service; reads are served by the writing connection while `false`
    /// — before [`Connection::enable_readers`], while a repair holds the store quiet, and once the
    /// store is on its way down.
    in_service: tokio::sync::watch::Sender<bool>,
    /// Set by [`ReaderPool::release`], never cleared: keeps a repair's [`QuietReaders`] guard,
    /// dropped after the release, from putting readers back in service during the exit sequence.
    released: AtomicBool,
    /// How long a quiet/release waits for the readers to fall idle — [`READERS_IDLE_WAIT`] unless a
    /// check shortened it. Absent from a production build: no production code sets it.
    #[cfg(test)]
    idle_wait: std::sync::Mutex<Duration>,
}

struct ReaderPoolInner {
    idle: Vec<store::Connection>,
    state: Readers,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Readers {
    Uncreated,
    Created,
    Failed,
}

impl std::fmt::Debug for ReaderPool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReaderPool")
            .field("connections", &READER_CONNECTIONS)
            .finish()
    }
}

impl ReaderPool {
    fn new(db: Arc<store::Database>) -> Self {
        Self {
            db,
            inner: tokio::sync::Mutex::new(ReaderPoolInner {
                idle: Vec::new(),
                state: Readers::Uncreated,
            }),
            freed: tokio::sync::Notify::new(),
            in_service: tokio::sync::watch::channel(false).0,
            released: AtomicBool::new(false),
            #[cfg(test)]
            idle_wait: std::sync::Mutex::new(READERS_IDLE_WAIT),
        }
    }

    /// Shorten how long a quiet/release waits for the readers to fall idle, for a check that holds
    /// a reader on purpose and would otherwise pay the whole [`READERS_IDLE_WAIT`] for it.
    #[cfg(test)]
    fn shorten_idle_wait(&self, wait: Duration) {
        *self.idle_wait.lock().unwrap_poison() = wait;
    }

    /// Put the readers in service (see [`Connection::enable_readers`]). `send_replace` rather than
    /// `send`: the pool holds no receiver, and a `watch` sender refuses to send while none exists.
    fn enable(&self) {
        self.in_service.send_replace(true);
    }

    /// Hand out a reader for one read, creating the readers on first use, or `None` when
    /// no reader can serve this read (not in service, creation failed, or they went out
    /// of service while this call waited). The caller then uses the writing connection.
    async fn lease(self: &Arc<Self>) -> Option<ReaderLease> {
        let mut in_service = self.in_service.subscribe();
        loop {
            if !*in_service.borrow() {
                return None;
            }
            {
                let mut inner = self.inner.lock().await;
                // Re-checked while holding the lock: the check above is stale by the time
                // this call gets it, and a read that got past it after a quiet() drained
                // the pool would create readers and run on one — exactly what quiet() is for.
                if !*in_service.borrow() {
                    return None;
                }
                match inner.state {
                    Readers::Created => {}
                    // Not retried: a creation that failed stays failed, and its reads keep being
                    // served the way they were before the pool existed.
                    Readers::Failed => return None,
                    Readers::Uncreated => match self.create_readers().await {
                        Ok(made) => {
                            debug!(
                                connections = made.len(),
                                "reader connections created — this store's reads are served by \
                                 them from now on"
                            );
                            inner.idle = made;
                            inner.state = Readers::Created;
                        }
                        Err(reason) => {
                            error!(
                                reason,
                                "could not create the store's reader connections — reads stay \
                                 on the writing connection"
                            );
                            inner.state = Readers::Failed;
                            return None;
                        }
                    },
                }
                if let Some(conn) = inner.idle.pop() {
                    return Some(ReaderLease {
                        pool: Arc::clone(self),
                        conn,
                    });
                }
            }
            tokio::select! {
                () = self.freed.notified() => {}
                changed = in_service.changed() => {
                    if changed.is_err() || !*in_service.borrow() {
                        return None;
                    }
                }
            }
        }
    }

    /// Take the readers out of service and wait for them to fall idle, closing them so nothing they
    /// hold predates the caller's work. `None` when they did not fall idle within
    /// [`READERS_IDLE_WAIT`] or the shortened wait a check sets: the caller then defers.
    async fn quiet(self: &Arc<Self>) -> Option<QuietReaders> {
        if !*self.in_service.borrow() || self.released.load(Ordering::SeqCst) {
            return Some(QuietReaders { pool: None });
        }
        self.in_service.send_replace(false);
        if self.drain_idle().await {
            Some(QuietReaders {
                pool: Some(Arc::clone(self)),
            })
        } else {
            // Back in service — unless the store was released while this call waited: the release
            // is final.
            if !self.released.load(Ordering::SeqCst) {
                self.in_service.send_replace(true);
            }
            None
        }
    }

    /// Take the readers out of service for good (see [`Connection::release_readers`]).
    async fn release(self: &Arc<Self>) {
        self.released.store(true, Ordering::SeqCst);
        self.in_service.send_replace(false);
        let _ = self.drain_idle().await;
    }

    /// Close the readers once every one is idle; `false` when they did not all fall idle within
    /// [`READERS_IDLE_WAIT`] (or the shortened wait a check set). A reader still out keeps its own
    /// connection (and reading position) until the runtime drops it.
    async fn drain_idle(&self) -> bool {
        #[cfg(test)]
        let wait = *self.idle_wait.lock().unwrap_poison();
        #[cfg(not(test))]
        let wait = READERS_IDLE_WAIT;
        let deadline = tokio::time::Instant::now() + wait;
        loop {
            {
                let mut inner = self.inner.lock().await;
                let all_idle = match inner.state {
                    Readers::Uncreated | Readers::Failed => true,
                    Readers::Created => inner.idle.len() == READER_CONNECTIONS,
                };
                if all_idle {
                    // A pool that had readers is back to having none: the next read creates them
                    // again. A failed creation stays failed.
                    inner.idle.clear();
                    if inner.state == Readers::Created {
                        inner.state = Readers::Uncreated;
                    }
                    return true;
                }
            }
            if tokio::time::timeout_at(deadline, self.freed.notified())
                .await
                .is_err()
            {
                return false;
            }
        }
    }

    /// Return a reader after a read. A reader given back after the pool was drained is closed
    /// instead of kept: the drain is what emptied it.
    async fn give_back(&self, conn: store::Connection) {
        {
            let mut inner = self.inner.lock().await;
            if inner.state == Readers::Created {
                inner.idle.push(conn);
            }
        }
        self.freed.notify_one();
    }

    /// Create the readers. Each reader is made by [`read_only_connection`], which carries the
    /// per-connection settings every read-only connection of the store gets.
    async fn create_readers(&self) -> Result<Vec<store::Connection>, String> {
        let mut made = Vec::with_capacity(READER_CONNECTIONS);
        for _ in 0..READER_CONNECTIONS {
            made.push(read_only_connection(&self.db, "a reader").await?);
        }
        Ok(made)
    }
}

/// Held for the duration of a repair that must not run while the readers are in use:
/// they are out of service (reads go to the writing connection) and closed. Dropping the
/// guard puts them back in service — unless the store released them for good
/// ([`ReaderPool::release`], the exit path), which a guard dropped late must not undo.
struct QuietReaders {
    pool: Option<Arc<ReaderPool>>,
}

impl Drop for QuietReaders {
    fn drop(&mut self) {
        if let Some(pool) = &self.pool
            && !pool.released.load(Ordering::SeqCst)
        {
            pool.in_service.send_replace(true);
        }
    }
}

struct ReaderLease {
    pool: Arc<ReaderPool>,
    conn: store::Connection,
}

impl ReaderLease {
    /// Run one read on this reader.
    ///
    /// The read runs in a DETACHED task, so a caller that gave up (a timeout, a shutdown cut, an
    /// aborted task) ends only its own wait: the statement finishes on the reader, which returns to
    /// the pool when it does. The statement is itself bounded by the per-statement limit every
    /// connection carries ([`crate::db::store::statement_limit`]), enforced as the engine steps, so
    /// an overrunning statement is terminated and the reader stays usable.
    ///
    /// The statement is checked against [`reader_refusal`] first, so a change routed here fails
    /// loudly instead of committing without ever being recorded.
    async fn run<T, F>(self, sql: &str, op: F) -> turso::Result<T>
    where
        T: Send + 'static,
        F: for<'a> FnOnce(
                &'a store::Connection,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = turso::Result<T>> + Send + 'a>,
            > + Send
            + 'static,
    {
        let Self { pool, conn } = self;
        let sql = sql.to_owned();
        let task = async move {
            let outcome = AssertUnwindSafe(async {
                if let Some(refusal) = reader_refusal(&sql) {
                    return Err(turso::Error::Error(refusal));
                }
                op(&conn).await
            })
            .catch_unwind()
            .await;
            pool.give_back(conn).await;
            match outcome {
                Ok(inner) => inner,
                Err(payload) => std::panic::resume_unwind(payload),
            }
        };
        join_detached(tokio::spawn(task).await)
    }
}

/// Collect `quick_check` problem rows, skipping `"ok"` and the known FTS
/// index-cardinality false positive ([`OwnConnection::quick_check_problems`]).
fn scan_integrity_rows(rows: &[Row]) -> anyhow::Result<Vec<String>> {
    let mut problems: Vec<String> = Vec::new();
    for row in rows {
        match row.get_value(0)? {
            Value::Text(s) if s == "ok" => {}
            Value::Text(s) if s.contains(KNOWN_FTS_DIR_COUNT_FALSE_POSITIVE) => {}
            Value::Text(s) => problems.push(s),
            _ => anyhow::bail!("Unexpected result from PRAGMA quick_check"),
        }
    }
    Ok(problems)
}

/// Outcome of `PRAGMA wal_checkpoint`, parsed from its 3-column row (`busy`, `log`,
/// `checkpointed`).
///
/// A checkpoint the engine could not run (blocked or failed) leaves a row with `busy` set and the
/// frame columns NULL, and [`parse_checkpoint_row`] refuses it — so only a completed or partial
/// checkpoint is parsed here, a partial one detected via `log > checkpointed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CheckpointOutcome {
    /// True when the engine's row itself says the attempt was blocked. The shipped engine never
    /// writes that row with frame counts (the parse refuses it), so this is false for every row
    /// that reaches here; it stays so the arms rendering a partial attempt keep rendering it.
    pub busy: bool,
    /// WAL frame high-water mark after the checkpoint (`-1` for non-WAL databases). After
    /// a complete TRUNCATE the frame index resets, so this equals `checkpointed_frames`.
    pub log_frames: i64,
    /// Frames backfilled into the database by the checkpoint (`-1` for non-WAL).
    pub checkpointed_frames: i64,
}

impl CheckpointOutcome {
    #[must_use]
    pub fn is_complete(&self) -> bool {
        !self.busy && self.log_frames <= self.checkpointed_frames
    }
}

fn int_column(row: &Row, idx: usize) -> anyhow::Result<i64> {
    match row.get_value(idx)? {
        Value::Integer(n) => Ok(n),
        _ => anyhow::bail!("Unexpected result from PRAGMA wal_checkpoint"),
    }
}

/// `PRAGMA wal_checkpoint`'s three columns as a [`CheckpointOutcome`].
///
/// A checkpoint the engine could not run — blocked by a reading position, or failed in its pager —
/// comes back as a *successful* statement whose row has `busy` set and the frame columns NULL, its
/// reason only a debug event ([`checkpoint_cause`] captures it when armed). The NULL frame columns
/// are what refuses the row here; the captured reason then tells a blocked attempt from a failure
/// ([`crate::db::checkpoint_cause::is_blocked_checkpoint`]).
fn parse_checkpoint_row(row: &Row) -> anyhow::Result<CheckpointOutcome> {
    Ok(CheckpointOutcome {
        busy: int_column(row, 0)? != 0,
        log_frames: int_column(row, 1)?,
        checkpointed_frames: int_column(row, 2)?,
    })
}

/// One `PRAGMA wal_checkpoint(<mode>)` over whichever of the store's own connections runs
/// it. `run` issues `sql` with `cause` armed for its polls (see [`checkpoint_cause`]) —
/// the reason is only available there — and returns that statement's rows.
async fn wal_checkpoint<F, Fut>(mode: CheckpointMode, run: F) -> anyhow::Result<CheckpointOutcome>
where
    F: FnOnce(String, checkpoint_cause::CauseSink) -> Fut,
    Fut: Future<Output = turso::Result<Vec<Row>>>,
{
    let cause = checkpoint_cause::CauseSink::new();
    let sql = format!("PRAGMA wal_checkpoint({});", mode.label());
    let rows = run(sql, cause.clone())
        .await
        .map_err(|e| cause.attach(anyhow::Error::from(e)))
        .context("Failed to checkpoint WAL")?;
    let row = rows
        .first()
        .context("PRAGMA wal_checkpoint returned no result row")?;
    parse_checkpoint_row(row).map_err(|e| cause.attach(e))
}

/// A locked handle on the writing connection, scoped to one transaction: the mutex guard is
/// held for the whole duration, and a dropped guard triggers a rollback on the next write.
///
/// The transaction's own work goes through this guard: `query` for what it reads, `execute`
/// / `upsert_row` / `execute_batch` for what it changes, `execute_one` for a change reading
/// its own result back. The [`Connection`] entry points cannot be used — a write would
/// re-lock the mutex on a detached task and wait forever, and a read is refused outright.
///
/// It is the only place a read sees the transaction's own uncommitted writes: the read entry
/// refuses a read issued by the task holding the guard ([`Connection::refuse_transaction_read`]) so
/// a read cannot drift onto a reader behind the transaction's back.
pub(crate) struct TxGuard<'a> {
    conn: tokio::sync::MutexGuard<'a, store::Connection>,
    /// Shared flag on the parent Connection; set in Drop to signal a deferred rollback on the next
    /// write, and set to None once the transaction is explicitly committed or rolled back so Drop
    /// cannot flag a dangling one.
    has_dangling_tx: Option<Arc<AtomicBool>>,
    /// The parent's owning-task record, cleared with the flag above so the read entry stops
    /// refusing that task's reads.
    tx_task: Option<Arc<std::sync::Mutex<Option<tokio::task::Id>>>>,
}

impl TxGuard<'_> {
    /// Upsert one row inside the held transaction: the update-then-insert contract of
    /// [`Connection::upsert_row`] — including why the engine's own upsert form is unusable under
    /// change capture, and how a wrapping caller must render the chain — run on the connection this
    /// guard holds.
    ///
    /// `insert_sql` must be the `INSERT ... ON CONFLICT ... DO NOTHING` form and `update_params` a
    /// closure, because the update can run twice.
    pub async fn upsert_row<U, I>(
        &self,
        update_sql: &str,
        update_params: impl Fn() -> U,
        insert_sql: &str,
        insert_params: I,
    ) -> turso::Result<()>
    where
        U: IntoParams + Send + 'static,
        I: IntoParams + Send + 'static,
    {
        if self.execute(update_sql, update_params()).await? > 0 {
            return Ok(());
        }
        if self.execute(insert_sql, insert_params).await? == 0 {
            self.execute(update_sql, update_params()).await?;
        }
        Ok(())
    }

    pub async fn execute(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<u64> {
        self.conn.execute(sql, params).await
    }

    pub async fn execute_batch(&self, sql: &str) -> turso::Result<()> {
        self.conn.execute_batch(sql).await
    }

    /// Execute a read of the transaction's own work, returning zero or more rows.
    ///
    /// The only read that sees what the transaction itself has written: the connection's read entry
    /// refuses a read issued by this task while the transaction is open (see
    /// [`Connection::refuse_transaction_read`]).
    pub async fn query(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        Connection::query_impl(&self.conn, sql, params).await
    }

    pub async fn execute_one<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnOnce(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> turso::Result<T>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        Connection::query_row_impl(&self.conn, sql, params, map).await
    }

    pub async fn query_map_strict<T, E>(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
        map: impl FnMut(&Row) -> std::result::Result<T, E> + Send + 'static,
    ) -> anyhow::Result<Vec<T>>
    where
        T: Send + 'static,
        E: std::fmt::Display + Send + Sync + 'static,
    {
        let rows = self.query(sql, params).await?;
        strict_collect(map_rows(&rows, map))
    }

    pub async fn commit(mut self) -> turso::Result<()> {
        self.conn.execute("COMMIT", ()).await?;
        // Clear the flags so Drop doesn't try to roll back an already-committed tx, and the read
        // entry stops refusing this task's reads.
        self.has_dangling_tx = None;
        self.release_task_record();
        Ok(())
    }

    pub async fn rollback(mut self) -> turso::Result<()> {
        self.conn.execute("ROLLBACK", ()).await?;
        // Clear the flags so Drop doesn't try to roll back again
        self.has_dangling_tx = None;
        self.release_task_record();
        Ok(())
    }

    /// End this guard's hold on the connection's transaction record: the task's reads are ordinary
    /// reads again. Guard-side only — the parent's flag belongs to the write path
    /// ([`Connection::lock_and_cleanup`]).
    fn release_task_record(&mut self) {
        if let Some(task) = self.tx_task.take() {
            *task.lock().unwrap_poison() = None;
        }
    }
}

impl Drop for TxGuard<'_> {
    fn drop(&mut self) {
        // Set the dangling_tx flag on the parent so the next write (execute, begin_tx)
        // issues a ROLLBACK first. Deferred because Drop cannot await, but the lock is
        // not released yet, so no other task can write before the flag is set.
        if let Some(flag) = &self.has_dangling_tx {
            flag.store(true, Ordering::SeqCst);
        }
        // The hold ends with the guard even when the transaction is left for the deferred
        // rollback: a task that dropped its guard no longer has transaction work to read.
        self.release_task_record();
    }
}

/// Ensure a full-text search index exists with the correct tokenizer, dropping and recreating it
/// when the existing one differs. Index maintenance, so its shape probe reads through [`Upkeep`]
/// like the rest of the repair family.
pub(crate) async fn ensure_fts_index(
    conn: &Connection,
    index_name: &str,
    tokenizer: &str,
    ddl: &str,
) -> anyhow::Result<()> {
    let existing_sql: Option<String> = conn
        .upkeep()
        .query_optional(
            "SELECT sql FROM sqlite_master WHERE type='index' AND name=?1 LIMIT 1",
            params![index_name],
            |row| match row.get_value(0)? {
                Value::Text(s) => Ok::<_, ::turso::Error>(s),
                _ => Ok::<_, ::turso::Error>(String::new()),
            },
        )
        .await?
        .filter(|s| !s.is_empty());

    let needs_rebuild = existing_sql
        .as_deref()
        .is_none_or(|sql| !sql.to_lowercase().contains(&tokenizer.to_lowercase()));

    if needs_rebuild {
        // The tokenizer migration drops and recreates the index, so it holds the readers off
        // exactly as the corruption rebuilds do (see [`Connection::quiet_readers`]). At open time
        // the readers do not exist yet, but the guard is what the code rests on, not that ordering:
        // a reader that does not fall idle in time leaves the index as it is — the store still
        // opens and the next open retries.
        let Some(_quiet) = conn.quiet_readers().await else {
            warn!(
                index = index_name,
                "the store's readers did not fall idle — leaving the FTS index unchanged for \
                 this open; the next open retries the tokenizer migration"
            );
            return Ok(());
        };
        conn.execute(&format!("DROP INDEX IF EXISTS {index_name}"), ())
            .await?;
        // Race-safe: `CREATE INDEX IF NOT EXISTS` survives concurrent schema init.
        conn.execute(ddl, ()).await?;
    }

    Ok(())
}

/// Probe term for the MATCH smoke probe — a plain alphanumeric token valid for any ngram
/// width; zero rows on an empty index still proves the index is queryable end-to-end.
const FTS_PROBE_TERM: &str = "mahbot";

/// True when a `quick_check` problem is attributable to the ticket-title FTS index: it
/// names the user-visible index or the internal FTS dir (the benign count-mismatch is
/// already filtered by `scan_integrity_rows`; any other internal-dir row is real
/// corruption). core.db carries exactly one FTS index, so such rows belong to nothing else.
fn names_ticket_title_fts(problem: &str, index: &str) -> bool {
    problem.contains(index) || problem.contains(FTS_INTERNAL_INDEX_PREFIX)
}

/// True when the named index is a turso `USING fts` index (its `sqlite_master` DDL carries the
/// index-method clause). Upkeep, like the repair's other probes.
async fn is_fts_index(conn: &Connection, index: &str) -> bool {
    conn.upkeep()
        .query_optional(
            "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?",
            (index.to_string(),),
            |row| row.get::<String>(0),
        )
        .await
        .ok()
        .flatten()
        .is_some_and(|sql| sql.to_lowercase().contains("using fts"))
}

/// Name of the ticket-title FTS index. This const pair is the single shared known-good copy used by
/// [`crate::db::ensure_fts_index`] and the repair ([`crate::db::repair_ticket_title_fts_runtime`]);
/// the append-only migrations catalog carries its own raw-SQL entry by design.
pub(crate) const TICKETS_FTS_INDEX_NAME: &str = "idx_tickets_title_fts";

/// Known-good DDL for the ticket-title FTS index — the single shared known-good copy used by
/// [`crate::db::ensure_fts_index`] and the repair, never rebuilt from `sqlite_master` (whose DDL
/// for a corrupt index is untrusted). The migrations catalog carries its own raw-SQL entry by
/// design.
pub(crate) const TICKETS_FTS_INDEX_DDL: &str = "CREATE INDEX IF NOT EXISTS idx_tickets_title_fts ON tickets \
USING fts (title) WITH (tokenizer = 'ngram')";

/// Functional MATCH probe for the ticket-title FTS index: any successful MATCH proves the index is
/// readable (the incident's corruption also failed plain MATCH while quick_check looked clean apart
/// from masked rows). An `Err` is a detection signal, not a row count. Upkeep, like the rest of the
/// repair.
async fn title_fts_match_probe(conn: &Connection) -> anyhow::Result<()> {
    conn.upkeep()
        .query_optional(
            "SELECT id FROM tickets WHERE title MATCH ?1 LIMIT 1",
            params![FTS_PROBE_TERM.to_string()],
            |_| Ok::<_, ::turso::Error>(()),
        )
        .await
        .map(|_: Option<()>| ())
}

/// Corruption evidence for the ticket-title FTS index from the `quick_check` rows a caller
/// already read plus the MATCH probe: `Some(evidence)` when the signature is present. It
/// reads only the probe — a caller that has just scanned the store never scans it again —
/// and the probe reaches the MATCH-level breakage `quick_check` cannot see.
async fn ticket_title_fts_evidence(
    conn: &Connection,
    problems: &[String],
) -> anyhow::Result<Option<String>> {
    let fts_problems: Vec<&str> = problems
        .iter()
        .map(String::as_str)
        .filter(|p| names_ticket_title_fts(p, TICKETS_FTS_INDEX_NAME))
        .collect();
    if !fts_problems.is_empty() {
        return Ok(Some(fts_problems.join("; ")));
    }
    if let Err(e) = title_fts_match_probe(conn).await {
        return Ok(Some(format!("MATCH probe failed: {e}")));
    }
    Ok(None)
}

/// Post-rebuild verification: filtered quick_check result, index presence in
/// `sqlite_master`, and a MATCH smoke assertion on a token from a sampled ticket title.
async fn verify_rebuilt_ticket_title_fts(conn: &Connection, index: &str) -> anyhow::Result<()> {
    let problems = conn.quick_check_problems().await?;
    if !problems.is_empty() {
        warn!(
            index,
            ?problems,
            "ticket-title FTS post-rebuild quick_check still reports problems"
        );
    }
    let present = conn
        .upkeep()
        .query_optional(
            "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?1",
            params![index.to_string()],
            |_| Ok::<_, ::turso::Error>(()),
        )
        .await?;
    anyhow::ensure!(
        present.is_some(),
        "rebuilt index '{index}' not found in sqlite_master"
    );
    // MATCH-smoke on a single whitespace-separated token (>= 3 chars, ngram-matchable) taken from a
    // sampled title: it must match its own row — robust against multi-token titles and titles whose
    // sanitized form is too short to tokenize.
    let titles: Vec<String> = conn
        .upkeep()
        .query_map(
            "SELECT title FROM tickets WHERE title IS NOT NULL AND title != '' LIMIT 16",
            (),
            |row| row.get::<String>(0),
        )
        .await?
        .into_iter()
        .collect::<std::result::Result<Vec<_>, _>>()?;
    let Some((title, term)) = titles.iter().find_map(|title| {
        let sanitized = sanitize_fts_query(title);
        let term = sanitized.split(' ').find(|tok| tok.chars().count() >= 3)?;
        Some((title.clone(), term.to_string()))
    }) else {
        debug!(
            index,
            "no ticket title with an ngram-matchable token — MATCH smoke skipped"
        );
        return Ok(());
    };
    let hit = conn
        .upkeep()
        .query_optional(
            "SELECT id FROM tickets WHERE title MATCH ?1 LIMIT 1",
            params![term.clone()],
            |_| Ok::<_, ::turso::Error>(()),
        )
        .await?;
    anyhow::ensure!(
        hit.is_some(),
        "MATCH smoke failed: token '{term}' from title '{title}' not found via MATCH"
    );
    info!(
        index,
        title, "ticket-title FTS MATCH smoke assertion passed"
    );
    Ok(())
}

struct TicketTitleFtsRebuildOutcome {
    drop_create: anyhow::Result<()>,
    verified: anyhow::Result<()>,
}

/// Rebuild the ticket-title FTS index from the KNOWN-GOOD DDL threaded in by the caller, never from
/// `sqlite_master` (whose stored DDL for a corrupt index is untrusted). Mirrors
/// `drop_create_index_fallback`'s transactional DROP+CREATE: a failed CREATE rolls the DROP back,
/// leaving the original index for operator review; ticket rows are never touched. Then verify
/// (filtered quick_check, index presence, MATCH smoke on a known title). All outcomes are logged,
/// never propagated (fail-safe).
///
/// No reclaiming checkpoint is issued here: a rebuild reached from a live round must not
/// TRUNCATE under the writers the periodic loop keeps it away from. The rebuilt pages reach
/// the main file on the next checkpoint round; committed transactions are durable without it.
async fn rebuild_ticket_title_fts(
    conn: &Connection,
    index: &str,
    ddl: &str,
) -> TicketTitleFtsRebuildOutcome {
    let quoted = index.replace('"', "\"\"");
    // Transactional DROP+CREATE: a failed CREATE rolls the DROP back via the dropped TxGuard,
    // preserving the original index for operator review (the same deferred-rollback discipline as
    // `drop_create_index_fallback`).
    let drop_create = async {
        let tx = conn.begin_tx().await?;
        tx.execute_batch(&format!("DROP INDEX IF EXISTS \"{quoted}\"; {ddl};"))
            .await?;
        tx.commit().await
    }
    .await
    .map_err(anyhow::Error::from);
    let verified = verify_rebuilt_ticket_title_fts(conn, index).await;
    match (&drop_create, &verified) {
        (Ok(()), Ok(())) => {
            info!(index, "ticket-title FTS index rebuilt and verified");
        }
        (drop_create, verified) => {
            warn!(
                index,
                repair_error = ?drop_create.as_ref().err(),
                verify_error = ?verified.as_ref().err(),
                "ticket-title FTS rebuild finished with warnings — check earlier log lines"
            );
        }
    }
    TicketTitleFtsRebuildOutcome {
        drop_create,
        verified,
    }
}

#[derive(Debug)]
pub(crate) enum TicketTitleFtsRuntimeRepair {
    NotApplicable,
    Healthy,
    Rebuilt(String),
    Deferred(String),
    Failed(String),
}

impl TicketTitleFtsRuntimeRepair {
    /// A compact human-readable summary for the failure report (the derived Debug keeps the
    /// shape but is not report-friendly): the payload variants are surfaced.
    #[must_use]
    pub(crate) fn summary(&self) -> String {
        match self {
            Self::NotApplicable => "not applicable (no ticket-title FTS index)".to_string(),
            Self::Healthy => "healthy (index present, probe clean)".to_string(),
            Self::Rebuilt(evidence) => format!("rebuilt after detection — {evidence}"),
            Self::Deferred(reason) => format!("deferred — {reason}"),
            Self::Failed(reason) => format!("failed — {reason}"),
        }
    }
}

/// The ticket-title FTS repair as the periodic round reaches it: the round's recovery step once a
/// checkpoint attempt failed or was answered busy (see
/// [`crate::db::checkpoint::periodic_checkpoint_and_verify`]). That round hands nothing to a
/// repair, so this entry point takes the scan it needs; the open's warranted scan reaches the same
/// repair through [`repair_ticket_title_fts_from_scan`], sharing its rows.
///
/// Execution holds the writing connection, so the store serves nothing else meanwhile —
/// acceptable for this rare path. Its statements are ordinary statements, so the
/// per-statement limit applies as everywhere else. The `sqlite_master` presence check makes
/// stores without the index (e.g. logs.db) no-ops, and panics are caught per probe.
///
/// # What else may be in flight
///
/// The rebuild drops and recreates the index inside one transaction, on the premise that nothing
/// else is in flight. The writing connection's mutex gives that for the product's writers, and the
/// periodic round is held off by construction: it reaches this repair only after the attempt loop
/// that used the maintenance connection returned. That connection holds no reading position across
/// the repair, and on its next statement the engine sees the WAL has moved, drops its page cache
/// and schema cookie, and adopts the writer's committed schema. The readers are the remaining case:
/// they are taken out of service and closed first ([`Connection::quiet_readers`]), reads keep being
/// served by the writing connection, and the next read creates fresh ones. A reader that does not
/// fall idle in time defers the repair to a later round (`Deferred`) rather than running it against
/// live readers — a reader is never invalidated on the assumption that the engine would notice the
/// index move under it.
pub(crate) async fn repair_ticket_title_fts_runtime(
    conn: &Connection,
) -> TicketTitleFtsRuntimeRepair {
    // Quiet the readers before the scan: a repair deferred here costs no scan.
    let Some(_quiet) = conn.quiet_readers().await else {
        return TicketTitleFtsRuntimeRepair::Deferred(
            "reader connections did not fall idle".to_string(),
        );
    };
    // Panic-guarded: a panicking probe is itself corruption evidence (boot precedent) — the rebuild
    // is attempted on it, never escaped.
    match AssertUnwindSafe(conn.quick_check_problems())
        .catch_unwind()
        .await
    {
        Ok(Ok(problems)) => {
            repair_ticket_title_fts_from_scan(conn, FtsScan::Problems(problems)).await
        }
        Ok(Err(e)) => TicketTitleFtsRuntimeRepair::Failed(format!("detection probe failed: {e}")),
        Err(panic) => {
            repair_ticket_title_fts_from_scan(
                conn,
                FtsScan::Panicked(format!(
                    "detection probe panicked: {}",
                    crate::util::panic_message(&panic)
                )),
            )
            .await
        }
    }
}

/// What FTS detection reads besides its MATCH probe.
enum FtsScan {
    /// The `quick_check` rows the caller read — the open's one scan, shared.
    Problems(Vec<String>),
    Panicked(String),
}

/// The repair body from a scan the caller owns: the presence check, detection from `scan`
/// plus the MATCH probe, and the drop+recreate rebuild when the evidence says so. The open's
/// warranted scan passes the rows it already read, so that start never scans twice.
///
/// The callers own the readers: [`repair_ticket_title_fts_runtime`] takes them out first, and the
/// open's call site runs before any reader exists.
async fn repair_ticket_title_fts_from_scan(
    conn: &Connection,
    scan: FtsScan,
) -> TicketTitleFtsRuntimeRepair {
    // Absent index → nothing to repair (non-domain stores never carry it). Panic-guarded like
    // every probe on this path: a turso panic must become this repair's own `Failed` outcome,
    // never escape to the outer per-store catch and skip the checkpoint round's stop.
    let present = AssertUnwindSafe(conn.upkeep().query_optional(
        "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?",
        params![TICKETS_FTS_INDEX_NAME.to_string()],
        |_| Ok::<_, ::turso::Error>(()),
    ))
    .catch_unwind()
    .await;
    let present = match present {
        Ok(Ok(present)) => present,
        Ok(Err(e)) => {
            return TicketTitleFtsRuntimeRepair::Failed(format!(
                "index presence probe failed: {e}"
            ));
        }
        Err(panic) => {
            return TicketTitleFtsRuntimeRepair::Failed(format!(
                "index presence probe panicked: {}",
                crate::util::panic_message(&panic)
            ));
        }
    };
    if present.is_none() {
        return TicketTitleFtsRuntimeRepair::NotApplicable;
    }

    let evidence = match scan {
        FtsScan::Panicked(evidence) => evidence,
        FtsScan::Problems(problems) => {
            let detected = AssertUnwindSafe(ticket_title_fts_evidence(conn, &problems))
                .catch_unwind()
                .await;
            match detected {
                Ok(Ok(None)) => return TicketTitleFtsRuntimeRepair::Healthy,
                Ok(Ok(Some(evidence))) => evidence,
                Ok(Err(e)) => {
                    return TicketTitleFtsRuntimeRepair::Failed(format!(
                        "detection probe failed: {e}"
                    ));
                }
                Err(panic) => format!(
                    "detection probe panicked: {}",
                    crate::util::panic_message(&panic)
                ),
            }
        }
    };

    let rebuilt = AssertUnwindSafe(rebuild_ticket_title_fts(
        conn,
        TICKETS_FTS_INDEX_NAME,
        TICKETS_FTS_INDEX_DDL,
    ))
    .catch_unwind()
    .await;
    let TicketTitleFtsRebuildOutcome {
        drop_create,
        verified,
    } = match rebuilt {
        Ok(outcome) => outcome,
        Err(panic) => {
            return TicketTitleFtsRuntimeRepair::Failed(format!(
                "rebuild panicked: {}; evidence: {evidence}",
                crate::util::panic_message(&panic)
            ));
        }
    };
    if drop_create.is_err() || verified.is_err() {
        return TicketTitleFtsRuntimeRepair::Failed(format!(
            "rebuild incomplete: drop_create error: {:?}; verify error: {:?}; evidence: {evidence}",
            drop_create.as_ref().err(),
            verified.as_ref().err(),
        ));
    }
    // The rebuild logs its own verification and the caller's terminal report runs its own
    // panic-guarded quick_check — no extra probe here, keeping this path panic-free.
    TicketTitleFtsRuntimeRepair::Rebuilt(format!("corruption detected: {evidence}"))
}

// Any schema creation, change, or removal is an entry in the append-only
// catalog (see [`crate::db::migrations`]); the only tracking mechanism is the
// id-based applied check in [`crate::db::migrations::run_migrations`].

/// Open a database, create parent directories if needed, and run schema init: `schema` is executed
/// via `execute_batch` (multiple DDL statements).
pub(crate) async fn open_with_schema(db_path: &Path, schema: &str) -> anyhow::Result<Connection> {
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }

    let conn = Connection::open(db_path)
        .await
        .with_context(|| format!("Failed to open database: {}", db_path.display()))?;

    conn.execute("PRAGMA foreign_keys = ON;", ())
        .await
        .context("Failed to enable foreign key enforcement")?;

    // Never embed the DDL in the error: a multi-kilobyte schema string hides the engine's
    // actual reason (`no such column: ticket_id`), which once hid a schema failure.
    execute_schema_ddl(&conn, schema).await?;

    Ok(conn)
}

/// Run a schema batch. The source Turso error is the context's cause — do not interpolate `sql`
/// into the message (see [`open_with_schema`]).
async fn execute_schema_ddl(conn: &Connection, sql: &str) -> anyhow::Result<()> {
    if sql.trim().is_empty() {
        return Ok(());
    }
    conn.execute_batch(sql)
        .await
        .context("Failed to run schema DDL")?;
    Ok(())
}

/// Resolve a logical store name to its physical database file path: every domain name (and
/// [`CONSOLIDATED_DB_NAME`] itself) maps to `root/db/{CONSOLIDATED_DB_NAME}.db`, and
/// [`LOG_DB_NAME`] to `root/db/{LOG_DB_NAME}.db`.
#[must_use]
pub(crate) fn store_db_path(root: &Path, name: &str) -> std::path::PathBuf {
    store_dir(root).join(format!("{}.db", store_stem(name)))
}

/// The stem of the physical store file a logical name lives in: only the logs store is a file of
/// its own, every other name is consolidated into core.
#[must_use]
fn store_stem(name: &str) -> &str {
    if name == LOG_DB_NAME {
        LOG_DB_NAME
    } else {
        CONSOLIDATED_DB_NAME
    }
}

/// The migration catalog target of the physical store a logical name lives in —
/// [`store_stem`]'s rule read one step on, so the layout decides the catalog.
#[must_use]
fn store_target(name: &str) -> migrations::TargetDb {
    if store_stem(name) == LOG_DB_NAME {
        migrations::TargetDb::Logs
    } else {
        migrations::TargetDb::Core
    }
}

/// The store directory of a storage root — where both physical stores live, together with the
/// recovery copies kept of them. The one place the layout is spelled: anything deciding by
/// location (the live-store refusal, the forensic listing) asks here rather than joining `db`.
#[must_use]
pub(crate) fn store_dir(root: &Path) -> std::path::PathBuf {
    root.join("db")
}

/// The marker a rebuild's own temp file carries — `{store}.db.rebuild-{stamp}`, beside the store it
/// rebuilds. The tool guard recognises a rebuild temp as the service's own by it, so it is spelled
/// once, here, beside the writer.
pub(crate) const REBUILD_TEMP_MARKER: &str = ".rebuild-";

/// The `-wal` sidecar path of a store's database file. The WAL is the engine's own and can hold
/// committed-but-uncheckpointed frames, so it is moved aside with the store by the quarantine and
/// the rebuild swap, and never deleted while it might hold them.
#[must_use]
pub(crate) fn wal_path(db_path: &Path) -> std::path::PathBuf {
    std::path::PathBuf::from(format!("{}-wal", db_path.display()))
}

/// Resource/permission keywords for [`is_actionable_signal`]: actionable conditions (never
/// damage), so ENOSPC/EMFILE/OOM/permission is not reported as a repair finding.
const RESOURCE_SIGNAL_KEYWORDS: [&str; 4] = [
    "no space left on device",
    "too many open files",
    "out of memory",
    "permission denied",
];

fn has_resource_signal(lower: &str) -> bool {
    RESOURCE_SIGNAL_KEYWORDS.iter().any(|k| lower.contains(k))
}

/// Lock/busy contention keywords for [`is_actionable_signal`]: another process holding a store (the
/// `Locking error:` step marker, whatever the platform's contention wording — see
/// [`is_open_time_lock_error`]), a locked table, or a busy database. One external condition, never
/// damage and never silently ignored.
const LOCK_SIGNAL_KEYWORDS: [&str; 3] = ["locking", "locked", "busy"];

fn has_lock_signal(lower: &str) -> bool {
    LOCK_SIGNAL_KEYWORDS.iter().any(|k| lower.contains(k))
}

/// True when a failure is an actionable signal: a resource/permission condition
/// (ENOSPC/EMFILE/OOM/permission) or lock contention with another process. Neither is damage, so
/// the repair path propagates them loud rather than reporting a spurious finding, and the durable
/// failure record marks them as environment-caused.
pub(crate) fn is_actionable_signal(e: &anyhow::Error) -> bool {
    text_is_actionable_signal(&format!("{e:#}"))
}

/// [`is_actionable_signal`] over an already-rendered message — for callers holding probe text
/// rather than an error chain.
pub(crate) fn text_is_actionable_signal(text: &str) -> bool {
    let lower = text.to_lowercase();
    has_resource_signal(&lower) || has_lock_signal(&lower)
}

/// Open a store database under `<root>/db/<name>.db` (path built by [`store_db_path`]).
///
/// The bring-up gate lives here. An absent data file is a genuine first launch: the store is
/// created, the only path that builds a schema in place of nothing. An existing file must pass the
/// file-level shape check ([`crate::db::wal_guard::classify_store_shape`]) and then open AND carry
/// the product's own schema, otherwise the call refuses with a [`StoreRefusal`] and leaves the file
/// exactly as it is. The data-preserving repairs run only when [`open_present_store`] finds a
/// reason for them, and only a repair that *fails* refuses — a condition they leave report-only (an
/// unknown quick_check signature) opens the store as it does today. Per-store `open()` constructors
/// are generated by [`crate::define_store!`] on top of [`open_consolidated_store`].
pub(crate) async fn open_store(
    root: &Path,
    name: &'static str,
    schema: &str,
) -> anyhow::Result<Connection> {
    let db_path = store_db_path(root, name);
    match crate::db::wal_guard::classify_store_shape(&db_path) {
        // No data file — a genuine first launch. Creating the store is the only path that builds a
        // schema in place of nothing.
        crate::db::wal_guard::StoreShape::Absent => open_with_schema(&db_path, schema).await,
        crate::db::wal_guard::StoreShape::Unusable(defect) => {
            Err(StoreRefusal::new(name, &db_path, defect.reason())
                .with_environment(defect.is_environment_caused())
                .into())
        }
        crate::db::wal_guard::StoreShape::Present => {
            let opened = AssertUnwindSafe(open_present_store(root, &db_path, name, schema))
                .catch_unwind()
                .await;
            match opened {
                Ok(result) => result,
                // turso's own reopen of a damaged store can panic; a panic is a refusal, not a
                // reason to replace the file.
                Err(payload) => Err(StoreRefusal::new(
                    name,
                    &db_path,
                    format!("open panicked: {}", crate::util::panic_message(&*payload)),
                )
                .into()),
            }
        }
    }
}

/// Open an existing, shape-valid store: require it to open and to carry the product's own
/// schema, then run the data-preserving repairs **when this start has a reason for them**.
/// Every failure is a refusal — the store is never quarantined, recreated or emptied.
///
/// # When the integrity scan runs
///
/// The scan costs a full pass, so it is not on the path to readiness on an ordinary start. Three
/// facts warrant it, all read here:
///
/// - **The previous run did not end cleanly.** A clean exit checkpoints with TRUNCATE,
///   leaving the `-wal` at zero bytes (see [`crate::db::checkpoint`]); a larger journal
///   carries frames — committed work that run wrote but never checkpointed.
/// - **A runtime integrity check failed.** The periodic round records the failure and marks
///   the store as owing a scan ([`crate::db::wal_guard::note_integrity_scan_owed`]) instead
///   of repairing under live readers. A scan that completes every repair clears the marker;
///   one whose FTS rebuild did not complete re-arms it ([`run_repairs`]).
/// - **The catalog still has entries to apply.** This start is about to write schema DDL, so
///   an already unreadable store must be refused *before* that, and a structural repair must
///   land before new schema is built on top of it.
///
/// Everything else is left to the periodic integrity round
/// ([`crate::db::checkpoint::periodic_checkpoint_and_verify`]), the one owner of a healthy
/// store's verification.
async fn open_present_store(
    root: &Path,
    db_path: &Path,
    name: &'static str,
    schema: &str,
) -> anyhow::Result<Connection> {
    // Stat-only, and taken BEFORE the store is opened (the module's lock rule): the size of the
    // journal the previous run left. Its header alone holds no frames — only a larger one carries
    // work the previous run never checkpointed.
    let uncheckpointed_journal =
        crate::db::wal_guard::wal_size(db_path) > crate::db::wal_guard::WAL_HEADER_BYTES;
    // Stat-only too: the marker a failed runtime integrity check left behind.
    let scan_owed = crate::db::wal_guard::integrity_scan_owed(db_path);
    let conn = match open_with_schema(db_path, schema).await {
        Ok(conn) => conn,
        // A resource/permission/lock condition is environmental, never store damage: it propagates
        // unwrapped so the boot recorder names it (the lock case with its own wording) and records
        // it with the environment note.
        Err(e) if is_actionable_signal(&e) => return Err(e),
        Err(e) => {
            return Err(
                StoreRefusal::new(name, db_path, format!("it could not be opened: {e:#}")).into(),
            );
        }
    };
    match has_product_schema(&conn).await {
        Ok(true) => {}
        Ok(false) => {
            return Err(StoreRefusal::new(
                name,
                db_path,
                "it opens but does not carry the product's own schema",
            )
            .into());
        }
        // Environmental, like an open failure — never recorded as damage.
        Err(e) if is_actionable_signal(&e) => return Err(e),
        Err(e) => {
            return Err(StoreRefusal::new(
                name,
                db_path,
                format!("the schema probe failed: {e:#}"),
            )
            .into());
        }
    }
    // The ledger was read successfully just above, so a failure here is the engine's and propagates
    // as the open's own error — never as damage.
    if !uncheckpointed_journal
        && !scan_owed
        && !migrations::has_pending(&conn, store_target(name)).await?
    {
        return Ok(conn);
    }
    run_repairs(conn, root, db_path, name, schema).await
}

/// True when an opened store carries the product's own schema — the ledger every install writes
/// ([`crate::db::migrations::MIGRATIONS_TABLE`]). A present store without it was never built by the
/// product (an empty file, a foreign SQLite file, or one left before its first catalog run) and
/// must not have a schema built inside it. An older install carries the ledger and migrates as
/// usual.
async fn has_product_schema(conn: &Connection) -> anyhow::Result<bool> {
    let table = crate::db::migrations::MIGRATIONS_TABLE;
    let ledger: Option<i64> = conn
        .query_optional(
            &format!(
                "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '{table}'"
            ),
            (),
            |row| row.get::<i64>(0),
        )
        .await?;
    if ledger.unwrap_or(0) == 0 {
        return Ok(false);
    }
    let recorded: i64 = conn
        .query_row(&format!("SELECT COUNT(*) FROM {table}"), (), |row| {
            row.get::<i64>(0)
        })
        .await?;
    Ok(recorded > 0)
}

/// Run the data-preserving repairs on an opened store — the one integrity scan the open
/// performs, and only when [`open_present_store`] found a reason for it. Only outcomes that
/// used to fall back to moving the store aside and recreating it are refusals now.
///
/// The scan is taken once and shared: the btree repair classifies its rows and the ticket-title FTS
/// repair detects from the same ones, so a warranted start that finds nothing wrong pays for one
/// full scan. A start that repairs pays for that scan plus the repair's own verification (see
/// [`rebuild_ticket_title_fts`]).
///
/// It also settles the store's integrity-scan marker: cleared once every repair the scan owns has
/// completed, and re-armed when the FTS rebuild reported `Failed` — a MATCH-only breakage
/// `quick_check` cannot see, so the next start must try again.
async fn run_repairs(
    conn: Connection,
    root: &Path,
    db_path: &Path,
    name: &'static str,
    schema: &str,
) -> anyhow::Result<Connection> {
    // All problem rows, not just the first: quick_check can surface a named index desync in one row
    // and overflow-aliasing in another — the veto must hold regardless of row order.
    let problems = match conn.quick_check_problems().await {
        Ok(problems) => problems,
        Err(e) => {
            // The quick_check itself failed to run — an actionable signal is never a repair
            // finding; propagate it.
            if is_actionable_signal(&e) {
                return Err(e);
            }
            crate::boot::boot_diagnostic(format!(
                "store '{name}' quick_check could not run: {e} — unreadable table; the \
                 store is refused",
            ));
            return Err(StoreRefusal::new(
                name,
                db_path,
                "its integrity check cannot read a table",
            )
            .into());
        }
    };
    let (outcome, conn) =
        match repair_desynced_btree_index(conn, &problems, root, db_path, name, schema).await {
            Ok((RepairOutcome::Unreadable, _conn)) => {
                return Err(StoreRefusal::new(
                    name,
                    db_path,
                    "its integrity check cannot read a table",
                )
                .into());
            }
            Ok((outcome, conn)) => (outcome, conn),
            // A resource/permission/lock condition is environmental, never store damage: propagate
            // it unwrapped so it is recorded (and shown) as the condition it is.
            Err(e) if is_actionable_signal(&e) => return Err(e),
            // Only a data-preserving rebuild that could not complete reaches here: the original
            // family is preserved or quarantined and the store is refused, never replaced with an
            // empty one.
            Err(e) => {
                return Err(StoreRefusal::new(
                    name,
                    db_path,
                    format!("the data-preserving rebuild could not be completed: {e:#}"),
                )
                .into());
            }
        };
    // A rebuilt store was created from the old DDL, filled by the row copy and verified by its own
    // quick_check, so the FTS half has nothing to detect.
    if matches!(outcome, RepairOutcome::Migrated) {
        crate::db::wal_guard::clear_integrity_scan_owed(db_path);
        return Ok(conn);
    }
    // The same scan owns the ticket-title FTS index: its detection reaches a MATCH-only breakage
    // quick_check cannot see, so the one FTS repair runs here from the rows already read — never by
    // scanning again. This is before any reader exists, so no reader has to be taken out of
    // service. Stores without the index (logs.db) are a presence-check no-op.
    let fts = repair_ticket_title_fts_from_scan(&conn, FtsScan::Problems(problems)).await;
    match &fts {
        // Silent. `Deferred` is the runtime entry point's own outcome (that is the one that
        // quietens readers) and cannot occur here.
        TicketTitleFtsRuntimeRepair::NotApplicable
        | TicketTitleFtsRuntimeRepair::Healthy
        | TicketTitleFtsRuntimeRepair::Deferred(_) => {}
        // Rebuilt and verified: INFO, the level the log store's retention keeps.
        TicketTitleFtsRuntimeRepair::Rebuilt(_) => info!(
            db = %name,
            outcome = %fts.summary(),
            "ticket-title FTS index rebuilt by the open's integrity scan",
        ),
        // A repair that did not complete leaves the store serving a broken index: that is a finding
        // operators must see, not an INFO line.
        TicketTitleFtsRuntimeRepair::Failed(_) => error!(
            db = %name,
            outcome = %fts.summary(),
            "ticket-title FTS repair failed during the open's integrity scan",
        ),
    }
    // The scan settled every repair it owns, so the store stops owing one — except a failed FTS
    // rebuild, which quick_check cannot see: that store keeps owing a scan, so the next start
    // retries what could not be completed here.
    if matches!(&fts, TicketTitleFtsRuntimeRepair::Failed(_)) {
        crate::db::wal_guard::note_integrity_scan_owed(db_path);
    } else {
        crate::db::wal_guard::clear_integrity_scan_owed(db_path);
    }
    Ok(conn)
}

/// Open (or create) the single consolidated domain database file.
///
/// The canonical open for the domain stores: it opens the one file ([`store_db_path`] maps all
/// domain names to [`CONSOLIDATED_DB_NAME`]) and applies the append-only catalog
/// ([`crate::db::migrations`]) — the single owner of every schema creation, change and removal for
/// core.db. It does NOT run the per-store post-open hooks (tickets FTS index, admin-user seed):
/// those are idempotent and run in [`init_all_stores`] and each store's `open` (isolated tests).
///
/// # Catalog, not SCHEMA
/// The catalog is a current-shape baseline: entries create the exact current schema (every
/// statement `IF NOT EXISTS`), so a fresh install converges in one pass and an existing one is a
/// no-op except the entries still pending on it. The catalog's entries, the id → release record
/// and the resume point live in the [`crate::db::migrations`] module doc; the only control flow
/// is the id-based applied check. A catalog failure is a hard boot failure — never a repair
/// finding, never a reason to replace the store.
///
/// # Why tables → ALTER → indexes is baked into the catalog order
///
/// The incident was real: SCHEMA gained `CREATE UNIQUE INDEX … ON jobs(kind, ticket_id)` while
/// `ticket_id` was only added by a later ALTER; `CREATE TABLE IF NOT EXISTS jobs` left the old
/// table unchanged, the index failed with `no such column`, and the store was misclassified as
/// corruption and rebuilt empty. In the baseline `jobs` is created WITH `ticket_id`, so
/// `idx_jobs_phase_ticket` is safe in the same batch.
///
/// Returns a **fresh** connection: production shares it across all domain stores via
/// [`DOMAIN_CONN`], isolated test opens drop it with the store. No process-global cache here, so
/// test isolation never leaks a connection across roots.
pub(crate) async fn open_consolidated_store(root: &Path) -> anyhow::Result<Connection> {
    // The catalog owns the ENTIRE schema. Open the raw connection (no DDL) and run the catalog; a
    // catalog failure is a hard boot error, never a repair finding or a reason to replace the
    // store.
    let conn = open_store(root, CONSOLIDATED_DB_NAME, "").await?;
    migrations::run_migrations(&conn, migrations::TargetDb::Core).await?;

    // Enable CDC on the FINAL connection, after all migrations, so boot-time schema writes are not
    // captured. This single chokepoint covers the boot open and the test-store opens.
    cdc::enable_capture(&conn).await?;

    // The store is final now — nothing past this point replaces or rebuilds its file — so its reads
    // may be served by reader connections of their own. (The log store keeps its own writing
    // connection without readers.)
    conn.enable_readers();

    Ok(conn)
}

enum RepairOutcome {
    NoRepair,
    Repaired,
    /// Overflow-aliasing: the data was rebuilt in a fresh file and swapped into place (an in-file
    /// DROP of the aliased b-trees would double-free the shared overflow page). The returned
    /// connection is the reopened, verified store.
    Migrated,
    Unreadable,
}

/// Open a fixture store and run the repair half of the existing-store open, unconditionally — what
/// `open_present_store` runs when the start warrants the integrity scan. (The boot path
/// additionally requires the product-schema ledger, which the raw-DDL fixtures are built without.)
#[cfg(test)]
async fn open_and_repair_for_test(
    root: &Path,
    db_path: &Path,
    name: &'static str,
    schema: &str,
) -> anyhow::Result<Connection> {
    let conn = open_with_schema(db_path, schema).await?;
    run_repairs(conn, root, db_path, name, schema).await
}

/// The baked overflow-aliasing signature: a prior REINDEX/DROP+CREATE on a store whose index leaves
/// shared an overflow page left the page doubly on the freelist, so a later allocation reuses it as
/// both a b-tree page and an overflow chain; reading that chain yields this exact short-read on every
/// scan. The table stays readable there — the store is rebuilt data-preservingly in a fresh sibling
/// file, never recreated empty.
const BAKED_OVERFLOW_ALIASING_READ: &str = "short read on page 167772160";

/// What the class-B repair should do given the full quick_check problem list.
enum RepairTarget {
    Unreadable,
    /// Shared overflow pages between index leaves (fresh "Page N referenced multiple times" or the
    /// baked short-read) — never REINDEX (bakes a worse error); rebuild data-preservingly.
    OverflowAliasing,
    Index(String),
    Unknown,
}

/// Classify the full quick_check problem list for the class-B repair.
///
/// Ordering is deliberate and structural: unreadable-table signatures win over everything, and
/// overflow-aliasing anywhere in the list vetoes the REINDEX even when an earlier row names an
/// index desync (both can surface in one scan — the veto must not depend on row order). The baked
/// short-read (page 0x0A000000) is an overflow-aliasing marker, not a table-read failure, so the
/// generic short-read check comes after it.
fn classify_repair_target(problems: &[String]) -> RepairTarget {
    if problems.iter().any(|p| p.contains("Invalid page type")) {
        RepairTarget::Unreadable
    } else if problems.iter().any(|p| {
        p.contains("referenced multiple times") || p.contains(BAKED_OVERFLOW_ALIASING_READ)
    }) {
        RepairTarget::OverflowAliasing
    } else if problems.iter().any(|p| p.contains("short read")) {
        RepairTarget::Unreadable
    } else {
        match problems.iter().find_map(|p| desynced_index_name(p)) {
            Some(index) => RepairTarget::Index(index.to_string()),
            None => RepairTarget::Unknown,
        }
    }
}

/// True when a filtered `quick_check` list names only conditions the boot path deliberately leaves
/// report-only (an unrecognised signature) rather than damage it acts on. The runtime integrity
/// record uses this so a tolerated finding is never filed as damage.
#[must_use]
pub(crate) fn is_tolerated_integrity_report(problems: &[String]) -> bool {
    matches!(classify_repair_target(problems), RepairTarget::Unknown)
}

/// Pre-repair forensic snapshot path (engine-produced): `{db}.pre-reindex-{stamp}-{pid}`. The base
/// name must stay parseable by `debug::parse_family_name` — the writer round-trip test locks it.
#[must_use]
fn pre_reindex_snapshot_path(db_path: &Path) -> std::path::PathBuf {
    std::path::PathBuf::from(format!(
        "{}.pre-reindex-{}",
        db_path.display(),
        family_stamp()
    ))
}

/// Forensic pre-repair snapshot of a store, produced BY THE ENGINE (`VACUUM INTO`) rather
/// than copied with `fs::copy`: copying opens the store's main file, which wal_guard's lock
/// rule forbids in the running service. It leaves an empty `<dest>-wal` beside the copy, so
/// the forensic family stays db + wal. Two accepted consequences: the artifact is a logical
/// copy, not the original bytes, and a store the engine cannot vacuum gets no snapshot — the
/// caller only warns, since an engine that cannot read the store cannot REINDEX it either.
///
/// Panic-absorbed: the vacuum walks every btree of an already-damaged store, exactly where
/// the engine can panic, and a panic must not unwind boot for missing evidence.
async fn snapshot_store_via_engine(
    conn: &Connection,
    db_path: &Path,
) -> anyhow::Result<std::path::PathBuf> {
    let dest = pre_reindex_snapshot_path(db_path);
    // `VACUUM INTO` takes a SQL string literal (no bind parameter), so the path is single-quote
    // escaped.
    let escaped = dest.display().to_string().replace('\'', "''");
    // `Connection::execute` routes through `run_detached`, which holds the connection mutex for the
    // whole statement — no other statement is active on the writing connection. (The store's
    // readers are statements of their own on their own connections.)
    match AssertUnwindSafe(conn.execute(&format!("VACUUM INTO '{escaped}'"), ()))
        .catch_unwind()
        .await
    {
        Ok(Ok(_)) => Ok(dest),
        Ok(Err(e)) => {
            Err(anyhow::Error::from(e).context(format!("VACUUM INTO {}", dest.display())))
        }
        Err(payload) => Err(anyhow::anyhow!(
            "VACUUM INTO {} panicked: {}",
            dest.display(),
            crate::util::panic_message(&*payload)
        )),
    }
}

/// Class-B btree-index desync repair, from the problem rows the open's single integrity scan
/// produced ([`run_repairs`] owns that scan): `quick_check` names a specific non-FTS index →
/// REINDEX in place, DROP+CREATE as the fallback (both validated on the 324MB prod sessions copy —
/// both M>N and M<N desync forms, survives reopen and TRUNCATE). A problem naming the ticket-title
/// FTS index is left report-only here; the same scan hands FTS detection its rows right after.
///
/// Preconditions hold at boot: single-writer, exclusive access, and a snapshot taken before the
/// REINDEX. The overflow-aliasing signature is **never** REINDEXed — that bakes a worse error; the
/// store is rebuilt data-preservingly instead ([`migrate_overflow_aliased_store`]). Unreadable
/// tables surface as scan failures and refuse the store.
async fn repair_desynced_btree_index(
    conn: Connection,
    problems: &[String],
    root: &Path,
    db_path: &Path,
    name: &'static str,
    schema: &str,
) -> anyhow::Result<(RepairOutcome, Connection)> {
    if problems.is_empty() {
        return Ok((RepairOutcome::NoRepair, conn));
    }
    let index = match classify_repair_target(problems) {
        RepairTarget::Unreadable => {
            crate::boot::boot_diagnostic(format!(
                "store '{name}' quick_check cannot scan a table ({}) — unreadable table; \
                 the store is refused",
                problems.join("; "),
            ));
            return Ok((RepairOutcome::Unreadable, conn));
        }
        // Overflow-aliasing (shared overflow pages between index leaves) must NEVER be REINDEXed —
        // that bakes a worse error. Structural veto: checked across the whole problem list.
        RepairTarget::OverflowAliasing => {
            crate::boot::boot_diagnostic(format!(
                "store '{name}' quick_check reports overflow-aliasing ({}) — rebuilding \
                 the store data-preservingly in a fresh file",
                problems.join("; "),
            ));
            return migrate_overflow_aliased_store(conn, root, db_path, name, schema).await;
        }
        // Report-only by decision: an unrecognised signature is not proof the data is unusable, so
        // the store boots as it does today — never a refusal, never a rebuild over the operator's
        // data.
        RepairTarget::Unknown => {
            crate::boot::boot_diagnostic(format!(
                "store '{name}' quick_check flagged an unknown condition: {}",
                problems.join("; "),
            ));
            return Ok((RepairOutcome::NoRepair, conn));
        }
        RepairTarget::Index(index) => {
            // Belt-and-braces: unreachable today (`scan_integrity_rows` filters the exact FTS
            // count-mismatch row first), but never REINDEX the out-of-scope FTS internal index if a
            // future filter change lets it through.
            if known_fts_dir_false_positive(&index) {
                crate::boot::boot_diagnostic(format!(
                    "store '{name}' quick_check flagged the known FTS false positive — \
                     not repairing",
                ));
                return Ok((RepairOutcome::NoRepair, conn));
            }
            // FTS indexes are never REINDEXed or DROP+CREATEd here — that is the documented "FTS
            // Drop" panic class. The index is left to the one FTS repair this scan runs after;
            // report the finding either way.
            if is_fts_index(&conn, &index).await {
                crate::boot::boot_diagnostic(format!(
                    "store '{name}' quick_check flagged FTS index '{index}' — its own repair \
                     owns the rebuild",
                ));
                return Ok((RepairOutcome::NoRepair, conn));
            }
            index
        }
    };
    // Forensic snapshot before the in-place repair, engine-produced (see
    // [`snapshot_store_via_engine`] for why). Best effort: evidence, not a precondition.
    if let Err(e) = snapshot_store_via_engine(&conn, db_path).await {
        warn!("Failed to write pre-reindex snapshot: {e:#}");
    }
    // REINDEX rewrites the index btree in place. Quoting: identifiers may contain special
    // characters.
    let quoted = index.replace('"', "\"\"");
    if conn
        .execute_batch(&format!("REINDEX \"{quoted}\";"))
        .await
        .is_ok()
        && conn.quick_check().await.is_ok()
    {
        info!(
            db = %name,
            index = %index,
            "class-B btree index desync repaired in place (REINDEX)",
        );
        return Ok((RepairOutcome::Repaired, conn));
    }
    crate::boot::boot_diagnostic(format!(
        "store '{name}' REINDEX of '{index}' did not clear the quick_check desync — \
         falling back to DROP+CREATE",
    ));
    Ok((
        drop_create_index_fallback(&conn, name, &index, &quoted).await,
        conn,
    ))
}

/// Row count of a table by name (the identifier is quoted inside). Both callers in
/// [`migrate_overflow_aliased_store`] own their per-site error handling — the pre-count's
/// unreadable-table classification and the post-swap verification's actionable-signal split differ
/// by site — so this only centralises the quoted `SELECT COUNT(*)` shape.
async fn count_table_rows(conn: &Connection, table: &str) -> turso::Result<i64> {
    let quoted = table.replace('"', "\"\"");
    conn.query_row(&format!("SELECT COUNT(*) FROM \"{quoted}\""), (), |r| {
        r.get::<i64>(0)
    })
    .await
}

/// Overflow-aliasing repair: rebuild the data in a fresh sibling file, verify it, then swap it into
/// place. The in-file alternative (DROP the aliased b-trees and recreate) double-frees the shared
/// overflow page — the free-walk frees it once per referencing leaf — corrupting the freelist, so
/// the rebuilt store re-aliases on the next allocation. A fresh file is the only path that verifies
/// clean. Preconditions hold at boot: single-writer, exclusive access before any live traffic. The
/// original family is quarantined (renamed aside, never deleted) before the swap, so the data
/// survives even when the rebuild aborts. A constraint violation during the copy (a data-integrity
/// finding) or a fresh store that cannot be built leaves the original untouched and reports only
/// (`NoRepair`). A table that cannot be read, and a swap that could not complete (partial
/// quarantine, failed rename, rebuilt store that will not reopen), propagate as `Err`, which
/// refuses the store rather than replacing it with an empty one. Actionable resource conditions
/// propagate as `Err` too.
#[expect(clippy::too_many_lines)] // one linear boot-repair flow, split across helpers
async fn migrate_overflow_aliased_store(
    conn: Connection,
    root: &Path,
    db_path: &Path,
    name: &'static str,
    schema: &str,
) -> anyhow::Result<(RepairOutcome, Connection)> {
    // Readability + row-count per user table (quick_check does not name the aliased index, so every
    // table's read is gated; unreadable → the store is refused). `__turso_internal_%` tables reject
    // user writes and are recreated by the DDL replay — excluded from the copy + verification.
    let mut counts: Vec<(String, i64)> = Vec::new();
    let tables = match conn
        .query(
            &format!(
                "SELECT name FROM sqlite_master WHERE type='table' \
                 AND {USER_OBJECT_FILTER} ORDER BY rowid"
            ),
            (),
        )
        .await
    {
        Ok(t) => t,
        // A table-enumeration failure is an engine-level read problem, not proof the data is
        // unreadable — report-only (conservative, no data loss), unlike the per-table read below.
        Err(e) => {
            let err = anyhow::anyhow!(e);
            if is_actionable_signal(&err) {
                return Err(err);
            }
            crate::boot::boot_diagnostic(format!(
                "store '{name}' cannot enumerate tables for the rebuild: {err} — left \
                 for operator review",
            ));
            return Ok((RepairOutcome::NoRepair, conn));
        }
    };
    for t in &tables {
        let tbl = match t.get::<String>(0) {
            Ok(tbl) => tbl,
            // sqlite_master.name is always TEXT — a non-string here is an engine anomaly; fail
            // closed rather than silently dropping the table from the copy and verification.
            Err(e) => {
                crate::boot::boot_diagnostic(format!(
                    "store '{name}' table name is not text ({e}) — rebuild aborted; \
                     left for operator review",
                ));
                return Ok((RepairOutcome::NoRepair, conn));
            }
        };
        match count_table_rows(&conn, &tbl).await {
            Ok(count) => counts.push((tbl, count)),
            Err(e) => {
                // The data cannot be read, so the rebuild cannot preserve it: the store is refused
                // (never replaced). An actionable condition is the environment — the caller
                // propagates it.
                let err = anyhow::anyhow!(e);
                return Err(if is_actionable_signal(&err) {
                    err
                } else {
                    err.context(format!("table '{tbl}' cannot be read"))
                });
            }
        }
    }

    let temp = std::path::PathBuf::from(format!(
        "{}{REBUILD_TEMP_MARKER}{}",
        db_path.display(),
        family_stamp()
    ));
    // Guard removes the temp family on every exit, including a turso panic mid-copy (absorbed by
    // open_store's catch_unwind).
    let _temp_guard = TempCleanup(&temp);
    let fresh = match Connection::open(&temp).await {
        Ok(f) => f,
        Err(e) if is_actionable_signal(&e) => return Err(e),
        Err(e) => {
            crate::boot::boot_diagnostic(format!(
                "store '{name}' rebuild store open failed: {e} — left for operator review",
            ));
            return Ok((RepairOutcome::NoRepair, conn));
        }
    };
    let migrated = migrate_schema_and_data(&conn, &fresh, &counts).await;
    let outcome = match migrated {
        Ok(()) => match fresh.quick_check().await {
            Ok(()) => checkpoint_rebuilt_before_swap(&fresh, name, root).await,
            Err(e) => Err(classify_migrate(e)),
        },
        Err(f) => Err(f),
    };
    drop(fresh); // release the fds before the temp cleanup / family swap
    if let Err(failure) = outcome {
        return match failure {
            MigrateFailure::Actionable(e) => Err(e),
            // The aliasing persists: the boot repair is the only path that acts on it, so a later
            // warranted start re-runs this rebuild attempt before falling back to NoRepair — the
            // operator-facing signal to intervene (e.g. restore from backup).
            MigrateFailure::Finding(msg) => {
                crate::boot::boot_diagnostic(format!(
                    "store '{name}' rebuild aborted: {msg} — original store preserved \
                     for operator review (no data changed)",
                ));
                Ok((RepairOutcome::NoRepair, conn))
            }
        };
    }

    drop(conn); // release the fds before the family rename
    if !quarantine_store_artifacts(db_path) {
        // A clobbering swap would destroy part of the original family without a forensic record —
        // never swap onto a partial quarantine. The temp guard cleans the migrated family. The main
        // renames first; main-in-place means the original main is preserved, main-moved means the
        // data is not at its path.
        crate::boot::boot_diagnostic(format!(
            "store '{name}' original family could not be fully quarantined — the \
             rebuild swap would clobber it without a forensic record; rebuild aborted, \
             migrated data discarded",
        ));
        return if db_path.exists() {
            crate::boot::boot_diagnostic(format!(
                "store '{name}' original family remains in place — left for operator \
                 review",
            ));
            open_with_schema(db_path, schema)
                .await
                .map(|reopened| (RepairOutcome::NoRepair, reopened))
        } else {
            crate::boot::boot_diagnostic(format!(
                "store '{name}' original family is in the quarantine and the store \
                 path is empty — boot aborted; recover from the quarantine and retry",
            ));
            Err(anyhow::anyhow!(
                "the rebuild aborted with the original family partially quarantined and the \
                 main file already moved — the store path was not rebuilt"
            ))
        };
    }
    // Main-file rename first; the `-wal` moves only when it succeeds. The fresh store is normally
    // TRUNCATE-checkpointed first (`checkpoint_rebuilt_before_swap`), so its main file alone holds
    // every row; when the pre-shrink gate refused that, the journal still holds committed frames
    // and these two renames are the crash window that refusal accepts.
    let wal = wal_path(db_path);
    let temp_wal = wal_path(&temp);
    if let Err(e) = std::fs::rename(&temp, db_path) {
        // The swap cannot proceed: the store path is absent and the original family is in
        // quarantine. Bail loudly (the store's boot fails) instead of opening an empty store over
        // the abandoned migrated data; the temp guard discards it.
        return Err(anyhow::anyhow!(e).context(
            "the rebuild swap could not move the rebuilt store into place — migrated temp \
             family discarded; original family quarantined for recovery",
        ));
    }
    if temp_wal.exists()
        && let Err(e) = std::fs::rename(&temp_wal, &wal)
    {
        warn!(
            error = %e,
            from = %temp_wal.display(),
            to = %wal.display(),
            "rebuild swap sidecar rename failed",
        );
    }
    let reopened = match open_with_schema(db_path, schema).await {
        Ok(reopened) => reopened,
        Err(e) if is_actionable_signal(&e) => return Err(e),
        Err(e) => {
            // The reopened store failed — the quarantine holds the original.
            crate::boot::boot_diagnostic(format!(
                "store '{name}' rebuilt store reopen failed: {e} — original family is \
                 quarantined for recovery",
            ));
            return Err(e);
        }
    };
    // Post-swap verification: a genuine finding (integrity message or count mismatch) reports
    // loudly with its own diagnostic; a transient read error on the healthy swapped store stays at
    // warn level — "lost data" must not fire on the latter (it could prompt restoring the corrupt
    // original).
    let mut verified = true;
    let mut finding_reported = false;
    match reopened.quick_check().await {
        Ok(()) => {}
        Err(e) if is_actionable_signal(&e) => {
            warn!(error = %e, db = %name, "post-swap verification quick_check hit an actionable signal");
            verified = false;
        }
        Err(e) => {
            crate::boot::boot_diagnostic(format!(
                "store '{name}' rebuilt store failed post-swap quick_check ({e}) — \
                 original family is quarantined for recovery",
            ));
            verified = false;
            finding_reported = true;
        }
    }
    for (tbl, expected) in &counts {
        match count_table_rows(&reopened, tbl).await {
            // A read error is not proof of data loss — actionable signals warn transiently,
            // anything else is a genuine finding.
            Err(e) => {
                let err = anyhow::anyhow!(e);
                if is_actionable_signal(&err) {
                    verified = false;
                    warn!(
                        error = %err,
                        db = %name,
                        table = %tbl,
                        "post-swap counts verification query hit an actionable signal",
                    );
                } else {
                    crate::boot::boot_diagnostic(format!(
                        "store '{name}' post-swap verification counts query for table \
                         '{tbl}' failed ({err}) — verification incomplete; original \
                         family is quarantined for recovery",
                    ));
                    verified = false;
                    finding_reported = true;
                }
            }
            Ok(c) if c != *expected => {
                crate::boot::boot_diagnostic(format!(
                    "store '{name}' post-swap verification failed for table '{tbl}' \
                     (expected {expected} rows, found {c}) — the swap lost data; \
                     original family is quarantined for recovery",
                ));
                verified = false;
                finding_reported = true;
            }
            Ok(_) => {}
        }
    }
    if verified {
        info!(db = %name, "overflow-aliasing repaired: store rebuilt data-preservingly");
        Ok((RepairOutcome::Migrated, reopened))
    } else {
        // Transient read errors only (no finding above): the swap succeeded and the store is in
        // place — the periodic integrity round re-verifies it from here.
        if !finding_reported {
            warn!(db = %name, "post-swap verification incomplete (transient read errors) — store is in place; the periodic integrity round verifies it from here");
        }
        Ok((RepairOutcome::NoRepair, reopened))
    }
}

/// Fold the rebuilt store's WAL into the temp main file before the swap, so a crash between the
/// main and `-wal` renames cannot leave a valid-but-empty store (turso does not checkpoint on
/// close). The checkpoint is reclaiming, so it passes the pre-shrink gate first; a refused gate
/// skips it and those two renames remain the crash window (see [`crate::db::shrink_gate`]).
///
/// The gate checks the rebuilt TEMP file (`conn`), not the live store's file.
async fn checkpoint_rebuilt_before_swap(
    conn: &Connection,
    name: &'static str,
    root: &Path,
) -> Result<(), MigrateFailure> {
    if !crate::db::shrink_gate::shrink_allowed(conn, name, Some(root)).await {
        return Ok(());
    }
    match conn.checkpoint_ungated().await {
        Ok(o) if o.is_complete() => Ok(()),
        Ok(o) => Err(MigrateFailure::Finding(format!(
            "rebuilt store checkpoint incomplete (busy={}, {} of {} frames)",
            o.busy, o.checkpointed_frames, o.log_frames,
        ))),
        Err(e) => Err(classify_migrate(e)),
    }
}

/// Failures of the overflow-aliasing rebuild, classified for the caller.
enum MigrateFailure {
    Actionable(anyhow::Error),
    /// Data-integrity finding (constraint violation) or any other non-actionable failure — report
    /// only; the original store is preserved.
    Finding(String),
}

/// Classify a rebuild-path error: actionable signals propagate, everything else is a report-only
/// finding (covers both `turso::Error` from the wrapper's query/execute and `anyhow::Error` from
/// checkpoint/quick_check).
fn classify_migrate<E: Into<anyhow::Error>>(e: E) -> MigrateFailure {
    let err = e.into();
    if is_actionable_signal(&err) {
        MigrateFailure::Actionable(err)
    } else {
        MigrateFailure::Finding(format!("{err:#}"))
    }
}

/// Build `INSERT INTO "…" VALUES (…)` for a row copy using positional placeholders
/// ([`sql_in_placeholders`]); `table_ref` is a bare identifier — the quotes are added here.
fn row_insert_sql(table_ref: &str, row: &Row) -> Result<(String, Vec<Value>), MigrateFailure> {
    let ncols = row.column_count();
    let mut vals = Vec::with_capacity(ncols);
    for c in 0..ncols {
        vals.push(row.get_value(c).map_err(classify_migrate)?);
    }
    Ok((
        format!(
            "INSERT INTO \"{table_ref}\" VALUES ({})",
            sql_in_placeholders(ncols)
        ),
        vals,
    ))
}

/// Replay the old store's schema (tables + indexes, creation order) into the fresh store and copy
/// every table's data row by row (two connections — the SQL engine cannot reference the old store
/// from the fresh one). Indexes are created before the copy and maintained by the inserts. Counts
/// are verified per table; a mismatch or constraint violation is a data-integrity finding, not
/// corruption.
async fn migrate_schema_and_data(
    old: &Connection,
    fresh: &Connection,
    counts: &[(String, i64)],
) -> Result<(), MigrateFailure> {
    let ddl_rows = old
        .query(
            &format!(
                "SELECT sql FROM sqlite_master \
                 WHERE sql IS NOT NULL \
                   AND {USER_OBJECT_FILTER} \
                 ORDER BY rowid"
            ),
            (),
        )
        .await
        .map_err(classify_migrate)?;
    for row in &ddl_rows {
        // sqlite_master.sql is always TEXT — a non-string is an engine anomaly; fail closed rather
        // than silently skipping the object (mirrors the counts loop's name handling).
        let ddl = row
            .get::<String>(0)
            .map_err(|e| MigrateFailure::Finding(format!("DDL replay row is not text ({e})")))?;
        fresh.execute(&ddl, ()).await.map_err(classify_migrate)?;
    }
    // sqlite_sequence (AUTOINCREMENT bookkeeping) is auto-created by the replayed DDLs; copying its
    // rows keeps the old watermark across the explicit-id copy, so deleted high ids are not
    // re-issued (surviving-rows tables; a fully-purged table restarts at 1, harmless).
    let has_sequence: i64 = old
        .query_row(
            "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='sqlite_sequence'",
            (),
            |r| r.get::<i64>(0),
        )
        .await
        .map_err(classify_migrate)?;
    if has_sequence > 0 {
        let seq_rows = old
            .query("SELECT * FROM sqlite_sequence", ())
            .await
            .map_err(classify_migrate)?;
        for row in &seq_rows {
            let (sql, vals) = row_insert_sql("sqlite_sequence", row)?;
            fresh.execute(&sql, vals).await.map_err(classify_migrate)?;
        }
    }
    for (tbl, expected) in counts {
        let quoted = tbl.replace('"', "\"\"");
        // Full-table materialization: `SELECT *` collects every row before the copy loop — a
        // boot-time memory spike on large stores, accepted for this rare repair path.
        let rows = old
            .query(&format!("SELECT * FROM \"{quoted}\""), ())
            .await
            .map_err(classify_migrate)?;
        let tx = fresh.begin_tx().await.map_err(classify_migrate)?;
        let mut copied = 0i64;
        for row in &rows {
            let (sql, vals) = row_insert_sql(&quoted, row)?;
            tx.execute(&sql, vals).await.map_err(classify_migrate)?;
            copied += 1;
        }
        tx.commit().await.map_err(classify_migrate)?;
        if copied != *expected {
            return Err(MigrateFailure::Finding(format!(
                "table '{tbl}' copy count {copied} != pre-migration {expected}",
            )));
        }
    }
    Ok(())
}

/// DROP+CREATE fallback for a REINDEX that could not clear the desync: reproduce the index's
/// original DDL from `sqlite_master` (validated on the prod copy; clears desyncs REINDEX cannot).
async fn drop_create_index_fallback(
    conn: &Connection,
    name: &str,
    index: &str,
    quoted: &str,
) -> RepairOutcome {
    let ddl = conn
        .query_optional(
            "SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?",
            (index.to_string(),),
            |row| row.get::<String>(0),
        )
        .await
        .ok()
        .flatten();
    let Some(ddl) = ddl else {
        crate::boot::boot_diagnostic(format!(
            "store '{name}' index '{index}' DDL not found in sqlite_master — cannot \
             DROP+CREATE; left for operator review",
        ));
        return RepairOutcome::NoRepair;
    };
    // Transactional: `execute_batch` is autocommit per statement, so a failed rebuild (e.g. a
    // UNIQUE-constraint violation on table data) would leave the index permanently dropped.
    // DROP+CREATE inside a tx rolls the DROP back when the CREATE fails, so the original (desynced)
    // index survives for operator review. The rollback is deferred: the dropped guard flags the
    // connection and the ROLLBACK fires at the next detached access (`run_detached` /
    // `lock_and_cleanup_owned`).
    let outcome = async {
        let tx = conn.begin_tx().await?;
        tx.execute_batch(&format!("DROP INDEX \"{quoted}\"; {ddl};"))
            .await?;
        tx.commit().await
    }
    .await;
    match outcome {
        Ok(()) if conn.quick_check().await.is_ok() => {
            info!(
                db = %name,
                index = %index,
                "class-B btree index desync repaired in place (DROP+CREATE)",
            );
            RepairOutcome::Repaired
        }
        Ok(()) => {
            // The batch committed but the post-rebuild quick_check is not clean (desync report or
            // the scan itself failed to run) — reported only; the store opens normally either way.
            crate::boot::boot_diagnostic(format!(
                "store '{name}' DROP+CREATE of '{index}' post-rebuild quick_check \
                 not clean — left for operator review",
            ));
            RepairOutcome::NoRepair
        }
        Err(repair_err) => {
            // The DROP is rolled back on the next connection operation (deferred) — the original
            // index is preserved, not dropped.
            crate::boot::boot_diagnostic(format!(
                "store '{name}' DROP+CREATE of '{index}' failed: {repair_err} — DROP \
                 rolled back on the next connection op, original index preserved; left \
                 for operator review",
            ));
            RepairOutcome::NoRepair
        }
    }
}

/// Extract the specific btree index name from a quick_check desync message (`wrong # of entries in
/// index <name>`). `None` for any other shape (overflow-aliasing, unreadable table — the FTS false
/// positive is already filtered by [`scan_integrity_rows`]).
fn desynced_index_name(msg: &str) -> Option<&str> {
    const PREFIX: &str = "wrong # of entries in index ";
    let rest = msg.strip_prefix(PREFIX)?;
    let end = rest.find(['\n', ';', '\r']).unwrap_or(rest.len());
    let name = &rest[..end];
    (!name.is_empty()).then_some(name)
}

/// WAL checkpoint mode — the engine's two compaction levels.
///
/// PASSIVE backfills as many frames as it can without blocking readers or writers and never resets
/// the shared WAL frame index, so it is safe beside live connections; the WAL keeps growing until a
/// TRUNCATE runs, which is why callers bound that growth with a size cap (see
/// [`crate::db::checkpoint`]). TRUNCATE additionally resets the shared frame index — the
/// live-writer corruption vector — so it must pass the pre-shrink gate
/// ([`crate::db::shrink_gate`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CheckpointMode {
    Passive,
    Truncate,
}

impl CheckpointMode {
    /// The mode a `truncate` flag selects — the rounds' cap decision, and the shape
    /// [`OwnConnection::checkpoint`] takes.
    fn from_truncate(truncate: bool) -> Self {
        if truncate {
            Self::Truncate
        } else {
            Self::Passive
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::Passive => "PASSIVE",
            Self::Truncate => "TRUNCATE",
        }
    }
}

/// Move a store's whole artifact family (`db` + `-wal`) aside to a timestamped quarantine name.
/// Best-effort: a rename failure is logged, never fatal. The quarantine copy is never deleted — it
/// is the forensic record for the verify-then-swap rebuild. `false` when any existing file could
/// not be moved (a partial quarantine — the migration path must abort with the un-moved files in
/// place).
#[must_use]
pub(crate) fn quarantine_store_artifacts(db_path: &Path) -> bool {
    quarantine_family(db_path, &[(db_path, ""), (&wal_path(db_path), "-wal")])
}

/// Shared quarantine-family rename (timestamped, PID + seq-suffixed so it never clobbers an earlier
/// quarantine: the seq counter is process-local, so the PID disambiguates same-second renames from
/// other processes, where POSIX rename would silently overwrite the earlier forensic copy).
///
/// True when every existing source was moved aside — a partial quarantine means a later clobbering
/// rename would destroy part of the forensic record, so the migration path aborts instead.
#[must_use]
fn quarantine_family(db_path: &Path, sources: &[(&Path, &str)]) -> bool {
    static QUARANTINE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let stamp = family_stamp();
    let seq = QUARANTINE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let base = if seq == 0 {
        format!(
            "{}.quarantine-{stamp}",
            db_path.file_name().unwrap_or_default().to_string_lossy()
        )
    } else {
        format!(
            "{}.quarantine-{stamp}-{seq}",
            db_path.file_name().unwrap_or_default().to_string_lossy()
        )
    };
    let mut complete = true;
    for (src, suffix) in sources {
        if !src.exists() {
            continue;
        }
        let dst = db_path.with_file_name(format!("{base}{suffix}"));
        if let Err(e) = std::fs::rename(src, &dst) {
            warn!(
                error = %e,
                from = %src.display(),
                to = %dst.display(),
                "Failed to quarantine store artifact",
            );
            complete = false;
        }
    }
    complete
}

/// Execute `work` within a transaction on `conn`, committing on success.
///
/// `action_label` is `&str` rather than `&'static str` so callers can include dynamic context.
/// `ticket_id` (or any identifying label) and `action_label` feed the structured warn-level logging
/// on failure.
///
/// Thin adapter over [`with_tx_outcome`]: commits whenever `work` returns `Ok`.
pub(crate) async fn with_tx(
    conn: &Connection,
    ticket_id: &str,
    action_label: &str,
    work: impl AsyncFnOnce(&TxGuard<'_>) -> anyhow::Result<()>,
) -> anyhow::Result<()> {
    with_tx_outcome(conn, ticket_id, action_label, async |tx| {
        work(tx).await?;
        Ok(true)
    })
    .await
    .map(|_| ())
}

/// Execute `work` within a transaction, letting the work choose the outcome via its return value.
///
/// `Ok(true)` commits. `Ok(false)` rolls back **without** a warning: the work deliberately aborted
/// and nothing must be written (the board layer's claim convention for expected no-ops, e.g. a CAS
/// phase-guard miss). `Err(e)` rolls back and logs the standard warn-level messages, including
/// `"{action_label}: transaction rolled back"`.
///
/// Returns `Ok(true)` when it committed, `Ok(false)` when it rolled back silently, and the wrapped
/// error on failure. This is the canonical transaction helper; [`with_tx`] delegates to it.
pub(crate) async fn with_tx_outcome(
    conn: &Connection,
    ticket_id: &str,
    action_label: &str,
    work: impl AsyncFnOnce(&TxGuard<'_>) -> anyhow::Result<bool>,
) -> anyhow::Result<bool> {
    let tx = conn
        .begin_tx()
        .await
        .map_err(|e| {
            warn!(
                ticket = %ticket_id,
                error = %e,
                "Failed to begin transaction for {action_label}",
            );
            e
        })
        .with_context(|| format!("Failed to begin transaction for {action_label}"))?;

    match work(&tx).await {
        Ok(true) => {
            tx.commit()
                .await
                .map_err(|e| {
                    warn!(
                        ticket = %ticket_id,
                        error = %e,
                        "Failed to commit transaction for {action_label}",
                    );
                    e
                })
                .with_context(|| format!("Failed to commit transaction for {action_label}"))?;
            Ok(true)
        }
        Ok(false) => {
            tx.rollback()
                .await
                .map_err(|e| {
                    warn!(
                        ticket = %ticket_id,
                        error = %e,
                        "Transaction rollback also failed for {action_label}",
                    );
                    e
                })
                .with_context(|| format!("Failed to roll back transaction for {action_label}"))?;
            Ok(false)
        }
        Err(e) => {
            if let Err(rollback_err) = tx.rollback().await {
                warn!(
                    ticket = %ticket_id,
                    error = %rollback_err,
                    "Transaction rollback also failed for {action_label}",
                );
            }
            warn!(
                ticket = %ticket_id,
                error = %e,
                "{action_label}: transaction rolled back",
            );
            Err(e.context(format!("{action_label}: transaction rolled back")))
        }
    }
}

/// Forensic-family name suffix `{stamp}-{pid}` (stamp `%Y%m%dT%H%M%SZ`). Parse side shape-validates
/// it via `debug::is_family_stamp`; bind once per family, since two calls could straddle a second
/// boundary.
#[must_use]
fn family_stamp() -> String {
    format!(
        "{}-{}",
        Utc::now().format("%Y%m%dT%H%M%SZ"),
        std::process::id()
    )
}

/// Test-support helpers shared by the db test modules (`mod.rs`, `checkpoint.rs`).
#[cfg(test)]
pub(crate) mod test_support {
    use std::path::Path;
    use std::process::Command;

    use anyhow::{Context, Result, ensure};

    use super::wal_guard::WAL_HEADER_BYTES;
    use super::{Connection, TICKETS_FTS_INDEX_NAME, now, params};

    /// Insert a minimal ticket row whose title is FTS-indexed (the `CREATE INDEX ... USING fts`
    /// index is auto-maintained).
    pub(crate) async fn insert_fts_ticket(conn: &Connection, id: &str, title: &str) {
        conn.execute(
            "INSERT INTO tickets (id, title, description, workspace_name, created_at, updated_at) \
             VALUES (?1, ?2, 'desc', 'ws', ?3, ?3)",
            params![id.to_string(), title.to_string(), now()],
        )
        .await
        .unwrap();
    }

    /// DDL replacing the ticket-title FTS index with a same-named plain btree — the deterministic
    /// corruption stand-in for FTS repair tests.
    pub(crate) fn fts_corruption_ddl() -> String {
        format!(
            "DROP INDEX {TICKETS_FTS_INDEX_NAME}; \
             CREATE INDEX {TICKETS_FTS_INDEX_NAME} ON tickets(title);"
        )
    }

    /// Assert that no forensic quarantine family was left in a store directory — a refused store
    /// must be left exactly as it was.
    pub(crate) fn assert_not_quarantined(dir: &std::path::Path, what: &str) {
        let quarantined: Vec<String> = std::fs::read_dir(dir)
            .expect("read the store dir")
            .filter_map(std::result::Result::ok)
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.contains("quarantine-"))
            .collect();
        assert!(
            quarantined.is_empty(),
            "{what} must not be quarantined, found: {quarantined:?}"
        );
    }

    /// Byte offset of the page-1 header's "database size in pages" field (a big-endian `u32`) —
    /// exactly the `database_size` the engine's reclaiming (TRUNCATE) checkpoint derives the new
    /// main-file size from.
    const PAGE_1_DATABASE_SIZE_OFFSET: u64 = 28;

    /// The fixed frame-header size of the SQLite WAL format: the page number, the commit marker,
    /// the two salts and the checksum pair, ahead of the page image (the 32-byte file header is
    /// [`WAL_HEADER_BYTES`]).
    const WAL_FRAME_HEADER_BYTES: usize = 24;

    /// The DDL and one row of every shrink-gate fixture store: real pages with a row that must
    /// survive, so a reclaiming checkpoint that shrank the store to nothing would destroy data.
    const FIXTURE_SCHEMA: &str = "CREATE TABLE fixture (id INTEGER PRIMARY KEY, v TEXT);";
    const FIXTURE_ROW: &str = "INSERT INTO fixture (v) VALUES ('data')";

    /// Create the fixture store (schema plus one row) through the engine and close the connection.
    /// turso takes no checkpoint on drop, so the committed frames stay in the `-wal` where fixture
    /// builders want them.
    async fn create_fixture_store(db_path: &Path) {
        let conn = super::open_with_schema(db_path, FIXTURE_SCHEMA)
            .await
            .expect("create the shrink-gate fixture store");
        conn.execute(FIXTURE_ROW, ())
            .await
            .expect("insert the shrink-gate fixture row");
        drop(conn);
    }

    /// Build the destructive state whose resolved page-1 header declares no pages (see
    /// [`crate::db::shrink_gate`]): `PRAGMA page_count` answers 0 while the main file holds real
    /// pages and the rows still read — so an ungated reclaiming checkpoint would truncate it to
    /// nothing. A real store is checkpointed (TRUNCATE) and its page-1 header's declared page count
    /// is then patched to 0. A test fixture may open the store file; the product may not
    /// (wal_guard's lock rule).
    pub(crate) async fn build_zero_page_count_store(db_path: &Path) {
        use std::io::{Seek, SeekFrom, Write};

        let conn = super::open_with_schema(db_path, FIXTURE_SCHEMA)
            .await
            .expect("create the shrink-gate fixture store");
        conn.execute(FIXTURE_ROW, ())
            .await
            .expect("insert the shrink-gate fixture row");
        conn.checkpoint_ungated()
            .await
            .expect("truncate-checkpoint the shrink-gate fixture store");
        drop(conn);

        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .open(db_path)
            .expect("open the shrink-gate fixture store to patch its page-1 header");
        file.seek(SeekFrom::Start(PAGE_1_DATABASE_SIZE_OFFSET))
            .expect("seek to the page-1 database-size field");
        file.write_all(&0u32.to_be_bytes())
            .expect("zero the page-1 database-size field");
    }

    /// Build the destructive state of an empty main file with a non-empty journal: a real store
    /// whose committed frames are still in the `-wal`, with the main file then truncated to 0
    /// bytes. The engine that reopens it sees an empty database — `sqlite_schema` is empty, so the
    /// fixture's rows are NOT readable — and discards the orphan journal as it opens: turso 0.8.0
    /// answers 0 pages. The state is a boot refusal, and this fixture pins that it never reaches a
    /// reclaiming round.
    pub(crate) async fn build_empty_main_file_store(db_path: &Path) {
        create_fixture_store(db_path).await;
        let wal = super::wal_path(db_path);
        let wal_bytes = std::fs::metadata(&wal)
            .expect("the fixture store must leave a journal")
            .len();
        assert!(
            wal_bytes > WAL_HEADER_BYTES,
            "the fixture must leave committed frames in its journal, found {wal_bytes} bytes",
        );
        // Truncate only the main file: the journal is left exactly as the engine committed it.
        std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(db_path)
            .expect("truncate the fixture's main file");
    }

    /// Build the destructive state whose newest in-journal page-1 image declares no pages: the main
    /// file is intact, but the page-1 image the engine resolves comes from the journal, so `PRAGMA
    /// page_count` answers 0 while the rows stay readable. [`zero_wal_page_1_database_size`]
    /// self-checks the checksums it rewrites; what the engine resolves from the patched journal is
    /// the caller's to assert.
    pub(crate) async fn build_zero_page_count_wal_store(db_path: &Path) {
        create_fixture_store(db_path).await;
        zero_wal_page_1_database_size(db_path);
    }

    /// Zero the page-1 "database size in pages" field of the newest in-journal page-1 image,
    /// re-checksumming the frame chain from that frame to the end (the stored checksums after it
    /// are seeded by it).
    ///
    /// A test fixture may write these bytes; the product may not (wal_guard's lock rule).
    fn zero_wal_page_1_database_size(db_path: &Path) {
        let wal = super::wal_path(db_path);
        let mut bytes = std::fs::read(&wal).expect("read the fixture journal");
        let header_len = usize::try_from(WAL_HEADER_BYTES).expect("the WAL header fits a usize");
        // The WAL's magic selects the byte order every checksum word is read in (see
        // [`wal_checksum`]).
        let use_native = cfg!(target_endian = "big") == (be_u32(&bytes, 0) & 1 == 1);
        let page_size = usize::try_from(be_u32(&bytes, 8)).expect("the WAL page size fits a usize");
        let frame_size = WAL_FRAME_HEADER_BYTES + page_size;

        // Self-check first: every frame's stored checksum must be the cumulative checksum of what
        // is on disk. If not, this helper's algorithm does not match the engine's and any patch
        // would be a bogus fixture — fail loudly rather than fabricate one. Frame numbering follows
        // the engine's own scan: it stops at the first frame header with page 0.
        let mut seed = (be_u32(&bytes, 24), be_u32(&bytes, 28));
        let mut newest_page_1 = None;
        let mut offset = header_len;
        while offset + frame_size <= bytes.len() && be_u32(&bytes, offset) != 0 {
            let computed = frame_checksum(&bytes, offset, frame_size, seed, use_native);
            assert_eq!(
                computed,
                (be_u32(&bytes, offset + 16), be_u32(&bytes, offset + 20)),
                "the fixture journal's frame at offset {offset} does not carry the cumulative \
                 checksum of its bytes — the fixture's checksum algorithm does not match the \
                 engine's",
            );
            seed = computed;
            if be_u32(&bytes, offset) == 1 {
                newest_page_1 = Some(offset);
            }
            offset += frame_size;
        }
        let patch_at = newest_page_1.expect("the fixture journal must hold a page-1 image");

        let field = patch_at
            + WAL_FRAME_HEADER_BYTES
            + usize::try_from(PAGE_1_DATABASE_SIZE_OFFSET)
                .expect("the page-1 database-size offset fits a usize");
        bytes[field..field + 4].fill(0);

        // Re-checksum the whole chain with the patched page image; the frames before the patch
        // recompute to the values already stored, so only the patched frame and the ones after it
        // change.
        let mut seed = (be_u32(&bytes, 24), be_u32(&bytes, 28));
        let mut offset = header_len;
        while offset + frame_size <= bytes.len() && be_u32(&bytes, offset) != 0 {
            let computed = frame_checksum(&bytes, offset, frame_size, seed, use_native);
            bytes[offset + 16..offset + 20].copy_from_slice(&computed.0.to_be_bytes());
            bytes[offset + 20..offset + 24].copy_from_slice(&computed.1.to_be_bytes());
            seed = computed;
            offset += frame_size;
        }
        std::fs::write(&wal, &bytes).expect("write the patched fixture journal");
    }

    /// The cumulative checksum a journal frame at `offset` stores: the frame header's first 8 bytes
    /// (page number and commit marker) fed the running chain, then its page image.
    fn frame_checksum(
        bytes: &[u8],
        offset: usize,
        frame_size: usize,
        seed: (u32, u32),
        use_native: bool,
    ) -> (u32, u32) {
        wal_checksum(
            &bytes[offset + WAL_FRAME_HEADER_BYTES..offset + frame_size],
            wal_checksum(&bytes[offset..offset + 8], seed, use_native),
            use_native,
        )
    }

    /// The engine's cumulative WAL checksum (SQLite's), mirrored from turso's `checksum_wal`:
    /// 32-bit word pairs read in the byte order the WAL header's magic selects, folded into two
    /// running sums. `data` must be a multiple of 8 bytes.
    fn wal_checksum(data: &[u8], seed: (u32, u32), use_native: bool) -> (u32, u32) {
        let word = |bytes: &[u8]| {
            let mut word = [0u8; 4];
            word.copy_from_slice(bytes);
            if use_native {
                u32::from_ne_bytes(word)
            } else {
                u32::from_ne_bytes(word).swap_bytes()
            }
        };
        let (mut s1, mut s2) = seed;
        let (groups, remainder) = data.as_chunks::<8>();
        assert!(
            remainder.is_empty(),
            "the cumulative WAL checksum is defined over 8-byte groups only",
        );
        for group in groups {
            let v0 = word(&group[0..4]);
            let v1 = word(&group[4..8]);
            s1 = s1.wrapping_add(v0.wrapping_add(s2));
            s2 = s2.wrapping_add(v1.wrapping_add(s1));
        }
        (s1, s2)
    }

    /// The big-endian `u32` the WAL format stores at `offset` (every field, checksums included).
    fn be_u32(bytes: &[u8], offset: usize) -> u32 {
        u32::from_be_bytes(
            bytes[offset..offset + 4]
                .try_into()
                .expect("the field is four bytes"),
        )
    }

    /// The fixture store's row count — it still answers queries in the gate's destructive state.
    pub(crate) async fn fixture_rows(conn: &Connection) -> i64 {
        conn.query_row("SELECT COUNT(*) FROM fixture", (), |r| r.get::<i64>(0))
            .await
            .expect("count the fixture rows")
    }

    /// The store's own `PRAGMA page_count` answer: exactly the field the pre-shrink gate reads.
    pub(crate) async fn page_count(conn: &Connection) -> i64 {
        conn.query_row("PRAGMA page_count;", (), |r| r.get::<i64>(0))
            .await
            .expect("ask the fixture store for its page count")
    }

    /// The two foreign-client probes: a read (needs a SHARED lock to load the schema) and a write
    /// (needs a RESERVED lock).
    pub(crate) const PROBES: [(&str, &str); 2] = [
        ("read", "SELECT count(*) FROM sqlite_schema;"),
        (
            "write",
            "CREATE TABLE lock_probe (x); INSERT INTO lock_probe VALUES (1);",
        ),
    ];

    /// Whether the stock `sqlite3` CLI is on `PATH`. The probes need it; the project's test run
    /// does not (see the module doc), so its absence skips them — the evidence then says so in
    /// place of the probe results, and the run still passes.
    pub(crate) fn sqlite3_available() -> bool {
        Command::new("sqlite3")
            .arg("--version")
            .output()
            .is_ok_and(|output| output.status.success())
    }

    /// Run one `sqlite3` probe against a live store, require it to be refused as locked, and return
    /// the first line of the refusal. Only called after [`sqlite3_available`]: a spawn failure here
    /// is a hard error, not a skip — running no probe is not the same as a refused probe.
    ///
    /// Assert on the lock/busy substring, never a byte-exact message (the phrasing varies by
    /// version): a non-zero exit alone proves nothing, since a lost lock lets `sqlite3` reach the
    /// schema, where turso's FTS DDL is unparseable and also exits non-zero.
    pub(crate) fn probe_store(store: &Path, sql: &str) -> Result<String> {
        let output = Command::new("sqlite3")
            .arg(store)
            .arg(sql)
            .output()
            .with_context(|| format!("spawning sqlite3 to probe {}", store.display()))?;
        let refusal = format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
        ensure!(
            !output.status.success(),
            "sqlite3 was NOT refused by {} (exit {}) — the store is unlocked: {}",
            store.display(),
            output.status,
            refusal.trim(),
        );
        let lower = refusal.to_lowercase();
        ensure!(
            lower.contains("locked") || lower.contains("busy"),
            "sqlite3 was refused by {} without a lock/busy error — the failure is not the lock: {}",
            store.display(),
            refusal.trim(),
        );
        Ok(refusal
            .lines()
            .next()
            .unwrap_or_default()
            .trim()
            .to_string())
    }

    /// Require both foreign probes against a live store to be refused as locked — the engine's
    /// process-wide record locks can only be observed from another process, so a refusal says the
    /// store is still held. Skipped, with a line saying so, when the stock `sqlite3` CLI is absent.
    pub(crate) fn foreign_client_is_refused(store: &Path) {
        if !sqlite3_available() {
            println!(
                "foreign-client probes SKIPPED for {}: no stock sqlite3 on PATH",
                store.display(),
            );
            return;
        }
        for (kind, sql) in PROBES {
            let refusal = probe_store(store, sql).unwrap_or_else(|e| {
                panic!("the foreign {kind} probe must be refused as locked: {e:#}")
            });
            println!(
                "foreign {kind} probe on {} refused: {refusal}",
                store.display()
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicUsize;
    use test_support::{assert_not_quarantined, fts_corruption_ddl, insert_fts_ticket};

    /// An existing store built with raw DDL only (no `schema_migrations` ledger) was never created
    /// by the product: opening it must refuse rather than build a schema inside it, and the file
    /// must stay byte-for-byte as it was.
    #[tokio::test]
    async fn existing_store_without_product_schema_is_refused() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        let db_path = store_db_path(root, "board");
        std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
        {
            let _conn = open_with_schema(
                &db_path,
                "CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY);",
            )
            .await
            .unwrap();
        }
        let before = std::fs::read(&db_path).unwrap();

        let err = open_store(root, "board", "")
            .await
            .expect_err("a store without the product schema must be refused");
        let refusal = err
            .downcast_ref::<StoreRefusal>()
            .unwrap_or_else(|| panic!("expected a StoreRefusal, got: {err:#}"));
        assert!(
            refusal.reason.contains("product's own schema"),
            "the reason must name the missing product schema: {}",
            refusal.reason
        );
        assert_not_quarantined(
            db_path.parent().unwrap(),
            "a store without the product schema",
        );
        assert_eq!(
            std::fs::read(&db_path).unwrap(),
            before,
            "the main file must be unchanged byte-for-byte"
        );
    }

    /// The forensic-family name writers (`quarantine_family`, the pre-reindex snapshot helper) must
    /// produce names the debug CLI's `--family` parser accepts — a writer change that breaks the
    /// listing contract fails here, not against a stale literal lock.
    #[test]
    fn family_writer_names_parse_via_debug_parser() {
        let dir = tempfile::TempDir::new().unwrap();
        let db_path = dir.path().join("board.db");
        let wal = wal_path(&db_path);
        for f in [&db_path, &wal] {
            std::fs::write(f, b"x").unwrap();
        }

        // Quarantine: move db + wal aside; every moved base name must be a valid `--family` id (the
        // listing/query contract).
        assert!(
            quarantine_store_artifacts(&db_path),
            "quarantine writer must move every existing source"
        );
        let moved: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .filter(|n| n.contains("board.db.quarantine-"))
            .collect();
        assert_eq!(moved.len(), 2, "db + wal moved: {moved:?}");
        for name in moved {
            let base = name.strip_suffix("-wal").unwrap_or(&name);
            let meta = crate::db::debug::parse_family_name(base).unwrap_or_else(|| {
                panic!("quarantine writer name must parse as a family id: {name}")
            });
            assert_eq!(meta.store, "board");
            assert_eq!(meta.kind, crate::db::debug::FamilyKind::Quarantine);
        }

        // Pre-reindex snapshot: the writer helper's base name must parse too.
        let snap = pre_reindex_snapshot_path(&db_path);
        let meta = crate::db::debug::parse_family_name(snap.file_name().unwrap().to_str().unwrap())
            .expect("pre-reindex snapshot name must parse as a family id");
        assert_eq!(meta.kind, crate::db::debug::FamilyKind::PreReindex);
    }

    /// Guard: only [`crate::db::store`] may construct a store handle, and only it and the read-only
    /// debug CLI may arm the per-statement limit.
    /// All database access must go through [`crate::db::Connection`], which centralises the
    /// experimental feature flags, the per-connection settings, the per-statement limit, the
    /// writing connection's serialization, the reader pool and dangling-transaction handling. A
    /// handle built anywhere else — the SDK kit's `TursoDatabase::new` or the core API's
    /// `turso::core::Database::open*` — would have neither, and the limit would be silently
    /// disarmed.
    ///
    /// The debug CLI (`src/db/debug.rs`) is the documented exception, and only for the limit:
    /// it opens the store read-only with no lock and no create
    /// (`OpenFlags::ReadOnly | OpenFlags::NoLock`) and steps statements synchronously, which
    /// the connection layer does not offer.
    ///
    /// This is a source-scanning tripwire, not a security boundary: any new module that opens
    /// a store or arms the limit directly fails with a pointer to the canonical path.
    #[test]
    fn store_handle_creation_and_the_statement_limit_are_confined() {
        // Spelled in halves: this file is scanned too — it is where the handle used to be built —
        // so the literals must not match themselves. Each pattern carries its own exceptions: the
        // debug CLI may open and arm a store the way its read-only path needs, nothing else may
        // build a handle.
        const PATTERNS: [(&str, &[&str]); 4] = [
            (concat!("TursoDatabase", "::new("), &["src/db/store.rs"]),
            // The facade's own builder: the store it makes carries neither the experiment flags nor
            // the limit, and nothing in the tree starts one.
            (concat!("Builder", "::new_local", "("), &[]),
            // The low-level open: the handle it makes carries neither the feature flags nor the
            // limit unless both are set by hand.
            (concat!("core::Database", "::open"), &["src/db/debug.rs"]),
            (
                concat!("set_query_timeout", "("),
                &["src/db/store.rs", "src/db/debug.rs"],
            ),
        ];

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let files = crate::util::test::rs_files_under(&manifest_dir.join("src"));

        let mut violations: Vec<(String, &'static str)> = Vec::new();
        for file in files {
            let rel = crate::util::test::rel_source_path(manifest_dir, &file);
            let content = std::fs::read_to_string(&file).expect("read source file");
            // Skip line comments so doc comments mentioning the connection layer don't
            // false-positive — the tripwire targets actual code usage. Block comments are not
            // handled (best-effort by design).
            let code_only: String = content
                .lines()
                .filter(|line| !line.trim_start().starts_with("//"))
                .collect::<Vec<_>>()
                .join("\n");
            for (pattern, allowed) in PATTERNS {
                if !allowed.contains(&rel.as_str()) && code_only.contains(pattern) {
                    violations.push((rel.clone(), pattern));
                }
            }
        }

        assert!(
            violations.is_empty(),
            "a store handle was built, or the per-statement limit armed, outside the \
             connection layer and the debug CLI.\n\
             All database access must go through crate::db::Connection (db/mod.rs), whose \
             handles come from db/store.rs — the only place a store handle is built and the \
             limit armed;\n\
             the debug CLI (db/debug.rs) is the only documented exception, and only for the \
             limit on the connection it opens itself.\n\
             Violations: {violations:#?}"
        );
    }

    /// Guard: the in-memory temp-store setting is applied on EVERY turso connection the application
    /// opens.
    ///
    /// P0 incident (2026-08-17): a missing pinned temp root failed every statement whose plan
    /// contains eager temp-file opcodes (RETURNING buffers, ORDER BY+LIMIT heap sorts, DISTINCT,
    /// IN-subqueries, compound SELECTs, window functions, CREATE INDEX) and every overflowing
    /// sorter/hash-join spill with "I/O error (tempdir): entity not found" — turso_core's tempdir
    /// creation has no parent-creation and no fallback chain. The fix: every application connection
    /// runs with `PRAGMA temp_store = MEMORY` (the engine's `TempStore::Memory`), so intermediate
    /// query structures stay in RAM and a missing temp root cannot affect any turso operation.
    ///
    /// The carriers do NOT share one opening path: the writing connection (`Connection::open`) sets
    /// the pragma itself, the readers and the maintenance connection are made by
    /// `read_only_connection`, and the debug CLI's `connect_readonly` has its own. If one regresses
    /// the guarantee silently breaks; this tripwire reads each carrier's body and fails with a
    /// pointer to the requirement.
    #[test]
    fn in_memory_temp_store_applied_on_every_opening_path() {
        const PRAGMA: &str = "PRAGMA temp_store = MEMORY";
        // (file, the header of the function that must carry the PRAGMA itself)
        const CARRIERS: [(&str, &str); 3] = [
            ("src/db/mod.rs", "pub async fn open(path: &Path)"),
            ("src/db/mod.rs", "async fn read_only_connection("),
            ("src/db/debug.rs", "pub(crate) fn connect_readonly("),
        ];

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let mut violations: Vec<String> = Vec::new();
        for (file, header) in CARRIERS {
            let path = manifest_dir.join(file);
            let content =
                std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {file}: {e}"));
            // Skip line comments so doc comments mentioning the PRAGMA don't false-positive — the
            // tripwire targets actual code usage (same best-effort approach as the store-handle
            // guard).
            let code_only: String = content
                .lines()
                .filter(|line| !line.trim_start().starts_with("//"))
                .collect::<Vec<_>>()
                .join("\n");
            let body = function_body(&code_only, header).unwrap_or_else(|| {
                panic!("{file}: no function body found at `{header}` — the carrier moved")
            });
            if !body.contains(PRAGMA) {
                violations.push(format!(
                    "{file}: `{header}…` no longer applies the in-memory temp-store \
                     setting (missing `{PRAGMA}` in its own body).\n\
                     The missing-temp-root guarantee requires the writing connection \
                     to set it itself and every read-only connection of a store — the \
                     readers and the maintenance connection — to be made by \
                     `read_only_connection`, which sets it; the debug CLI's own \
                     opening path sets it too."
                ));
            }
        }

        assert!(
            violations.is_empty(),
            "in-memory temp-store regression guard failed:\n{}",
            violations.join("\n\n")
        );
    }

    /// The body of the function whose header begins at `header`: from that line
    /// to the line that closes it (a `}` at the header line's own indentation).
    fn function_body<'a>(code: &'a str, header: &str) -> Option<&'a str> {
        let start = code.find(header)?;
        let line_start = code[..start].rfind('\n').map_or(0, |i| i + 1);
        let indent = code[line_start..].chars().take_while(|c| *c == ' ').count();
        let close = format!("\n{}}}", " ".repeat(indent));
        let rest = &code[start..];
        Some(&rest[..rest.find(&close)?])
    }

    /// Verify that checkpoint reports a complete outcome on a healthy database for both TRUNCATE
    /// and PASSIVE modes, parsed from the result row rather than discarded as success, and that
    /// `is_complete` is false for a busy condition or leftover WAL frames (`log > checkpointed`).
    #[tokio::test]
    async fn test_checkpoint_reports_complete_outcome() {
        let complete = CheckpointOutcome {
            busy: false,
            log_frames: 0,
            checkpointed_frames: 0,
        };
        assert!(complete.is_complete());

        let busy = CheckpointOutcome {
            busy: true,
            log_frames: 0,
            checkpointed_frames: 0,
        };
        assert!(!busy.is_complete(), "busy outcome must be incomplete");

        let partial = CheckpointOutcome {
            busy: false,
            log_frames: 12,
            checkpointed_frames: 5,
        };
        assert!(
            !partial.is_complete(),
            "uncheckpointed WAL frames must be incomplete"
        );

        let tmp = tempfile::TempDir::new().expect("temp dir for test");
        let conn = Connection::open(tmp.path().join("test.db").as_path())
            .await
            .expect("open test database");
        conn.execute(
            "CREATE TABLE IF NOT EXISTS _test (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
            (),
        )
        .await
        .expect("create test table");
        conn.execute("INSERT INTO _test (id, val) VALUES (1, 'hello')", ())
            .await
            .expect("insert test row");

        let truncate = conn
            .checkpoint_ungated()
            .await
            .expect("truncate checkpoint should succeed on a healthy database");
        assert!(
            truncate.is_complete(),
            "TRUNCATE outcome must be complete: {truncate:?}"
        );
        let passive = conn
            .run_checkpoint(CheckpointMode::Passive)
            .await
            .expect("passive checkpoint should succeed on a healthy database");
        assert!(
            passive.is_complete(),
            "PASSIVE outcome must be complete: {passive:?}"
        );
    }

    /// An existing store data file that fails the file-level shape check refuses the boot: the file
    /// (and any `-wal`) is left byte-for-byte as it was — no quarantine, no recreate. An absent
    /// file is a genuine first launch and is created.
    #[tokio::test]
    async fn open_store_refuses_unusable_store_files() {
        let mut bad_page = vec![0u8; 4096];
        bad_page[..16].copy_from_slice(b"SQLite format 3\0");
        let cases = [
            ("0 bytes", Vec::new(), true),
            ("64 bytes", vec![0u8; 64], false),
            ("garbage (bad magic)", vec![0x42; 128], false),
            ("valid magic, page size 0", bad_page, false),
        ];
        for (name, bytes, with_wal) in cases {
            let tmp = tempfile::TempDir::new().expect("temp dir for test");
            let root = tmp.path();
            let db_path = store_db_path(root, "board");
            std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
            std::fs::write(&db_path, &bytes).unwrap();
            let wal_bytes = [0x7au8; 512];
            if with_wal {
                std::fs::write(wal_path(&db_path), wal_bytes).unwrap();
            }

            let err = open_store(root, "board", "")
                .await
                .expect_err("an unusable store file must refuse the boot");
            assert!(
                err.downcast_ref::<StoreRefusal>().is_some(),
                "{name}: expected a StoreRefusal, got: {err:#}"
            );
            assert_eq!(
                std::fs::read(&db_path).unwrap(),
                bytes,
                "{name}: the main file must be unchanged"
            );
            if with_wal {
                assert_eq!(
                    std::fs::read(wal_path(&db_path)).unwrap(),
                    wal_bytes,
                    "{name}: the -wal must be unchanged"
                );
            }
            assert_not_quarantined(db_path.parent().unwrap(), name);
        }

        let tmp = tempfile::TempDir::new().expect("temp dir for test");
        let root = tmp.path();
        let db_path = store_db_path(root, "board");
        let _conn = open_store(root, "board", "CREATE TABLE IF NOT EXISTS t (id INTEGER);")
            .await
            .expect("an absent store file is a genuine first launch");
        assert!(db_path.exists(), "first launch must create the store file");
    }

    /// A plausible-shaped real store with content damage must refuse, never be quarantined or
    /// recreated: the open's integrity scan errors with a `StoreRefusal` and leaves the main file
    /// as it was.
    /// The scan is on the boot path only when the start has a reason for it (see
    /// `open_present_store`); this exercises the scan's own outcome, the entry the warranted boot
    /// takes.
    #[tokio::test]
    async fn existing_corrupt_store_is_refused_not_recreated() {
        let tmp = tempfile::TempDir::new().expect("temp dir for test");
        let root = tmp.path();
        {
            let conn = open_consolidated_store(root)
                .await
                .expect("build a real product store");
            conn.checkpoint_ungated()
                .await
                .expect("checkpoint the fixture store");
        }
        let db_path = store_db_path(root, CONSOLIDATED_DB_NAME);
        let bytes = std::fs::read(&db_path).unwrap();
        assert!(bytes.len() > 8192, "fixture needs a multi-page core.db");
        let mut corrupted = bytes.clone();
        corrupted[4096..8192].fill(0); // zero the page-2 b-tree page
        std::fs::write(&db_path, &corrupted).unwrap();

        let err = open_and_repair_for_test(root, &db_path, CONSOLIDATED_DB_NAME, "")
            .await
            .expect_err("a content-damaged store must be refused");
        assert!(
            err.downcast_ref::<StoreRefusal>().is_some(),
            "expected a StoreRefusal, got: {err:#}"
        );
        assert_eq!(
            std::fs::read(&db_path).unwrap(),
            corrupted,
            "the refused store's main file must be unchanged"
        );
        assert_not_quarantined(db_path.parent().unwrap(), "a refused store");
    }

    /// The gate's unclean-end reason: a `-wal` carrying frames (the previous run never reached its
    /// exit checkpoint) warrants the open's one integrity scan, and a clean start of the same store
    /// runs none. The breakage repaired here is the ticket-title FTS index.
    #[tokio::test]
    async fn uncheckpointed_journal_warrants_the_open_scan() {
        let tmp = tempfile::TempDir::new().expect("temp dir for test");
        let root = tmp.path();
        let db_path = store_db_path(root, CONSOLIDATED_DB_NAME);
        {
            let conn = open_consolidated_store(root)
                .await
                .expect("build a real product store");
            insert_fts_ticket(&conn, "t-1", "Important bug fix one").await;
            conn.execute_batch(&fts_corruption_ddl()).await.unwrap();
        }
        assert!(
            wal_guard::wal_size(&db_path) > wal_guard::WAL_HEADER_BYTES,
            "the fixture must leave frames in the journal, not just its header"
        );

        let conn = open_store(root, CONSOLIDATED_DB_NAME, "")
            .await
            .expect("the store opens");
        assert!(
            is_fts_index(&conn, TICKETS_FTS_INDEX_NAME).await,
            "an unclean previous end must reach the scan that repairs the index"
        );

        // Break it again and hand the store off the way a clean exit does: the journal is
        // truncated, so the next start has no reason to scan.
        conn.execute_batch(&fts_corruption_ddl()).await.unwrap();
        conn.checkpoint_ungated()
            .await
            .expect("truncate the journal");
        drop(conn);
        assert_eq!(
            wal_guard::wal_size(&db_path),
            0,
            "a clean exit leaves no journal behind"
        );

        let conn = open_store(root, CONSOLIDATED_DB_NAME, "")
            .await
            .expect("the store opens");
        assert!(
            !is_fts_index(&conn, TICKETS_FTS_INDEX_NAME).await,
            "a clean start runs no scan, so nothing repairs an index it was not told to"
        );
    }

    /// The gate's runtime-failure reason: the periodic round cannot repair under live readers, so
    /// it leaves a marker beside the store ([`wal_guard::note_integrity_scan_owed`]). An otherwise
    /// clean start runs the scan that marker asks for, and a completed scan clears it.
    #[tokio::test]
    async fn a_recorded_runtime_integrity_failure_warrants_the_open_scan() {
        let tmp = tempfile::TempDir::new().expect("temp dir for test");
        let root = tmp.path();
        let db_path = store_db_path(root, CONSOLIDATED_DB_NAME);
        {
            let conn = open_consolidated_store(root)
                .await
                .expect("build a real product store");
            insert_fts_ticket(&conn, "t-1", "Important bug fix one").await;
            conn.execute_batch(&fts_corruption_ddl()).await.unwrap();
            conn.checkpoint_ungated()
                .await
                .expect("truncate the journal");
        }
        assert_eq!(
            wal_guard::wal_size(&db_path),
            0,
            "the journal must not be the reason here — the marker is"
        );
        assert!(!wal_guard::integrity_scan_owed(&db_path));

        wal_guard::note_integrity_scan_owed(&db_path);
        let conn = open_store(root, CONSOLIDATED_DB_NAME, "")
            .await
            .expect("the store opens");
        assert!(
            is_fts_index(&conn, TICKETS_FTS_INDEX_NAME).await,
            "a recorded runtime integrity failure must reach the scan that repairs the index"
        );
        assert!(
            !wal_guard::integrity_scan_owed(&db_path),
            "a completed scan clears the marker"
        );
    }

    /// The quick_check desync parser names exactly the non-FTS btree index,
    /// and refuses the overflow-aliasing / unreadable shapes (never REINDEX).
    #[test]
    fn desynced_index_name_parses_quick_check_shapes() {
        assert_eq!(
            desynced_index_name("wrong # of entries in index idx_tickets_phase"),
            Some("idx_tickets_phase")
        );
        assert_eq!(
            desynced_index_name("wrong # of entries in index a; row 5 missing"),
            Some("a")
        );
        assert!(
            desynced_index_name(
                "wrong # of entries in index __turso_internal_fts_dir_idx_tickets_title_fts_key"
            )
            .is_some()
        );
        assert!(desynced_index_name("Page referenced multiple times: page 167772160").is_none());
        assert!(desynced_index_name("short read on page 12").is_none());
        assert!(desynced_index_name("row 5 missing from index idx_x").is_none());
        assert!(desynced_index_name("ok").is_none());
    }

    /// The overflow-aliasing veto is structural: a named index desync in an earlier row must NOT
    /// lead to a REINDEX when a later row reports overflow-aliasing. The matcher covers turso's
    /// real message shape and the baked short-read (page 0x0A000000) — both route to the
    /// data-preserving rebuild, while a genuine short read on a real page stays unreadable
    /// (refused).
    #[test]
    fn overflow_aliasing_vetoes_reindex_across_rows() {
        assert!(matches!(
            classify_repair_target(&[
                "wrong # of entries in index idx_phase".to_string(),
                "Page referenced multiple times: page 167772160".to_string(),
            ]),
            RepairTarget::OverflowAliasing
        ));
        // turso's actual message shape (index leaves sharing an overflow page).
        assert!(matches!(
            classify_repair_target(&[
                "*** in database main ***\nPage 871 referenced multiple times \
                 (references=[3, 3], page_category=Normal)"
                    .to_string(),
                "wrong # of entries in index idx_t_v".to_string(),
            ]),
            RepairTarget::OverflowAliasing
        ));
        assert!(matches!(
            classify_repair_target(&[
                "Page referenced multiple times: page 5".to_string(),
                "wrong # of entries in index idx_phase".to_string(),
            ]),
            RepairTarget::OverflowAliasing
        ));
        // The baked overflow-aliasing signature routes to the rebuild, not to a refusal.
        assert!(matches!(
            classify_repair_target(&["short read on page 167772160".to_string()]),
            RepairTarget::OverflowAliasing
        ));
        assert!(matches!(
            classify_repair_target(&[
                "wrong # of entries in index idx_phase".to_string(),
                "short read on page 12".to_string(),
            ]),
            RepairTarget::Unreadable
        ));
        assert!(matches!(
            classify_repair_target(&["short read on page 12".to_string()]),
            RepairTarget::Unreadable
        ));
        assert!(matches!(
            classify_repair_target(&["wrong # of entries in index idx_phase".to_string()]),
            RepairTarget::Index(name) if name == "idx_phase"
        ));
        assert!(matches!(
            classify_repair_target(&["row 5 missing from index idx_x".to_string()]),
            RepairTarget::Unknown
        ));
    }

    /// The runtime integrity record must not file an unknown (report-only) quick_check signature as
    /// damage, but must file every signature the boot path acts on.
    #[test]
    fn only_unrecognised_integrity_signatures_are_tolerated() {
        assert!(is_tolerated_integrity_report(&[
            "row 5 missing from index idx_x".to_string(),
        ]));
        assert!(!is_tolerated_integrity_report(&[
            "wrong # of entries in index idx_phase".to_string(),
        ]));
        assert!(!is_tolerated_integrity_report(&[
            "Invalid page type: page 7".to_string(),
        ]));
        assert!(is_tolerated_integrity_report(&[]));
    }

    /// The known FTS-dir count-mismatch false positive is masked, while other
    /// messages naming the same internal index (genuine corruption) are not.
    #[test]
    fn known_fts_dir_false_positive_classification() {
        let fp = "wrong # of entries in index __turso_internal_fts_dir_idx_tickets_title_fts_key";
        assert!(fp.contains(KNOWN_FTS_DIR_COUNT_FALSE_POSITIVE));

        let genuine_missing =
            "row 5 missing from index __turso_internal_fts_dir_idx_tickets_title_fts_key";
        let genuine_unique =
            "non-unique entry in index __turso_internal_fts_dir_idx_tickets_title_fts_key";
        assert!(!genuine_missing.contains(KNOWN_FTS_DIR_COUNT_FALSE_POSITIVE));
        assert!(!genuine_unique.contains(KNOWN_FTS_DIR_COUNT_FALSE_POSITIVE));
    }

    /// turso rolls back DDL: the class-B DROP+CREATE fallback wraps the pair in a transaction
    /// because `execute_batch` is autocommit per statement — a failed rebuild must leave the
    /// original index in place. Covers both rollback paths: the explicit one and the production
    /// failure path (guard dropped without commit → deferred ROLLBACK on the next connection op).
    #[tokio::test]
    async fn transactional_ddl_rollback_preserves_dropped_index() {
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = open_with_schema(
            &tmp.path().join("t.db"),
            "CREATE TABLE t (a TEXT, b TEXT); \
             INSERT INTO t VALUES ('1', 'x'), ('1', 'y'); \
             CREATE UNIQUE INDEX u ON t(b);",
        )
        .await
        .expect("open test store");
        // The failed rebuild: DROP the existing index, then CREATE a UNIQUE index on the duplicated
        // column — the constraint violation aborts the batch; the rollback must restore `u`.
        let tx = conn.begin_tx().await.expect("begin tx");
        let err = tx
            .execute_batch("DROP INDEX u; CREATE UNIQUE INDEX u2 ON t(a);")
            .await
            .expect_err("CREATE UNIQUE on duplicated data must fail");
        assert!(
            format!("{err}").to_lowercase().contains("unique"),
            "expected a constraint violation, got: {err}"
        );
        tx.rollback().await.expect("rollback");
        // Production path: the guard is dropped without commit/rollback after the failure — the
        // dangling flag makes the next connection op (query → lock_and_cleanup) issue the deferred
        // ROLLBACK.
        {
            let tx = conn.begin_tx().await.expect("begin tx");
            let err = tx
                .execute_batch("DROP INDEX u; CREATE UNIQUE INDEX u2 ON t(a);")
                .await
                .expect_err("CREATE UNIQUE on duplicated data must fail");
            assert!(
                format!("{err}").to_lowercase().contains("unique"),
                "expected a constraint violation, got: {err}"
            );
        }
        let names: Vec<String> = conn
            .query_map_strict(
                "SELECT name FROM sqlite_master WHERE type = 'index' AND name IN ('u', 'u2')",
                (),
                |row| row.get::<String>(0),
            )
            .await
            .expect("query sqlite_master");
        assert_eq!(names, vec!["u".to_string()], "original index must survive");
        conn.quick_check()
            .await
            .expect("store must be consistent after the rollback");
        let n: i64 = conn
            .query_row("SELECT COUNT(*) FROM t INDEXED BY u", (), |row| {
                row.get::<i64>(0)
            })
            .await
            .expect("INDEXED BY must resolve");
        assert_eq!(n, 2);
    }

    /// Open a one-column store for the orphan-transaction tests below.
    async fn open_orphan_tx_store() -> (tempfile::TempDir, Connection) {
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = open_with_schema(&tmp.path().join("t.db"), "CREATE TABLE t (a INTEGER);")
            .await
            .expect("open test store");
        (tmp, conn)
    }

    async fn orphan_tx_rows(conn: &Connection) -> Vec<i64> {
        conn.query_map_strict("SELECT a FROM t ORDER BY a", (), |row| row.get::<i64>(0))
            .await
            .expect("query t")
    }

    /// Whether the connection is in autocommit (no transaction open) — probed
    /// under the connection's own lock, so the probe cleans nothing up itself.
    async fn orphan_tx_autocommit(conn: &Connection) -> bool {
        conn.conn.lock().await.is_autocommit()
    }

    /// Window (a): a transaction abandoned without commit, rolled back by the deferred arm — the
    /// guard is dropped and the next access must undo the still-open write before reusing the
    /// connection.
    #[tokio::test]
    async fn an_abandoned_transaction_is_rolled_back_before_the_connection_is_reused() {
        let (_tmp, conn) = open_orphan_tx_store().await;

        {
            let tx = conn.begin_tx().await.expect("begin tx");
            tx.execute("INSERT INTO t VALUES (1)", ())
                .await
                .expect("insert in the abandoned tx");
        }
        assert!(
            conn.has_dangling_tx.load(Ordering::SeqCst),
            "an abandoned transaction must leave the deferred arm set"
        );

        conn.execute("INSERT INTO t VALUES (2)", ())
            .await
            .expect("write after the abandon");
        assert_eq!(
            orphan_tx_rows(&conn).await,
            vec![2],
            "the abandoned insert must be rolled back, not committed into the new one"
        );
        assert!(
            orphan_tx_autocommit(&conn).await,
            "the connection must be in autocommit before it is reused"
        );
    }

    /// Window (b) — the incident: a transaction the arm never saw (`BEGIN` reached the engine,
    /// nothing was flagged) must still be rolled back before the connection is reused.
    #[tokio::test]
    async fn an_open_transaction_the_arm_never_saw_is_rolled_back_before_reuse() {
        let (_tmp, conn) = open_orphan_tx_store().await;

        // Drive the state directly on the connection, under its own lock: a raw `BEGIN` plus a
        // write, so the insert lands inside the orphan transaction and the arm stays false.
        {
            let raw = conn.conn.lock().await;
            raw.execute("BEGIN", ()).await.expect("raw BEGIN");
            raw.execute("INSERT INTO t VALUES (1)", ())
                .await
                .expect("insert in the orphan tx");
        }
        assert!(
            !conn.has_dangling_tx.load(Ordering::SeqCst),
            "the arm must be false — that is the missed window"
        );

        conn.execute("INSERT INTO t VALUES (2)", ())
            .await
            .expect("write after the orphan tx");
        // A committed insert into the orphan transaction would leave both rows.
        assert_eq!(
            orphan_tx_rows(&conn).await,
            vec![2],
            "the orphan transaction must be rolled back before the connection is reused"
        );
        assert!(
            orphan_tx_autocommit(&conn).await,
            "the connection must be in autocommit before it is reused"
        );
    }

    /// A stale arm with nothing open — what an interrupted `begin_tx` leaves before its `BEGIN`
    /// runs, or `BEGIN` failing — must be cleared, not kept alive by a doomed ROLLBACK that would
    /// repeat forever.
    #[tokio::test]
    async fn a_stale_arm_without_an_open_transaction_is_cleared() {
        let (_tmp, conn) = open_orphan_tx_store().await;

        conn.has_dangling_tx.store(true, Ordering::SeqCst);
        conn.execute("INSERT INTO t VALUES (1)", ())
            .await
            .expect("write after a stale arm");
        assert!(
            !conn.has_dangling_tx.load(Ordering::SeqCst),
            "nothing was open, so the arm must be cleared rather than kept"
        );
        assert_eq!(orphan_tx_rows(&conn).await, vec![1]);
    }

    /// The debug validator — applied before a query is sent anywhere — takes the reader guard's
    /// verdict as its own, so a query it accepts can never be turned away by the reader that serves
    /// it. The validator may refuse more; that direction only keeps a query from leaving the
    /// client.
    #[test]
    fn nothing_a_reader_refuses_survives_the_debug_validator() {
        // Every statement form the guard must refuse — asserted first, so this check cannot pass by
        // the guard going quiet.
        for sql in [
            "BEGIN",
            "COMMIT",
            "SAVEPOINT s",
            "RELEASE s",
            "ATTACH DATABASE 'other.db' AS other",
            "DETACH other",
            "PRAGMA wal_checkpoint(TRUNCATE)",
            "PRAGMA [wal_checkpoint]",
            "PRAGMA journal_mode=WAL",
            "PRAGMA query_only = 0",
            "PRAGMA user_version = 5",
            "PRAGMA [user_version] = 5",
            ";;  PRAGMA [wal_checkpoint]",
            "PRAGMA not_a_pragma",
        ] {
            let reason =
                reader_refusal(sql).unwrap_or_else(|| panic!("a reader must refuse '{sql}'"));
            assert!(
                crate::db::debug::validate_read_only(sql).is_err(),
                "the validator must refuse what a reader refuses: '{sql}' ({reason})"
            );
        }
        for sql in [
            "SELECT 1",
            "SELECT * FROM tickets",
            "SELECT 'DROP TABLE tickets'",
            "PRAGMA quick_check",
            "PRAGMA integrity_check(1)",
            "PRAGMA table_info(tickets)",
            "PRAGMA [table_info](tickets)",
            "PRAGMA table_info = tickets",
            "PRAGMA table_info('a=b')",
            "PRAGMA \"quick_check\"",
            "PRAGMA `stats`",
            "PRAGMA foreign_key_list(tickets)",
            // The call form of a settable listed name: no-op on a store the engine has initialized,
            // so the guard leaves it to the engine.
            "PRAGMA page_size(8192)",
            ";;SELECT 1",
        ] {
            assert!(
                reader_refusal(sql).is_none(),
                "'{sql}' is a read a reader must serve"
            );
            assert!(
                crate::db::debug::validate_read_only(sql).is_ok(),
                "'{sql}' must pass the validator"
            );
        }
    }

    /// Open a real product store (readers enabled) for the reader-pool tests.
    async fn open_reader_store() -> (tempfile::TempDir, Connection) {
        let tmp = tempfile::TempDir::new().expect("temp dir for test");
        let conn = open_consolidated_store(tmp.path())
            .await
            .expect("open a store with reader connections");
        (tmp, conn)
    }

    /// The reader entry refuses every statement form that changes state — the ones the engine's
    /// read-only switch already refuses (DML/DDL) and the ones it does not: transaction control,
    /// `ATTACH`, the compaction and the pragma setters. A change left to a reader would commit and
    /// never be recorded, because change capture runs on the writing connection only.
    #[tokio::test]
    async fn a_change_routed_to_a_reader_is_refused_loudly() {
        let (_tmp, conn) = open_reader_store().await;
        conn.execute_batch("CREATE TABLE reader_probe (id INTEGER)")
            .await
            .expect("create the probe table");
        // The forms the reader entry refuses itself. The leading `;;` is the engine's own
        // empty-statement skip — a guard that stopped at the separator would let the statement
        // after it through.
        for sql in [
            "BEGIN",
            "COMMIT",
            "SAVEPOINT s",
            "RELEASE s",
            "ATTACH DATABASE 'other.db' AS other",
            "PRAGMA wal_checkpoint(TRUNCATE);",
            "PRAGMA query_only = 0;",
            ";;PRAGMA wal_checkpoint(TRUNCATE);",
            ";;PRAGMA query_only = 0;",
        ] {
            let err = conn
                .query(sql, ())
                .await
                .expect_err("a change must not be served by a reader");
            assert!(
                err.to_string()
                    .contains("refused on a read-only connection"),
                "'{sql}' must be refused by the reader entry, got: {err}"
            );
        }
        // ...and one the engine's own switch refuses when the statement is prepared on the
        // read-only connection.
        assert!(
            conn.query("INSERT INTO reader_probe VALUES (1)", ())
                .await
                .is_err(),
            "a write statement must be refused on a reader"
        );
        // A quoted or bracketed name is the name inside it, which is how the engine parses it and
        // how the debug validator's tokenizer hands it over: a bracketed writing pragma is refused
        // all the same...
        let bracketed = conn
            .query("PRAGMA [wal_checkpoint];", ())
            .await
            .expect_err("a bracketed pragma name must not slip past the guard");
        assert!(
            bracketed.to_string().contains("wal_checkpoint"),
            "the refusal must name the pragma it runs, got: {bracketed}"
        );
        assert!(
            !conn
                .query("PRAGMA [table_info](tickets);", ())
                .await
                .expect("a bracketed read pragma must be served")
                .is_empty(),
            "the bracketed form of a listed pragma is that pragma"
        );
        // The same entry still serves reads, and the store's writing connection is untouched by the
        // refusals.
        assert_eq!(conn.query("SELECT 1", ()).await.expect("a read").len(), 1);
        assert!(
            conn.query("SELECT count(*) FROM reader_probe", ())
                .await
                .expect("a read")
                .first()
                .is_some_and(|row| {
                    row.get_value(0)
                        .is_ok_and(|v| v.as_integer().copied() == Some(0))
                }),
            "no refused statement may have changed the store"
        );
        conn.execute("INSERT INTO reader_probe VALUES (1)", ())
            .await
            .expect("a change on the writing connection still lands");
    }

    /// A change that has returned is what the next read sees: a reader connection is reused between
    /// reads and must never hand back a view from before the change.
    #[tokio::test]
    async fn a_read_after_a_change_sees_the_change() {
        let (_tmp, conn) = open_reader_store().await;
        conn.execute_batch("CREATE TABLE reader_probe (id INTEGER)")
            .await
            .expect("create the probe table");
        for id in 0..12 {
            conn.execute("INSERT INTO reader_probe VALUES (?1)", params![id])
                .await
                .expect("write");
            let rows = conn
                .query("SELECT id FROM reader_probe WHERE id = ?1", params![id])
                .await
                .expect("read");
            assert_eq!(
                rows.len(),
                1,
                "the read after the change must see it (iteration {id})"
            );
        }
    }

    /// A read that belongs to a transaction is served by that transaction: the read entry refuses a
    /// read issued by the task holding it, so it can no longer be served by a reader behind the
    /// transaction's back. A read from any other task is unrelated and stays served.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_read_inside_a_transaction_goes_through_the_transaction() {
        let (_tmp, conn) = open_reader_store().await;
        conn.execute_batch("CREATE TABLE reader_probe (id INTEGER)")
            .await
            .expect("create the probe table");
        // The transaction is opened by a spawned task, as the service's own transaction work is:
        // the rule is about the task that holds it.
        let (tx_open, opened) = tokio::sync::oneshot::channel::<()>();
        let (release, released) = tokio::sync::oneshot::channel::<()>();
        let holder = conn.clone();
        let holder_task = tokio::spawn(async move {
            let tx = holder.begin_tx().await.expect("begin tx");
            tx.execute("INSERT INTO reader_probe VALUES (7)", ())
                .await
                .expect("write in the transaction");
            // The transaction's own read sees its own uncommitted write...
            let own = tx
                .query("SELECT id FROM reader_probe", ())
                .await
                .expect("the transaction's own read")
                .len();
            // ...while this task's read through the connection is refused instead of being served a
            // view the transaction has not made true.
            let refused = holder
                .query("SELECT id FROM reader_probe", ())
                .await
                .expect_err("a read of the transaction's own work must go through it");
            tx_open.send(()).expect("the test is still listening");
            released.await.expect("the test releases the transaction");
            tx.commit().await.expect("commit");
            (own, refused.to_string())
        });
        opened.await.expect("the transaction must open");
        // Another task's read is an unrelated read: served, and seeing committed state only.
        let elsewhere = tokio::spawn({
            let conn = conn.clone();
            async move { conn.query("SELECT id FROM reader_probe", ()).await }
        })
        .await
        .expect("the other task must read")
        .expect("the unrelated read must be served");
        assert!(
            elsewhere.is_empty(),
            "an unrelated read sees committed state, never the transaction's own write"
        );
        release.send(()).expect("the holder is still listening");
        let (own, refusal) = holder_task.await.expect("the holder must finish");
        assert_eq!(
            own, 1,
            "the transaction must read its own uncommitted write"
        );
        assert!(
            refusal.contains("must be served by the transaction itself"),
            "got: {refusal}"
        );
        assert_eq!(
            conn.query("SELECT id FROM reader_probe", ())
                .await
                .expect("read after the commit")
                .len(),
            1
        );
    }

    /// Reading positions, settled by measurement on the engine we ship.
    ///
    /// The engine's source keeps a handful of frame-valued read marks (four for readers), which
    /// reads like a ceiling of four readers pinned at *different* frames. The measurement
    /// disagrees: twenty-four read transactions, each holding a live, only-partly-stepped read of a
    /// table written to again before the next one opened its snapshot, are all admitted at once —
    /// the engine hands a reader the highest read mark at or below its snapshot rather than
    /// refusing it, so a position is shared between readers.
    ///
    /// So a reader of ours cannot be denied a position at [`READER_CONNECTIONS`] (nor at many
    /// times that), which makes the count safe to fix. Were the engine ever to deny one, it
    /// would arrive as that one read's own engine error after the engine's own retry.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn readers_at_distinct_frames_are_all_admitted() {
        const PROBE_READERS: usize = 24;
        let (_tmp, conn) = open_reader_store().await;
        conn.execute_batch("CREATE TABLE reader_probe (id INTEGER)")
            .await
            .expect("create the probe table");
        // Each entry keeps its reader connection and the statement it is in the middle of: it is
        // the unfinished statement that holds the position.
        let mut held = Vec::new();
        for id in 0..i64::try_from(PROBE_READERS).expect("the probe count fits an i64") {
            // A frame of its own per reader: this one is committed before the next reader opens its
            // snapshot.
            conn.execute("INSERT INTO reader_probe VALUES (?1)", params![id])
                .await
                .expect("write a frame");
            let reader = crate::util::with_block_in_place(|| conn.readers.db.connect())
                .expect("connect a probe reader");
            // LIMIT 1: the first row comes back with the read still open, so no reader here has
            // finished reading while the next one starts.
            let mut rows = reader
                .query("SELECT id FROM reader_probe ORDER BY id LIMIT 1", ())
                .expect("a reader at a distinct frame must be admitted");
            assert!(
                rows.next().await.expect("step the probe read").is_some(),
                "the probe read must produce a row"
            );
            held.push((reader, rows));
        }
        assert_eq!(held.len(), PROBE_READERS);
        // And they are holding positions, not merely returning: a compaction cannot run while an
        // unfinished read is pinned.
        assert!(
            conn.checkpoint_ungated().await.is_err(),
            "the held readings must pin positions — enough of them to block a compaction"
        );
    }

    /// A compacting (TRUNCATE) checkpoint blocked by a reader's reading position must not come back
    /// as a success: the engine answers with the same wordless row it uses for a pager failure
    /// (`busy`, no frame counts), and the parse refusing that row keeps a blocked attempt out of
    /// the completed arm. The captured reason then tells it from a real failure, so the round
    /// retries instead — a deferral, not a state failure, the journal staying unfolded until a
    /// later attempt.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_checkpoint_blocked_by_a_reader_is_a_deferral() {
        let (_tmp, conn) = open_reader_store().await;
        conn.execute_batch("CREATE TABLE reader_probe (id INTEGER)")
            .await
            .expect("create the probe table");
        for id in 0..8i64 {
            conn.execute("INSERT INTO reader_probe VALUES (?1)", params![id])
                .await
                .expect("write a frame");
        }
        // A reader whose statement is in flight holds its reading position for as long as it runs —
        // that is what blocks the compaction.
        let reader = crate::util::with_block_in_place(|| conn.readers.db.connect())
            .expect("connect a held reader");
        let held = tokio::spawn(async move {
            let mut rows = reader.query(
                "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c \
                     WHERE x < 120000) SELECT count(*) FROM c, reader_probe",
                (),
            )?;
            while rows.next().await?.is_some() {}
            Ok::<_, turso::Error>(())
        });
        tokio::time::sleep(Duration::from_millis(50)).await;
        let blocked = conn.checkpoint_ungated().await;
        assert!(
            blocked.is_err(),
            "a compaction blocked by a reading position must not look like a completed one: {blocked:?}"
        );
        held.await
            .expect("the held read must finish")
            .expect("the held read must succeed");
        // The deferral is over: the next attempt folds the journal.
        let retried = conn
            .checkpoint_ungated()
            .await
            .expect("the compaction must go through once the reader is done");
        assert!(retried.is_complete());
    }

    /// The runtime search-index repair never runs beside live readers: with a reader still out the
    /// readers cannot be brought to rest, so the repair defers to a later round instead of
    /// rebuilding under it — and the store keeps serving (the pool goes back in service, the held
    /// reader returned like a read's).
    #[tokio::test]
    async fn the_runtime_repair_defers_while_a_reader_is_still_out() {
        let (_tmp, conn) = open_reader_store().await;
        conn.readers.shorten_idle_wait(Duration::from_millis(100));
        // A reader out of the pool is what a read in flight leaves behind.
        let held = conn
            .readers
            .lease()
            .await
            .expect("the store's readers to exist");
        assert!(
            matches!(
                repair_ticket_title_fts_runtime(&conn).await,
                TicketTitleFtsRuntimeRepair::Deferred(_)
            ),
            "a repair that cannot reach a quiet store must defer, not run against a reader"
        );
        held.run("SELECT 1", |conn| {
            Box::pin(async move { Connection::query_impl(conn, "SELECT 1", ()).await })
        })
        .await
        .expect("the held reader serves the read it was held for");
        assert_eq!(
            conn.query("SELECT 1", ())
                .await
                .expect("reads are served after a deferred repair")
                .len(),
            1
        );
    }

    /// The open-time index work holds the readers off itself, instead of resting on the order in
    /// which a store is opened: with a reader still out, the tokenizer migration leaves the index
    /// alone and the open goes on. The migration is made to want to run (the tokenizer given is not
    /// the one the stored DDL carries) and its DDL names a different index, so an attempt is
    /// visible as that index appearing.
    #[tokio::test]
    async fn the_tokenizer_migration_leaves_the_index_alone_while_a_reader_is_out() {
        const PROBE_INDEX: &str = "idx_tokenizer_migration_probe";
        const PROBE_DDL: &str = "CREATE INDEX IF NOT EXISTS idx_tokenizer_migration_probe \
                                 ON tickets USING fts (title)";
        let (_tmp, conn) = open_reader_store().await;
        conn.readers.shorten_idle_wait(Duration::from_millis(100));
        ensure_fts_index(
            &conn,
            TICKETS_FTS_INDEX_NAME,
            "ngram",
            TICKETS_FTS_INDEX_DDL,
        )
        .await
        .expect("the store's ticket-title index");
        assert!(
            index_named(&conn, TICKETS_FTS_INDEX_NAME).await,
            "the store opens with its ticket-title index"
        );
        let held = conn
            .readers
            .lease()
            .await
            .expect("the store's readers to exist");

        ensure_fts_index(
            &conn,
            TICKETS_FTS_INDEX_NAME,
            "another tokenizer",
            PROBE_DDL,
        )
        .await
        .expect("the store still opens: the migration is skipped, not attempted");
        assert!(
            !index_named(&conn, PROBE_INDEX).await,
            "the migration must not run while a reader is out"
        );
        assert!(
            index_named(&conn, TICKETS_FTS_INDEX_NAME).await,
            "the index it would have dropped must still be there"
        );

        // The reader goes back, so the next open (this call) does the work.
        held.run("SELECT 1", |conn| {
            Box::pin(async move { Connection::query_impl(conn, "SELECT 1", ()).await })
        })
        .await
        .expect("the held reader serves the read it was held for");
        ensure_fts_index(
            &conn,
            TICKETS_FTS_INDEX_NAME,
            "another tokenizer",
            PROBE_DDL,
        )
        .await
        .expect("with the readers idle the migration runs");
        assert!(
            index_named(&conn, PROBE_INDEX).await,
            "with no reader out the migration is what runs"
        );
    }

    async fn index_named(conn: &Connection, name: &str) -> bool {
        conn.query_row(
            "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?1",
            params![name.to_string()],
            |row| row.get::<i64>(0),
        )
        .await
        .expect("count the index")
            > 0
    }

    /// A read whose caller has already given up finishes by itself, on its own connection: the
    /// caller's limit ends the caller's wait, and the statement is bounded by the connection's own
    /// per-statement limit rather than by the caller — so what it still holds cannot stop the next
    /// read or change. Multi-threaded on purpose: a read heavy enough to outlive its caller runs
    /// its steps in one poll, which on the current-thread runtime would starve the caller's own
    /// timer.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn an_abandoned_read_does_not_hold_up_the_store() {
        let (_tmp, conn) = open_reader_store().await;
        conn.execute_batch("CREATE TABLE reader_probe (id INTEGER)")
            .await
            .expect("create the probe table");
        conn.execute("INSERT INTO reader_probe VALUES (1)", ())
            .await
            .expect("write");
        // A read heavy enough that the caller's limit fires while it is running.
        let abandoned = tokio::time::timeout(
            Duration::from_millis(1),
            conn.query(
                "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 120000) \
                 SELECT count(*) FROM c, reader_probe",
                (),
            ),
        )
        .await;
        assert!(
            abandoned.is_err(),
            "the caller's own limit must end the caller's wait"
        );
        // The store keeps serving: the next read and the next change are both served while the
        // abandoned read is still in flight.
        assert_eq!(
            conn.query("SELECT count(*) FROM reader_probe", ())
                .await
                .expect("the next read must be served")
                .len(),
            1
        );
        conn.execute("INSERT INTO reader_probe VALUES (2)", ())
            .await
            .expect("the next change must be served");
    }

    /// Synthesize overflow-aliasing corruption on a closed store: patch one index leaf cell's
    /// overflow pointer to another cell's overflow page so two index entries share an overflow
    /// chain (turso's "Page N referenced multiple times"). Cells are located by their value prefix
    /// preceded by the record header `[hdr][text serial][rowid serial]` — the 2007-byte text serial
    /// is `[0x9f, 0x3b]`, and turso spills index payloads at the min threshold
    /// (`((usable-12)*32/255)-23` = 489 bytes for a 4096 page), so the 4-byte overflow pointer sits
    /// `local - 4` bytes after the value prefix.
    fn synthesize_overflow_aliasing(db_path: &Path) -> u32 {
        let file = std::fs::read(db_path).unwrap();
        let page_size = u16::from_be_bytes([file[16], file[17]]) as usize;
        let local = ((page_size - 12) * 32 / 255) - 23;
        let find = |file: &[u8], prefix: &[u8], rowid_serial: u8| -> (usize, u32) {
            for i in 0..file.len().saturating_sub(prefix.len() + 12) {
                // The index record header is [hdr=0x04][text serial 0x9f 0x3b][rowid serial] — the
                // table record's header differs, so the 4-byte pattern pins the index cell (leaf or
                // interior separator, both use the same record layout).
                if &file[i..i + prefix.len()] == prefix
                    && file[i - 4..i] == [0x04, 0x9f, 0x3b, rowid_serial]
                {
                    let ptr =
                        u32::from_be_bytes(file[i + local - 4..i + local].try_into().unwrap());
                    return (i, ptr);
                }
            }
            panic!(
                "index cell for {:?} not found",
                String::from_utf8_lossy(prefix)
            );
        };
        let (_, shared) = find(&file, b"v04000-", 0x02); // rowid 4001 → 16-bit serial
        let (patch_at, _) = find(&file, b"v00000-", 0x09); // rowid 1 → constant serial 9
        let mut file = file;
        file[patch_at + local - 4..patch_at + local].copy_from_slice(&shared.to_be_bytes());
        std::fs::write(db_path, &file).unwrap();
        shared
    }

    /// Build a store whose index carries overflow pages (long values), then checkpoint through a
    /// fresh connection (the writer's own checkpoint does not flush its last frames) so the main
    /// file holds every page the surgery will patch.
    async fn build_aliasing_candidate(
        db_path: &Path,
        schema: &str,
        extra_row: Option<(&str, i64)>,
    ) {
        {
            let conn = open_with_schema(db_path, schema).await.unwrap();
            for i in 0..5000i32 {
                let mut big = format!("v{i:05}-");
                big.push_str(&"q".repeat(2000));
                conn.execute(
                    "INSERT INTO t (v, n) VALUES (?1, 1);",
                    turso::params![big.clone()],
                )
                .await
                .unwrap();
            }
            if let Some((v, n)) = extra_row {
                conn.execute("PRAGMA ignore_check_constraints = ON;", ())
                    .await
                    .unwrap();
                conn.execute(
                    "INSERT INTO t (v, n) VALUES (?1, ?2);",
                    turso::params![v, n],
                )
                .await
                .unwrap();
                conn.execute("PRAGMA ignore_check_constraints = OFF;", ())
                    .await
                    .unwrap();
            }
            drop(conn);
        }
        {
            let conn = Connection::open(db_path).await.unwrap();
            conn.checkpoint_ungated().await.unwrap();
            drop(conn);
        }
    }

    /// The rebuild works on the FTS-bearing store shape (board's `CREATE INDEX ... USING fts`):
    /// turso's protected `__turso_internal_fts_dir_*` backing tables are excluded from the copy
    /// and verification, the DDL replay rebuilds the FTS index, and the fresh store's
    /// quick_check masks the known FTS count-mismatch false positive. The FTS index lives on a
    /// separate short-value table (real titles), not the overflow-aliased column.
    ///
    /// `#[ignore]` by default: real page surgery on a multi-MB fixture (~4 s). Run explicitly:
    /// `cargo test overflow_aliasing_rebuild_preserves_fts_store -- --ignored --nocapture`
    #[ignore = "performs real overflow-page DB surgery on a multi-MB fixture (~4 s); runs only when explicitly invoked"]
    #[tokio::test]
    async fn overflow_aliasing_rebuild_preserves_fts_store() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        let db_path = store_db_path(root, "board");
        std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
        let schema = "CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, v TEXT NOT NULL, \
                      n INTEGER NOT NULL DEFAULT 1); \
                      CREATE INDEX IF NOT EXISTS idx_t_v ON t(v); \
                      CREATE TABLE IF NOT EXISTS ft (title TEXT NOT NULL); \
                      CREATE INDEX IF NOT EXISTS idx_ft_fts ON ft USING fts (title) \
                      WITH (tokenizer = 'ngram');";
        build_aliasing_candidate(&db_path, schema, None).await;
        // FTS content (the count-mismatch false positive only appears once the index has rows),
        // checkpointed into the main file before the page surgery.
        {
            let conn = open_with_schema(&db_path, schema).await.unwrap();
            for i in 0..5 {
                conn.execute(
                    "INSERT INTO ft (title) VALUES (?1);",
                    turso::params![format!("ticket title {i}")],
                )
                .await
                .unwrap();
            }
            drop(conn);
        }
        {
            let conn = Connection::open(&db_path).await.unwrap();
            conn.checkpoint_ungated().await.unwrap();
            drop(conn);
        }
        let shared = synthesize_overflow_aliasing(&db_path);
        assert!(shared > 0, "surgery must reference a real overflow page");

        let conn = open_and_repair_for_test(root, &db_path, "board", schema)
            .await
            .expect("overflow-aliasing repair must succeed on an FTS store");
        conn.quick_check()
            .await
            .expect("rebuilt store must pass quick_check");
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM t", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(count, 5000, "all rows must survive the rebuild");
        let idx: i64 = conn
            .query_row("SELECT COUNT(*) FROM t INDEXED BY idx_t_v", (), |r| {
                r.get::<i64>(0)
            })
            .await
            .unwrap();
        assert_eq!(idx, 5000, "rebuilt index must be valid and complete");
        let ft: i64 = conn
            .query_row("SELECT COUNT(*) FROM ft", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(ft, 5, "FTS table data must survive the rebuild");
        // The rebuilt FTS dir must answer MATCH queries — quick_check does not pin it (the engine
        // skips the cardinality comparison for its own backing-btree indexes), so MATCH is the only
        // check that pins the rebuild.
        let matched: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM ft WHERE title MATCH 'title'",
                (),
                |r| r.get::<i64>(0),
            )
            .await
            .unwrap();
        assert_eq!(matched, 5, "rebuilt FTS index must answer MATCH queries");
        let quarantined = std::fs::read_dir(db_path.parent().unwrap())
            .unwrap()
            .filter_map(std::result::Result::ok)
            .any(|e| e.file_name().to_string_lossy().contains("quarantine-"));
        assert!(
            quarantined,
            "original family must be quarantined (forensic record)"
        );
        conn.execute("INSERT INTO t (v, n) VALUES ('post-rebuild', 1);", ())
            .await
            .unwrap();
        conn.quick_check()
            .await
            .expect("rebuilt store must stay clean after a write");
    }

    /// A constraint violation during the data copy is a data-integrity finding, not corruption: the
    /// rebuild aborts report-only (no silent recreate, no quarantine) and the original store — with
    /// its readable data — is preserved for operator review.
    ///
    /// `#[ignore]` by default: real page surgery on a multi-MB fixture (~4 s). Run explicitly:
    /// `cargo test overflow_aliasing_rebuild_constraint_finding_aborts -- --ignored`
    #[ignore = "performs real overflow-page DB surgery on a multi-MB fixture (~4 s); runs only when explicitly invoked"]
    #[tokio::test]
    async fn overflow_aliasing_rebuild_constraint_finding_aborts() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        let db_path = store_db_path(root, "board");
        std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
        let schema = "CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, v TEXT NOT NULL, \
                      n INTEGER NOT NULL CHECK (n < 50)); \
                      CREATE INDEX IF NOT EXISTS idx_t_v ON t(v);";
        // Row with n=99 violates the CHECK (written with constraints ignored).
        build_aliasing_candidate(&db_path, schema, Some(("v09999x", 99))).await;
        synthesize_overflow_aliasing(&db_path);

        let conn = open_and_repair_for_test(root, &db_path, "board", schema)
            .await
            .expect("aborted rebuild must still open the store (report-only)");
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM t", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(
            count, 5001,
            "original data must be preserved, not recreated"
        );
        assert_not_quarantined(
            db_path.parent().unwrap(),
            "a constraint finding (the rebuild abort)",
        );
    }

    /// The rebuild works on the real AUTOINCREMENT store shape (logs, chat_history, sessions):
    /// turso's protected `__turso_internal_seq_*` backing tables are excluded from the copy and
    /// verification, `sqlite_sequence` is carried over, and the fresh watermark advances past the
    /// copied max ids. Rows 4001..5000 are deleted before the repair (retention) so the old
    /// watermark (5000) exceeds the surviving max id (4000) — the only shape where the carry-over
    /// matters: without it the next auto-id would re-issue 4001. `#[ignore]` by default: real page
    /// surgery on a multi-MB fixture (~4 s). Run explicitly: `cargo test
    /// overflow_aliasing_rebuild_preserves_autoincrement_store -- --ignored --nocapture`
    #[ignore = "performs real overflow-page DB surgery on a multi-MB fixture (~4 s); runs only when explicitly invoked"]
    #[tokio::test]
    async fn overflow_aliasing_rebuild_preserves_autoincrement_store() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        let db_path = store_db_path(root, "board");
        std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
        let schema = "CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY AUTOINCREMENT, \
                      v TEXT NOT NULL, n INTEGER NOT NULL DEFAULT 1); \
                      CREATE INDEX IF NOT EXISTS idx_t_v ON t(v);";
        build_aliasing_candidate(&db_path, schema, None).await;
        let shared = synthesize_overflow_aliasing(&db_path);
        assert!(shared > 0, "surgery must reference a real overflow page");
        {
            let conn = Connection::open(&db_path).await.unwrap();
            conn.execute("DELETE FROM t WHERE id > 4000", ())
                .await
                .unwrap();
            drop(conn);
        }

        let conn = open_and_repair_for_test(root, &db_path, "board", schema)
            .await
            .expect("overflow-aliasing repair must succeed on an AUTOINCREMENT store");
        conn.quick_check()
            .await
            .expect("rebuilt store must pass quick_check");
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM t", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(count, 4000, "all surviving rows must be preserved");
        let idx: i64 = conn
            .query_row("SELECT COUNT(*) FROM t INDEXED BY idx_t_v", (), |r| {
                r.get::<i64>(0)
            })
            .await
            .unwrap();
        assert_eq!(idx, 4000, "rebuilt index must be valid and complete");
        conn.execute("INSERT INTO t (v, n) VALUES ('auto-next', 1);", ())
            .await
            .unwrap();
        let max_id: i64 = conn
            .query_row("SELECT MAX(id) FROM t", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(
            max_id, 5001,
            "AUTOINCREMENT must advance past the old watermark, never re-issue ids"
        );
        let seq: i64 = conn
            .query_row(
                "SELECT seq FROM sqlite_sequence WHERE name = 't'",
                (),
                |r| r.get::<i64>(0),
            )
            .await
            .unwrap();
        assert_eq!(
            seq, 5001,
            "sqlite_sequence watermark must be carried over and advanced"
        );
        conn.quick_check()
            .await
            .expect("rebuilt store must stay clean after a write");
        let quarantined = std::fs::read_dir(db_path.parent().unwrap())
            .unwrap()
            .filter_map(std::result::Result::ok)
            .any(|e| e.file_name().to_string_lossy().contains("quarantine-"));
        assert!(
            quarantined,
            "original family must be quarantined (forensic record)"
        );
    }

    #[test]
    fn open_time_lock_error_predicate() {
        let lock = |msg: &str| turso::Error::Error(msg.to_string());
        // The Unix open-time fcntl `F_SETLK` WouldBlock folded into the generic Error variant by
        // turso_core's catch-all From impl — the message observed on this host while another
        // process held a store.
        assert!(is_open_time_lock_error(&lock(
            "Locking error: Failed locking file '/x/logs.db-wal'. File is locked by another process"
        )));
        // The same lock's wording on the engine's async-handle IO paths.
        assert!(is_open_time_lock_error(&lock(
            "Locking error: Failed locking file. File is locked by another process"
        )));
        // The shared-WAL coordination file variant of the same open-time lock.
        assert!(is_open_time_lock_error(&lock(
            "Locking error: Failed locking shared WAL coordination file. File is locked by another process"
        )));
        // Windows reports `ERROR_LOCK_VIOLATION` (33), which std does not map to `WouldBlock`, so
        // the engine echoes the OS text plus the code — the code is what carries the contention
        // there.
        assert!(is_open_time_lock_error(&lock(
            "Locking error: Failed locking file, The process cannot access the file because another process has locked a portion of the file. (os error 33)"
        )));
        // A statement-level busy error is NOT the open-time lock.
        assert!(!is_open_time_lock_error(&turso::Error::Busy(
            "database is locked".into()
        )));
        // A table-level lock surfaced as a generic Error is NOT the open-time lock.
        assert!(!is_open_time_lock_error(&lock(
            "Runtime error: database table is locked"
        )));
        // The engine's other `LockingError` uses do not open a lock.
        assert!(!is_open_time_lock_error(&lock(
            "Locking error: mmap shared WAL coordination file failed: boom (offset=0)"
        )));
        assert!(!is_open_time_lock_error(&lock(
            "Locking error: Failed to release file lock: not locked"
        )));
        // A lock-open failure with no contention in it must not be retried, nor reported as
        // "another process holds the store".
        assert!(!is_open_time_lock_error(&lock(
            "Locking error: Failed locking file '/x/core.db', Too many open files (os error 24)"
        )));
        // An I/O completion error is not the open-time lock: it carries the kind of a failed
        // read/write, never the engine's `lock_file` step.
        assert!(!is_open_time_lock_error(&turso::Error::IoError(
            std::io::ErrorKind::WouldBlock,
            "read"
        )));
        // Corruption and I/O-class messages must not be treated as this race.
        assert!(!is_open_time_lock_error(&lock(
            "Database file is corrupted"
        )));
    }

    /// The two actionable-signal families (lock contention, resource exhaustion) must propagate
    /// instead of being reported as a repair finding.
    #[test]
    fn lock_and_resource_signals_are_actionable() {
        for msg in [
            "Locking error: File is locked by another process",
            "Runtime error: database table is locked",
            "Database is busy",
            "no space left on device",
        ] {
            let err = anyhow::Error::new(turso::Error::Error(msg.to_string()));
            assert!(
                is_actionable_signal(&err),
                "an external condition must propagate, not recreate: {msg}"
            );
        }
        let corrupt = anyhow::Error::new(turso::Error::Error("Invalid page type".to_string()));
        assert!(
            !is_actionable_signal(&corrupt),
            "corruption must not classify as an actionable signal"
        );
    }

    /// The forensic snapshot is engine-produced, so it must be a complete, independently queryable
    /// copy — and taking it must leave the source store usable (nothing here opens the source's
    /// main file).
    #[tokio::test]
    async fn engine_snapshot_is_queryable_and_leaves_the_source_usable() {
        let tmp = tempfile::TempDir::new().unwrap();
        let db_path = tmp.path().join("core.db");
        let conn = open_with_schema(&db_path, "CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);")
            .await
            .unwrap();
        conn.execute("INSERT INTO t (v) VALUES ('kept')", ())
            .await
            .unwrap();

        let snap = snapshot_store_via_engine(&conn, &db_path).await.unwrap();
        assert!(
            snap.exists(),
            "the snapshot must exist at {}",
            snap.display()
        );
        // `debug::classify_family` expects a pre-reindex family to be db + wal, so the forensic
        // listing depends on the engine leaving this sibling beside the copy. Pin it here, where
        // the snapshot is produced: an engine bump that drops it must move that expectation with
        // it.
        let wal = std::path::PathBuf::from(format!("{}-wal", snap.display()));
        assert!(
            wal.exists(),
            "VACUUM INTO must leave {} beside the snapshot",
            wal.display()
        );

        let reopened = open_with_schema(&snap, "").await.unwrap();
        let v: String = reopened
            .query_row("SELECT v FROM t WHERE id = 1", (), |r| r.get(0))
            .await
            .unwrap();
        assert_eq!(v, "kept", "the snapshot must carry the committed row");
        drop(reopened);

        let rows: i64 = conn
            .query_row("SELECT COUNT(*) FROM t", (), |r| r.get(0))
            .await
            .unwrap();
        assert_eq!(rows, 1, "the source store must stay queryable");
    }

    #[tokio::test]
    async fn open_lock_retry_succeeds_after_transient_lock() {
        let calls = AtomicUsize::new(0);
        let result = with_open_lock_retry(3, Duration::from_millis(1), || {
            let n = calls.fetch_add(1, Ordering::SeqCst);
            async move {
                if n < 2 {
                    Err(turso::Error::Error(
                        "Locking error: Failed locking file '/x/logs.db-wal'. File is locked by another process".to_string(),
                    ))
                } else {
                    Ok("opened")
                }
            }
        })
        .await;
        assert!(
            result.is_ok(),
            "open must succeed after the transient lock clears"
        );
        assert_eq!(
            calls.load(Ordering::SeqCst),
            3,
            "closure must be called twice before success"
        );
    }

    #[tokio::test]
    async fn open_lock_retry_exhausts_and_preserves_error() {
        let calls = AtomicUsize::new(0);
        let err = with_open_lock_retry(2, Duration::from_millis(1), || {
            calls.fetch_add(1, Ordering::SeqCst);
            async {
                Err::<(), turso::Error>(turso::Error::Error(
                    "Locking error: Failed locking file '/x/logs.db-wal'. File is locked by another process".to_string(),
                ))
            }
        })
        .await
        .expect_err("a persistent open-time lock must eventually surface");
        assert_eq!(
            calls.load(Ordering::SeqCst),
            3,
            "max total tries must be attempts + 1"
        );
        assert!(
            is_open_time_lock_error(&err),
            "the original lock error must be preserved"
        );
    }

    #[tokio::test]
    async fn open_lock_no_retry_on_non_lock_error() {
        let calls = AtomicUsize::new(0);
        let err = with_open_lock_retry(2, Duration::from_millis(1), || {
            calls.fetch_add(1, Ordering::SeqCst);
            async { Err::<(), turso::Error>(turso::Error::Error("Disk I/O error".to_string())) }
        })
        .await
        .expect_err("a non-lock open failure must not be retried");
        assert_eq!(
            calls.load(Ordering::SeqCst),
            1,
            "non-lock errors must not trigger retries"
        );
        assert!(
            matches!(&err, turso::Error::Error(msg) if msg == "Disk I/O error"),
            "the original non-lock error must be returned"
        );
    }

    /// `is_fts_index` recognizes the turso `USING fts` index-method clause and rejects plain btree
    /// indexes and unknown names.
    #[tokio::test]
    async fn is_fts_index_classifies_index_method() {
        let tmp = tempfile::TempDir::new().unwrap();
        let db_path = tmp.path().join("test.db");
        let conn = open_with_schema(
            &db_path,
            "CREATE TABLE IF NOT EXISTS ft (title TEXT NOT NULL); \
             CREATE INDEX IF NOT EXISTS idx_ft_fts ON ft USING fts (title) \
             WITH (tokenizer = 'ngram'); \
             CREATE TABLE IF NOT EXISTS t (x INTEGER); \
             CREATE INDEX IF NOT EXISTS idx_plain ON t(x);",
        )
        .await
        .unwrap();
        assert!(is_fts_index(&conn, "idx_ft_fts").await);
        assert!(!is_fts_index(&conn, "idx_plain").await);
        assert!(!is_fts_index(&conn, "does_not_exist").await);
    }

    /// The post-detection repair rebuilds the FTS index without touching ticket
    /// rows, verifies the rebuilt index, and leaves a healthy, idempotent store.
    #[tokio::test]
    async fn rebuild_ticket_title_fts_repairs_and_verifies() {
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = open_consolidated_store(tmp.path()).await.unwrap();
        insert_fts_ticket(&conn, "t-1", "Important bug fix one").await;
        insert_fts_ticket(&conn, "t-2", "Another relevant thing").await;

        let before: i64 = conn
            .query_row("SELECT COUNT(*) FROM tickets", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(before, 2);

        rebuild_ticket_title_fts(
            &conn,
            "idx_tickets_title_fts",
            "CREATE INDEX IF NOT EXISTS idx_tickets_title_fts ON tickets \
             USING fts (title) WITH (tokenizer = 'ngram')",
        )
        .await;

        let after = repair_ticket_title_fts_runtime(&conn).await;
        assert!(
            matches!(after, TicketTitleFtsRuntimeRepair::Healthy),
            "rebuilt FTS index must be healthy: {after:?}"
        );

        let sanitized = sanitize_fts_query("Important bug fix one");
        let matched: String = conn
            .query_row(
                "SELECT id FROM tickets WHERE title MATCH ?1 LIMIT 1",
                params![sanitized],
                |r| r.get::<String>(0),
            )
            .await
            .unwrap();
        assert_eq!(matched, "t-1");

        let after: i64 = conn
            .query_row("SELECT COUNT(*) FROM tickets", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(after, 2, "ticket rows must be untouched by the FTS rebuild");

        let present = conn
            .query_optional(
                "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?1",
                params!["idx_tickets_title_fts".to_string()],
                |_| Ok::<_, ::turso::Error>(()),
            )
            .await
            .unwrap();
        assert!(present.is_some());
    }

    /// End-to-end: a store whose title FTS index no longer serves MATCH is detected by the repair
    /// and actually rebuilt — FTS-shaped again from the known DDL, MATCH works, ticket rows
    /// survive, and a re-run is clean. Real pager-level corruption of an FTS-shaped index cannot be
    /// fabricated deterministically; a same-named plain btree index is the closest deterministic
    /// stand-in (a real boot would have ensure_fts_index fix this shape first — the repair path is
    /// exercised directly here).
    #[tokio::test]
    async fn broken_title_fts_store_is_detected_and_rebuilt_end_to_end() {
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = open_consolidated_store(tmp.path()).await.unwrap();
        insert_fts_ticket(&conn, "t-1", "Important bug fix one").await;

        conn.execute_batch(&fts_corruption_ddl()).await.unwrap();
        assert!(!is_fts_index(&conn, "idx_tickets_title_fts").await);

        assert!(matches!(
            repair_ticket_title_fts_runtime(&conn).await,
            TicketTitleFtsRuntimeRepair::Rebuilt(_)
        ));

        assert!(is_fts_index(&conn, "idx_tickets_title_fts").await);
        let matched: String = conn
            .query_row(
                "SELECT id FROM tickets WHERE title MATCH ?1 LIMIT 1",
                params![sanitize_fts_query("Important bug fix one")],
                |r| r.get::<String>(0),
            )
            .await
            .unwrap();
        assert_eq!(matched, "t-1");

        assert!(matches!(
            repair_ticket_title_fts_runtime(&conn).await,
            TicketTitleFtsRuntimeRepair::Healthy
        ));
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM tickets", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(count, 1);
    }

    /// The functional MATCH probe succeeds on a healthy store both with an empty index and with
    /// populated content.
    #[tokio::test]
    async fn title_fts_match_probe_ok_on_healthy_store() {
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = open_consolidated_store(tmp.path()).await.unwrap();
        title_fts_match_probe(&conn)
            .await
            .expect("probe must pass on an empty FTS index");

        insert_fts_ticket(&conn, "t-1", "Important bug fix").await;
        title_fts_match_probe(&conn)
            .await
            .expect("probe must pass on a healthy populated FTS index");
    }

    /// Runtime entry point returns `NotApplicable` for a store without the
    /// ticket-title FTS index and `Healthy` for a healthy index with content.
    #[tokio::test]
    async fn runtime_repair_classifies_missing_and_healthy_index() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plain_path = tmp.path().join("plain.db");
        let plain = open_with_schema(&plain_path, "CREATE TABLE plain (id INTEGER PRIMARY KEY);")
            .await
            .unwrap();
        assert!(matches!(
            repair_ticket_title_fts_runtime(&plain).await,
            TicketTitleFtsRuntimeRepair::NotApplicable
        ));

        let conn = open_consolidated_store(tmp.path()).await.unwrap();
        insert_fts_ticket(&conn, "t-1", "Important bug fix").await;
        assert!(matches!(
            repair_ticket_title_fts_runtime(&conn).await,
            TicketTitleFtsRuntimeRepair::Healthy
        ));
    }

    /// The debug surface hands stored text back verbatim to whoever asked, so a control token in a cell
    /// — a refusal body recorded before the mask existed — is masked on READ. Rewriting the live store
    /// is forbidden, so this is the only cure for the records already there.
    #[test]
    fn format_cell_masks_model_control_tokens_in_text_cells() {
        let placeholder = crate::util::control_token::PLACEHOLDER;
        assert_eq!(
            format_cell(&Value::Text("a body with <|image|> inside".to_string())),
            format!("a body with {placeholder} inside")
        );
        assert_eq!(format_cell(&Value::Integer(7)), "7");
        assert_eq!(format_cell(&Value::Null), "");
        // A marker shape is not a token: the debug surface still prints media markers verbatim.
        assert_eq!(
            format_cell(&Value::Text("[IMAGE:/tmp/a.png]".to_string())),
            "[IMAGE:/tmp/a.png]"
        );
    }
}