mahbot 0.9.0

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
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
//! The store layer: the two physical databases this product keeps, and the
//! single connection discipline every caller shares.
//!
//! The consolidated domain store (`core.db`: board, sessions, workspaces,
//! users, config, chat history, alarms, custom roles, Telegram intake) and the
//! logs store (`logs.db`) are the only files. This module owns the connection
//! surface (`Connection`, `TxGuard`, `ReaderPool`, `Maintenance`), the
//! transaction helpers, the timestamp and column conventions, the store-facing
//! pragmas, and the one display rule every pipe table prints its cells by
//! ([`format_cell`]). The schema lives in `migrations`, the change stream in
//! `cdc`, and the store-lock, checkpoint and read-only debug rules in their own
//! submodules.
//!
//! 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;

// ── Timestamp helper ────────────────────────────────────────────────

/// Current UTC timestamp in RFC 3339 format for database columns.
#[must_use]
pub fn now() -> String {
    Utc::now().to_rfc3339()
}

/// Parse an RFC 3339 timestamp string into a UTC DateTime.
///
/// All database timestamps are generated by [`now`] and are stored as RFC 3339
/// strings with a timezone offset (e.g., `2026-07-02T14:20:40+00:00`). This
/// function normalises them to [`DateTime<Utc>`] regardless of the offset
/// embedded in the string.
///
/// # Errors
///
/// Returns [`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 experimental Turso database features that must be enabled
/// consistently by the running instance and the debug CLI.
///
/// These correspond to the `with_*()` methods / public fields of
/// [`turso::core::DatabaseOpts`] — see [`experimental_database_opts`] for
/// the canonical construction.
///
/// This constant is the **single source** for which features are active, and it
/// is read by both layers of the product: the connection layer
/// ([`crate::db::store`]) turns it into the comma-separated feature string the
/// SDK takes when the instance opens a store, and
/// [`experimental_database_opts`] is the typed form the read-only debug path
/// opens with. The `db::store::tests::feature_string_matches_the_debug_paths_typed_opts`
/// test asserts the two are equal — it also catches a typo, because the SDK
/// silently ignores a feature name it does not know.
///
/// Adding a feature is therefore a two-step process: add the `with_*()` call in
/// [`experimental_database_opts`], and add the feature name string here — a flag
/// without its name, or a name without its flag, fails the test above.
///
/// # API naming asymmetries
///
/// Enabling a feature through the typed opts and naming it in this string form
/// do not spell it the same way. Known mismatch:
///
/// | DatabaseOpts field / `with_*()` | Feature string |
/// |---|---|
/// | `enable_views` / `with_views()` | `"views"` |
///
/// Fields with no string form exist too and can only be set through the typed
/// opts, so they never belong here:
/// - `enable_autovacuum` / `with_autovacuum()`.
/// - `unsafe_testing` / `with_unsafe_testing()`.
pub(crate) const EXPERIMENTAL_FEATURES: &[&str] = &["index_method"];

/// Name (file stem) of the single consolidated domain database file that backs
/// the board, sessions, workspaces, users, config, chat_history, alarms,
/// custom_roles and telegram_intake stores.
///
/// The domain stores were historically split across separate files; they
/// now share one file (and one shared [`Connection`] — one writing connection,
/// one transaction domain, one reader pool) so that cross-store
/// integrity is enforceable with real foreign keys and phase+stage updates are
/// atomic within a single transaction domain. The logs store remains a
/// separate file ([`LOG_DB_NAME`]).
///
/// `core` distinguishes this domain database from the separate logs store and
/// reads as the canonical core-domain file (`~/.mahbot/db/core.db`).
pub(crate) const CONSOLIDATED_DB_NAME: &str = "core";

/// Logical store names consolidated into [`CONSOLIDATED_DB_NAME`].
///
/// Each name maps to the single physical [`CONSOLIDATED_DB_NAME`] file via
/// [`store_db_path`]. These are a subset of the names accepted by
/// `mahbot debug --db <name>` — the full accepted set is [`debug_db_names`]
/// ([`store_names`] plus the physical `core` file name). The logs store is
/// NOT in this list — it remains its own file.
const DOMAIN_STORE_NAMES: &[&str] = &[
    "board",
    "sessions",
    "workspaces",
    "users",
    "config",
    "chat_history",
    "alarms",
    "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`]. Each domain store struct holds a clone of this
/// connection — literally one handle, whose writing connection is the one
/// transaction domain every domain write runs in and whose reader connections
/// serve the domain reads. The logs store does NOT use this connection.
pub(crate) static DOMAIN_CONN: tokio::sync::OnceCell<Connection> =
    tokio::sync::OnceCell::const_new();

/// Return an iterator over all **physical, checkpointable** database stores.
///
/// Each item is `(name, Option<&'static Connection>)` where `None` means the
/// store has not been initialized yet.
///
/// This is the single source of truth for which **physical files** exist and
/// are checkpointed. After consolidation all the domain stores share ONE file
/// ([`CONSOLIDATED_DB_NAME`]) plus the separate logs file, so this yields
/// exactly two units. [`store_names`] returns the LOGICAL store names accepted
/// by `mahbot debug --db <name>` — a deliberately separate list, because
/// several logical names map to the same 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()
}

/// Return all canonical **logical** store names accepted by `mahbot debug --db`.
///
/// These are the names users address stores by (`board`, `sessions`, …,
/// `chat_history`) plus `logs`. Several map to the single consolidated file via
/// [`store_db_path`]. This is **not** derived from
/// [`iter_checkpoint_stores`] (which enumerates the *physical* files): the two
/// lists are intentionally separate — several logical names share one physical
/// file. They change for different reasons: adding a consolidated domain
/// store only extends [`DOMAIN_STORE_NAMES`], from which this function
/// derives; [`iter_checkpoint_stores`] changes only when a brand-new physical
/// file appears. The name→file coupling itself lives in [`store_db_path`].
///
/// Used by:
/// - `mahbot debug` — validates `--db` argument values.
///
/// # Consolidated layout
///
/// The domain stores (board, sessions, workspaces, users, config, chat_history,
/// alarms, custom_roles, telegram_intake) are consolidated into ONE physical
/// file ([`CONSOLIDATED_DB_NAME`]); only the logs store is a separate file.
/// This function returns the LOGICAL store names so `--db board`, `--db sessions`,
/// etc. resolve to the single consolidated file via [`store_db_path`].
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
}

/// All accepted database selector values for the read-only debug/query surface
/// (the CLI's `--db` argument and the Assistant `mahbot_debug` tool's `db`
/// parameter): the logical store names ([`store_names`]) plus the physical
/// consolidated file name ([`CONSOLIDATED_DB_NAME`]).
///
/// This is the single derivation of that accepted set — [`crate::db::debug`]'s
/// validator, CLI usage text, and the tool's model-facing schema all use it so
/// the three cannot drift.
pub(crate) fn debug_db_names() -> Vec<&'static str> {
    let mut names = store_names();
    names.push(CONSOLIDATED_DB_NAME);
    names
}

/// Initialize all database stores concurrently.
///
/// This is the canonical initialization path for the domain stores (board,
/// session, workspace, users, chat_history, config, alarms, custom_roles,
/// telegram_intake).
/// The `logs` store
/// is **not** included here because it must be initialized earlier via
/// [`crate::logs::init_tracing`], which requires the log store before any
/// other subsystem is ready. The stats tables (tool_calls, llm_requests)
/// live in the logs store.
///
/// # Consolidated layout
///
/// The domain stores (`DOMAIN_STORE_NAMES`) now share ONE file
/// ([`CONSOLIDATED_DB_NAME`]) and ONE shared [`Connection`] ([`DOMAIN_CONN`]) —
/// every store struct holds a clone of the same connection, so `begin_tx` on
/// any store acquires the same mutex and phase+stage updates are atomic within
/// a single transaction domain. The
/// consolidated schema + migrations are applied once via
/// [`open_consolidated_store`], and per-store post-open hooks (tickets FTS
/// index, admin-user seed) run idempotently before the cells are set.
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 alarms = crate::alarms::AlarmStore { 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 change events to the
    // GUI and the chronicle subscriber; a reopen (the data-preserving rebuild)
    // re-enables capture in open_consolidated_store (above).
    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::alarms::ALARMS, alarms, "ALARMS")?;
    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"))
}

/// Create [`turso::core::DatabaseOpts`] with all experimental features enabled.
///
/// The typed form of [`EXPERIMENTAL_FEATURES`], used by the read-only debug path
/// (which opens through the low-level `turso::core` API rather than the
/// connection layer).
///
/// Every engine experimental field is a deliberate decision here: one the engine
/// adds later defaults off, and a field turned on here is only really active if
/// its feature name is also in [`EXPERIMENTAL_FEATURES`], which is the string the
/// instance passes to the engine.
///
/// The instance runs in **default single-process mode**: there is no
/// `multiprocess_wal` coordination.
///
/// Forensic-family reads (`mahbot debug --family`, via `open_readonly` in
/// `debug.rs`) use this same opts: family snapshots are copied from live stores
/// (which are created with `index_method`), so they read with the same
/// single-process feature set.
///
/// # Adding a new feature
///
/// 1. Add the `with_*()` call here.
/// 2. Add the feature name string to [`EXPERIMENTAL_FEATURES`].
///
/// The string [`EXPERIMENTAL_FEATURES`] lists is what the engine takes; see its
/// doc for the naming asymmetries between the typed field and that string.
#[must_use]
pub(crate) fn experimental_database_opts() -> turso::core::DatabaseOpts {
    turso::core::DatabaseOpts::new().with_index_method(true)
}

/// Remove characters that cause FTS query parser errors.
///
/// Tantivy special characters that act as syntax operators in query terms.
/// Characters not listed here (`.`, `@`, `#`, `_`, `/`, `$`, `%`, `!`, `,`,
/// `?`, etc.) are safe word characters in Tantivy's query grammar and are
/// preserved to improve 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 string for Tantivy FTS, stripping syntax
/// operators that would cause parse errors.
///
/// Required because turso's FTS uses Tantivy, whose query parser treats
/// certain characters as syntax operators, causing parse errors on
/// user-generated queries. This is a Tantivy design decision, not a turso
/// version bug — upgrading turso will not eliminate this requirement.
///
/// The `ngram` tokenizer indexes character substrings, so removing syntax
/// operators from queries does not reduce search quality. Non-special
/// punctuation is preserved to improve search precision — e.g. email
/// addresses like `user@example.com`, identifiers like `my_function`, or
/// paths like `feature/x` are kept intact.
///
/// # Edge cases
///
/// * Queries starting with `/` have the leading slash stripped to prevent
///   Tantivy's lenient parser from interpreting them as regex queries.
/// * Queries consisting entirely of Tantivy special characters (e.g. `+-~`)
///   produce an empty string, allowing callers to short-circuit.
#[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(" ")
}

/// Build a comma-separated list of `?` placeholders for SQL IN-clauses.
///
/// Returns an empty string for `count == 0`. Callers MUST guard against
/// empty lists to avoid producing invalid SQL like `WHERE id IN ()`.
///
/// Note: Turso/SQLite binds `Vec<Value>` positionally regardless of whether
/// the SQL uses `?` or `?N`, so numbered placeholders (`?1, ?2, ...`) are
/// never necessary — 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.
///
/// Every **change** — and the store's own upkeep (see [`Upkeep`]) — goes through
/// the one **writing connection** whose access is serialized by the [`Mutex`]
/// below, except the periodic round's checkpoint and its integrity verification,
/// which run on the store's maintenance connection ([`Maintenance`]). Every
/// ordinary **read** is served by the store's reader connections ([`ReaderPool`])
/// and never touches that mutex, so a read no longer queues behind whatever else
/// the store is doing.
///
/// The engine is what lets one `Database` carry many connections, and it takes
/// many reads on one connection at once. It does **not** queue a second *write*
/// statement behind the first: a write statement that starts while another
/// writer is still in progress on the same connection is rejected outright
/// (surfaced at the wrapper as a busy error), because a write statement can
/// suspend for async I/O, which would make the reset/drop cleanup of such a
/// statement hard to get right. The one-at-a-time sequencing over the writing
/// connection is therefore our own queue, and it stays exactly as it is.
///
/// A dropped transaction left open on the writing connection is rolled back
/// before the connection is reused: when a [`TxGuard`] is dropped without
/// explicit commit/rollback the flag is set and the next write operation rolls
/// it back first (mirrors the upstream `turso::Connection::dangling_tx` pattern
/// at wrapper level, avoiding async in `Drop`).
///
/// # Writing-connection discipline (consolidated layout)
///
/// All the domain stores hold a **clone of one** [`Connection`], so the
/// writing connection's mutex is NOT reentrant and is never shared between
/// independent locks. A code path that holds a [`TxGuard`] (which keeps the
/// mutex locked for the transaction's lifetime) MUST use `tx.query()` /
/// `tx.execute()` / `tx.begin_tx()` for any further access to that connection.
/// That is enforced, not merely required: a read issued by the very task that
/// holds the transaction is refused on the read entry (see
/// [`Connection::run_read`]), so a cross-store read can no longer quietly miss
/// what the transaction itself has written. A read issued by any other task is
/// an unrelated read and is served by a reader connection as usual — it sees
/// committed state, which may be the state as of just before the transaction
/// commits.
#[derive(Clone, Debug)]
pub(crate) struct Connection {
    /// The writing connection — reused for every change and for the store's own
    /// upkeep reads that stay on it (see [`Upkeep`]).
    conn: Arc<tokio::sync::Mutex<store::Connection>>,
    /// Set when a TxGuard is dropped without explicit commit/rollback.
    /// Checked at the start of every write operation (execute, begin_tx).
    /// Mirrors the upstream `turso::Connection::dangling_tx` pattern but
    /// works at our wrapper level so we don't need async in Drop.
    has_dangling_tx: Arc<AtomicBool>,
    /// The task that opened the transaction currently on `conn`, cleared when it
    /// commits or rolls back. A read issued by that same task belongs to that
    /// transaction and is 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 of this store is made from — the writing
    /// connection's, the readers' and the maintenance one's ([`Maintenance`]).
    /// Never a second open of the store's file (wal_guard's lock rule).
    db: Arc<store::Database>,
    /// The store's reader connections. Handed the already-open store at open;
    /// it creates reader connections only once the store is final and a read
    /// first needs one (see [`Connection::enable_readers`]).
    readers: Arc<ReaderPool>,
}

/// Result of a read-only query: column names, row values, and whether the
/// row limit was hit (more rows exist).
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 of the value. NULL empty (nothing between the delimiters reads
/// `||`), 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 above are both visible to the model through
/// the `mahbot_debug` tool's output.
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) => 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, so the index-cardinality comparison mismatched on every
/// populated index (upstream tursodatabase/turso#7611, reported against 0.7.x,
/// still open). Re-checked on the 0.8.0 upgrade: upstream now skips that
/// comparison for its own backing-btree indexes (the skip landed in 0.8.0-pre.8
/// and is in the engine we ship), so the row is not emitted at all and this
/// mask is currently a no-op. It stays because it is exact and one-directional
/// — only this count-mismatch message is masked, other messages naming the same
/// internal index (missing/non-unique entries) signal real corruption and stay
/// reported, and the never-REINDEX-the-FTS guard below 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 the
/// extracted index name against this, not the full message prefix).
const FTS_INTERNAL_INDEX_PREFIX: &str = "__turso_internal_fts_dir_";

/// `sqlite_master` filter for user-owned objects: excludes the engine's own
/// tables (`sqlite_%`), turso's protected `__turso_internal_%`
/// (AUTOINCREMENT seq backing, FTS dir), and the engine-managed CDC tables
/// (`turso_cdc`, `turso_cdc_version`) — those reject user writes and are
/// recreated by the DDL replay. Shared by the rebuild's counts enumeration,
/// DDL replay, and the debug CLI's 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 from the migration —
/// including a turso panic mid-copy (the documented pager-OOB class) —
/// removes the temp main + `-wal`. A panic is absorbed by `open_store` as a
/// refusal, so the fully-read migrated data is discarded either way — the
/// accepted panic trade-off.
struct TempCleanup<'a>(&'a Path);
impl Drop for TempCleanup<'_> {
    fn drop(&mut self) {
        remove_rebuild_temp(self.0);
    }
}

/// True when a `quick_check`/`integrity_check` message names the internal FTS
/// backing index — either the known count-mismatch false positive or any
/// other problem row about that index (the row-level scan masks only the exact
/// count-mismatch message; this is the broader never-REINDEX-the-FTS guard).
#[must_use]
fn known_fts_dir_false_positive(message: &str) -> bool {
    message.contains(FTS_INTERNAL_INDEX_PREFIX)
}

/// Map each row in a slice through a fallible closure, collecting into a
/// `Vec<turso::Result<T>>` with per-row error conversion.
///
/// Shared by the strict and per-row mapping entry points:
/// [`Connection::query_map`], [`Connection::query_map_strict`],
/// [`Connection::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 a single-row query result into `Ok(None)` on
/// [`turso::Error::QueryReturnedNoRows`], converting other errors 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 result stream through a fallible closure, mapping
/// an empty stream to [`turso::Error::QueryReturnedNoRows`] and per-row
/// errors to `turso::Error::Error`. Shared by [`Connection::query_row_impl`]
/// and [`Connection::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()))
}

/// Collect per-row results, failing on the first per-row error.
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
/// already 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 every place a statement can run: the
/// writing connection ([`Connection::run_detached_capturing`]) and the store's
/// maintenance connection ([`Maintenance::run_statement`]), both through
/// [`spawn_detached`], and a reader ([`ReaderLease::run`]) — so the places cannot
/// drift apart in what they do with the outcome.
///
/// A panicking op propagates the ORIGINAL panic payload (the hook prints it);
/// the unwind re-enters at the call site, so only the message, not the
/// location, survives. 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` — a statement op with its connection already chosen — 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)
}

/// Run a read-only query against an already-locked turso connection, bounded
/// to `row_limit` rows using LIMIT+1 semantics. A caller that runs this on the
/// **writing** connection is responsible for the `PRAGMA query_only` guard and
/// its reset ([`Connection::query_readonly`]); a reader connection carries the
/// switch for its whole life and needs neither.
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,
    })
}

/// Number of retry attempts for the open-time store lock held by another process.
const OPEN_LOCK_RETRY_ATTEMPTS: usize = 10;

/// Delay between open-time store-lock retries.
const OPEN_LOCK_RETRY_DELAY: Duration = Duration::from_millis(500);

/// Step prefix of [turso_core]'s locking-error variant as it survives into the
/// rendered message: the variant's `Display` prefix (`Locking error:`) followed
/// by the failing step. It covers the two steps that take the open-time lock
/// (`Failed locking file…`, `Failed locking shared WAL coordination file…`) and
/// excludes the variant's other uses, which take no lock never mind contention
/// (`mmap shared WAL coordination file failed`, `Failed to release file lock`).
/// `turso_sdk_kit` collapses the typed `LimboError::LockingError` variant into a
/// plain message string (`TursoError::Error(value.to_string())`), so a step
/// prefix is the most the 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, on the paths
/// where the conflict reaches it as an `ErrorKind::WouldBlock` (a `fcntl`
/// `F_SETLK` returning `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) when another process holds
/// the range, and std maps that code to `ErrorKind::Uncategorized` — not to
/// `WouldBlock` — so the engine takes its other branch and echoes the OS text:
/// `"Failed locking file, <localised OS text> (os error 33)"`. The OS text is
/// localised, the trailing code is not, and code 33 is the same discriminator
/// std's own Windows `try_lock` matches on.
const WINDOWS_LOCK_VIOLATION_CODE: &str = "(os error 33)";

/// Whether an error is the transient open-time store lock from [turso_core].
///
/// [`store::Database::open`] takes a whole-file fcntl `F_SETLK`
/// `F_WRLCK` record lock on the store files it opens read-write while the
/// database is opened — the main file and its `-wal` (see `wal_guard`'s lock
/// rule). When another process already holds that lock the open fails;
/// [`Connection::open`]'s `busy_timeout` does **not** cover this open-time
/// lock — it only governs per-statement waits after the handle is connected.
///
/// The predicate is the conjunction of [`LOCK_STEP_PREFIX`] and one contention
/// token ([`LOCK_CONTENTION_MARKER`] or [`WINDOWS_LOCK_VIOLATION_CODE`]). Both
/// halves are load-bearing: the step alone would also retry uncontended
/// lock-open failures and then report them as "locked by another process", while
/// the `WouldBlock` wording alone would never match on Windows.
/// `Busy("database is locked")` and table-level lock errors have their own retry
/// semantics and are never this condition; any other lock/busy wording stays
/// actionable through [`is_actionable_signal`], it is simply not retried.
///
/// Guarding this is asymmetric by platform, and worth knowing when trusting it:
/// `db::store_lock_check`'s `a_store_held_by_another_process_refuses_the_boot`
/// drives a real contended open across two processes, so the Unix half fails
/// loudly on an engine-wording change — that module is Unix-only, and the
/// Windows token has no such witness beyond the literal in
/// `open_time_lock_error_predicate`. The engine's opt-in IOCP backend is covered
/// only half-way: its shared-WAL path reuses the marker, but its main-file path
/// renders the contention as `"Locking error: The process cannot access the file
/// because another process has locked a portion of the file."` — neither our
/// step prefix nor a code — so selecting that vfs would silently disable the
/// retry for the main file.
///
/// [turso_core]: https://github.com/tursodatabase/turso
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`] instead.
///
/// [the open-time store lock]: is_open_time_lock_error
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. Callers use it to retry later instead of acting on a
/// transient read/write error.
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; the store's files are left exactly as they are — nothing
/// is created, modified, renamed or deleted, and no schema, migration or admin
/// account is built in its place.
#[derive(Debug)]
pub(crate) struct StoreRefusal {
    /// Physical store name (`core` or `logs`).
    pub store: &'static str,
    /// The store's data-file path (for the durable record).
    pub db_path: std::path::PathBuf,
    /// One-line reason.
    pub reason: String,
    /// True when the refusal is an environment condition (an unreadable file,
    /// resource exhaustion, permissions) rather than evidence about the store's
    /// contents. Records it 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; this bounded retry (a few seconds total) absorbs that
/// race without masking any other open failure. `attempts` is the number of
/// retries *after* the first try, so the maximum number of total tries is
/// `attempts + 1`; any other error is returned on the first encounter and never
/// retried.
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 propagation of a panic, the same handling of a cancelled task (see
/// [`join_detached`]). One runner is what keeps a read and an upkeep read from
/// drifting apart.
enum Place {
    /// The read entry: a reader connection when the store has one free, the
    /// writing connection otherwise (see [`Connection::run_read`]).
    Read,
    /// The writing connection, whatever the readers are doing — the store's own
    /// upkeep that stays on it ([`Upkeep`]) and every change.
    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()'s
        // doc for how the two sides of that single source are kept in step).
        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 for this connection (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 chain, 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". The PRAGMA maps to the
        // per-connection set_temp_store (turso_core translate/pragma.rs);
        // if a future engine rejects it, this open fails loudly instead of
        // silently regressing to disk-backed temp storage.
        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 — the
            // readers and the maintenance one — is a connection of this open
            // store and never a second open of its file, and it lives as long as
            // they do.
            db: Arc::clone(&db),
            readers: Arc::new(ReaderPool::new(db)),
        })
    }

    /// The main-file path this connection was opened on.
    pub(crate) fn db_path(&self) -> &std::path::Path {
        &self.db_path
    }

    /// Open the store's maintenance connection — see [`Maintenance`].
    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 has run — and never for a store whose file a reader
    /// must not be made from (the log store keeps its own writing connection
    /// and is not served by a reader pool). Turning readers on costs nothing:
    /// the reader connections themselves are created later, on the first read
    /// that needs one.
    ///
    /// It says nothing about store maintenance that runs after it: work that
    /// rebuilds a schema object — the FTS index work at open and in the periodic
    /// round — takes the readers out of service itself (see
    /// [`Self::quiet_readers`]) rather than resting on no read having happened
    /// yet.
    fn enable_readers(&self) {
        self.readers.enable();
    }

    /// Take the store's readers out of service for the duration of 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`] (the caller then leaves that work for a
    /// later round rather than running it against live readers).
    ///
    /// While the guard is held, reads are served by the writing connection and
    /// the readers are closed, so no reader carries a statement or a schema
    /// snapshot from before the work. Dropping the guard puts them back in
    /// service — unless the store has 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 store's readers for good, before the exit round's
    /// checkpoint runs on the writing connection.
    ///
    /// The writing connection is a handle that is never dropped, so this step
    /// is what makes sure a reader has no reading position left when the
    /// exit round's checkpoint tries to truncate the WAL. A reader that does
    /// not fall idle within [`READERS_IDLE_WAIT`] is left to the runtime: the
    /// checkpoint then answers "blocked", which the exit round recognises as
    /// blocked rather than as a failure.
    pub(crate) async fn release_readers(&self) {
        self.readers.release().await;
    }

    /// Lock the writing connection and rollback any dangling transaction.
    /// Both read and write callers on the writing connection should use this
    /// method — dangling transactions can affect read visibility in WAL mode if
    /// left active.
    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 on the writing connection MUST be rolled back
    /// before the connection is reused: the engine holds its written pages in
    /// that connection's page cache for as long as the transaction is open, and
    /// a WAL checkpoint refuses to clear a page cache with dirty pages in it
    /// (`Failed to clear page cache: Dirty { pgno: … }`) — every later write
    /// then fails and the WAL keeps the uncommitted frames.
    ///
    /// Two sources of an open transaction are covered: the deferred arm
    /// ([`TxGuard::drop`] and [`Self::begin_tx`]) and the connection's own
    /// autocommit state, which catches a transaction the arm never saw. A
    /// failed rollback keeps the arm set, so the next access retries it —
    /// one failure must not lose the orphan.
    ///
    /// `tx_task` is the record of which task owns the transaction. It is
    /// cleared here whenever this call leaves nothing open — after the rollback
    /// it performs, and when it finds the connection already in autocommit — so
    /// a record left by a dropped guard never outlives the transaction it
    /// names.
    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 there is nothing to roll back and a stale arm is only cleared — a
        // doomed ROLLBACK ("cannot rollback - no transaction is active") would
        // keep the arm set for every later access. An open transaction is rolled
        // back; that is 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 owned by the runtime, so a dropped
    /// caller abandons only the RESULT, never a half-executed statement.
    ///
    /// Why this is 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
    /// an explicit yield whose completion nothing will ever wake (turso's
    /// yields assume a fiber scheduler steps other fibers; the tokio wrapper
    /// has none). One poisoned page then hangs every subsequent op on the
    /// connection, process-wide. The detached task always runs the statement
    /// to completion, so cancellation can never strand the connection.
    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 then
    /// 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.
    /// Callers that need the pair to be atomic run it inside a transaction —
    /// through [`TxGuard::upsert_row`], never this method, which would re-lock
    /// the mutex the guard holds.
    ///
    /// The engine's upsert form is unusable while change capture is enabled on
    /// the store (`PRAGMA capture_data_changes_conn`); only its `DO UPDATE`
    /// branch has been observed to abort, with a record-decode error (`Payload
    /// too small for indicated header size`, `Invalid Text value`, `TEXT value
    /// contains invalid UTF-8`). The precise engine condition is not isolated.
    ///
    /// A caller that wraps this write's error in its own context must render the
    /// whole `anyhow` chain when it reports the failure (`?e`, or `{:#}` in a
    /// message): the outer context alone (`%e`) hides the engine's cause.
    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 via the engine's prepared-statement cache (turso's
    /// `execute` re-parses SQL on every call; hot loops use this instead). 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 (a
    /// counter's new value, the row a claim just took).
    ///
    /// This is the change entry that hands rows back, and it is what a change
    /// uses instead of the reading entries: the direction of a call is never
    /// inferred from its name, so a change issued through [`Self::query`] is a
    /// bug (it would be served by a reader, and a reader refuses it loudly),
    /// while a read issued through this one would take the writing connection
    /// for a read. The engine's `execute` discards rows, which is why the write
    /// side needs this second form; several changes read their own result back
    /// in the same statement, which is also what settles those read-then-act
    /// sequences in one step that cannot interleave.
    ///
    /// The statement is prepared per call; use [`Self::execute_rows_cached`]
    /// for a change whose SQL text is invariant across calls (see
    /// [`Self::query_cached`] for that contract).
    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 writing connection's
    /// 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 semantics
    /// (`Ok(None)` when the change matched nothing).
    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 to roll it back.
        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, a
        // dropped future or a panic before this point cannot leave a task
        // recorded as holding one. Unchanged until the guard clears it, so a
        // read issued by this task is refused on the read entry for as long as
        // the transaction is open, instead of being served by a reader behind
        // the transaction's 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.
    ///
    /// Served by a reader connection when the store has one free, by 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
    }

    /// [`Self::query`] on the connection `place` names.
    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.
    ///
    /// The two places are [`Self::run_read`] (a reader when one is free) and the
    /// writing connection; everything else about running an op — the detached
    /// task, the propagation of a panic, the handling of a cancelled task — is
    /// shared, so a read and an upkeep read cannot drift apart. `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 task calling here is the task holding an open transaction on this
    /// connection, the read is refused ([`TRANSACTION_READ_REFUSAL`]) — such a
    /// read must go through the transaction's own [`TxGuard`], or it would be
    /// served by a reader and quietly miss what the transaction itself has
    /// written. A read issued by any *other* task is an unrelated read and is
    /// served as usual.
    ///
    /// Otherwise the read is handed to a reader connection when the store has
    /// one free, and falls back to the writing connection when the store has no
    /// readers (the log store), when its readers could not be created, and while
    /// they are out of service for a repair or on the way down. Falling back is
    /// deliberate: a read that cannot get a reader is still a read the product
    /// must serve, and the reader connections are an optimisation of its
    /// latency, never a new way for a read to fail.
    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 that holds the open transaction on this
    /// connection — the transaction's own work, which must be read through its
    /// [`TxGuard`].
    ///
    /// Reads issued by any other task are unrelated to that transaction and are
    /// not affected, so this is not a rule that fails unrelated concurrent
    /// reads; and a read that is genuinely part of the transaction's work cannot
    /// be served any other way, because the transaction's own uncommitted writes
    /// are only visible on it. Before readers existed this mistake stopped dead
    /// on the connection's own mutex instead; the code says so here now.
    ///
    /// 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 (it
    /// sees committed state, never the transaction's own writes).
    fn refuse_transaction_read(&self) -> turso::Result<()> {
        // `try_id`: a caller outside a task (a `block_on` caller — the debug CLI,
        // a test body) has no id to compare with, and reads there are not the
        // transaction's own work in the sense this rule is about.
        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 connection the enforcement is the connection's own state: it
    /// was created read-only (`PRAGMA query_only = 1`, kept on for its whole
    /// life) and the reader entry refuses the statement forms that switch does
    /// not cover, so nothing has to be 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` — all under a
    /// single hold of the connection mutex. The reset is attempted on every
    /// outcome (including a query-engine panic) and is itself panic-guarded, so
    /// a reset-phase never unwinds the caller. A reset-phase panic, or a failure
    /// to roll a leaked transaction back, flags `has_dangling_tx` so the next
    /// access attempts a rollback; a non-panic `query_only=0` failure only
    /// surfaces an error. Either way a failed `query_only=0` leaves
    /// `query_only=1` (rejecting instance writes) — loud, with no automatic
    /// recovery. Bounds the result set to `row_limit` rows using LIMIT+1
    /// semantics (a result of exactly `row_limit` rows is NOT flagged truncated;
    /// the `row_limit + 1`-th row flags it). Returns column names + rows.
    ///
    /// The statement forms are refused the same way on either connection
    /// ([`reader_refusal`]): the reader entry refuses them on a reader, and this
    /// guard refuses them before the fallback path runs the statement — so a
    /// store gets one verdict per statement whichever connection serves it, and
    /// 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 instead of after waiting for a reader; the reader entry
        // applies the same guard for the reads that do not come through here
        // ([`ReaderLease::run`]), which is what keeps the verdict identical on
        // either path.
        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 to its normal state (query_only
                // off, autocommit) so instance writes are never left disabled. The
                // `query_only` reset happens first; then a transaction-control statement
                // (BEGIN/SAVEPOINT) that a raw IPC client could send — not re-validated
                // instance-side — is rolled back to autocommit, since an open transaction
                // on the writing connection would poison subsequent instance writes. The
                // whole reset is also panic-guarded: a turso engine panic here must not
                // unwind (leaving query_only=1), so the caller gets an error instead.
                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: the connection state is unknown (`query_only`
                        // may still be 1 and/or a transaction may be open). 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 through a closure.
    /// Returns a Vec of results so callers can handle per-row errors
    /// individually.
    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.
    /// Served by a reader connection 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
    }

    /// [`Self::query_row`] on the connection `place` names.
    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.
    ///
    /// Returns `Ok(Some(val))` if a row is found, `Ok(None)` when no row
    /// matches, or `Err` if the query fails for another reason. The no-row
    /// case is folded to `Ok(None)` by [`optional_row`].
    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`]. Operates on an
    /// already-locked connection. Returns [`turso::Error::QueryReturnedNoRows`]
    /// when no row 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, using the connection's
    /// prepared-statement cache instead of re-preparing the SQL on every call.
    /// Served by a reader connection when the store has one free — see
    /// [`Self::run_read`]. A change with rows to hand back goes through
    /// [`Self::execute_rows_cached`] instead.
    ///
    /// # Cache contract
    ///
    /// Only SQL whose full text is invariant across calls — call-site string
    /// literals or compile-time constants — may be routed through this method.
    /// turso caches compiled programs per connection keyed by the exact SQL
    /// text and never evicts them, so per-call-composed fragments (dynamic
    /// IN-lists, interpolated limits, arbitrary user SQL) must keep the plain
    /// prepare-per-call path instead. All `_cached` methods below share this
    /// contract.
    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
    }

    /// [`Self::query_cached`] on the connection `place` names.
    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`]. Operates on an
    /// already-locked connection, obtaining the statement from turso's
    /// per-connection prepared-statement cache. Collects all rows into a `Vec`.
    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`], which returns per-row results), using the cached
    /// prepared-statement path (see [`Self::query_cached`] for the cache
    /// contract).
    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, using the cached
    /// prepared-statement path (see [`Self::query_cached`] for the cache
    /// 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, using the cached
    /// prepared-statement path (see [`Self::query_cached`] for the cache
    /// contract).
    ///
    /// Returns `Ok(Some(val))` if a row is found, `Ok(None)` when no row
    /// matches, or `Err` if the query fails for another reason. The no-row
    /// case is folded to `Ok(None)` by [`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 database file and truncates
    /// the WAL. Run before hard process termination (e.g.,
    /// [`std::process::exit`] in self-update) for a clean store handoff;
    /// committed data is already fsync-durable at COMMIT.
    ///
    /// Safe to call even if the database is not in WAL mode — non-WAL databases
    /// treat this as a no-op (the result row reports `log == checkpointed == -1`).
    ///
    /// The result row is parsed into a [`CheckpointOutcome`] so callers can
    /// distinguish a complete checkpoint 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 (see [`crate::db::shrink_gate`]).
    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 the store's
        // maintenance connection, 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.
    ///
    /// Checks b-tree page structure, NOT NULL and CHECK constraints, and
    /// index cardinality. Returns `Ok(())` on success, or an error with the
    /// first corruption message if any corruption is detected.
    ///
    /// Read-only, and a full scan of the store's b-trees: its cost scales with
    /// the store, not with a constant. On the live installation the periodic
    /// integrity round of a ~540 MiB store is what ordinary reads used to wait
    /// seconds behind — which is why those reads are served by reader
    /// connections now, and why this is upkeep that runs on whichever of the
    /// store's own connections runs it (see [`OwnConnection`]): the maintenance
    /// connection for the periodic round ([`Maintenance`]), the writing
    /// connection for the boot-time repairs and the store-open checks.
    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 store's 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 those callers ask of the writing connection are all upkeep:
/// they judge or maintain the store itself rather than serve a caller, and the
/// compaction and the repair must not run against a reader's reading position
/// (and the repair must not run beside live readers at all). Keeping them behind
/// one entry leaves those exceptions in one place instead of hunting them down
/// call by call, and it 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 the store's maintenance connection ([`Maintenance`], and see
/// [`OwnConnection`]), so ordinary work never waits behind them. The pre-shrink
/// gate is asked of the connection that will run the reclaiming checkpoint, so
/// its probe travels with it (see [`crate::db::shrink_gate`]).
///
/// 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 be
/// committed between one of them and the change it decides. What relies on that
/// says so at the place it relies on it.
#[derive(Clone, Copy)]
pub(crate) struct Upkeep<'a>(&'a Connection);

impl Connection {
    /// The entry for the store's own upkeep reads — see [`Upkeep`].
    #[must_use]
    pub(crate) fn upkeep(&self) -> Upkeep<'_> {
        Upkeep(self)
    }
}

impl Upkeep<'_> {
    /// An upkeep read on the writing connection, returning all matching rows.
    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
    }

    /// An upkeep read on the writing connection that returns zero or one row.
    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)
    }

    /// An upkeep read on the writing connection that returns exactly one row.
    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
    }

    /// An upkeep read on the writing connection, mapping each row.
    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, so a reason the engine emits belongs to this call and no other
    /// (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 ──────────────────────────────

/// The store's maintenance connection — the second connection of the very store
/// this handle already has open (never a second open of its file), for the
/// upkeep that judges or compacts the store itself and must not make ordinary
/// work wait: the periodic round's checkpoint and its integrity verification
/// (see [`crate::db::checkpoint`], which is the round's own statement of where it
/// runs and of what could not move).
///
/// It is made for the round that uses it and dropped when that round ends, so
/// between rounds the store carries exactly the connections it carried before
/// and nothing a long-lived extra connection could accumulate (schema, header,
/// page cache) is ever stale. Making it costs no new file descriptor and takes
/// no lock of its own: the process keeps the single fcntl lock and the
/// single-writer discipline it had.
///
/// It is `query_only` for its whole life, which keeps the store's "only the
/// writing connection may change it" structural rather than a discipline: the
/// engine refuses any write statement on it. The three statements it does run
/// are unaffected — the pre-shrink gate's `PRAGMA page_count` (a read), the
/// compaction (`PRAGMA wal_checkpoint`, which the engine translates as a
/// statement that writes nothing; a checkpoint's serialization is the engine's
/// own WAL checkpoint lock, the same one the writing connection's compaction
/// takes) and `PRAGMA quick_check`, a read.
///
/// A store that cannot give the round one of these ([`Connection::maintenance`])
/// has the round issue both statements — the compaction and the verification — on
/// its writing connection instead; that is the round's fallback, not an end to its
/// upkeep.
///
/// Accepted, unchanged: the checkpoint can meet the store's live readers and
/// writers, and the engine then answers it blocked exactly as it always has —
/// retried, never a failure (see [`crate::db::checkpoint`]).
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 statements, 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 writing
    /// connection's 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 the store's
/// maintenance one ([`Maintenance`]) — as opposed to a reader, which serves a
/// caller's read ([`ReaderLease`]). The store's own upkeep is issued through this,
/// so one body serves the exit round (which owns the writing connection by
/// construction) and the periodic round (which owns the maintenance connection;
/// see [`crate::db::checkpoint`]).
///
/// A reader is deliberately not one of these: its snapshot could lag the frames
/// the very next statement tries to fold. Such a connection is shared by
/// reference across the awaits of the round's future, which runs on the daemon's
/// spawned tasks — hence the `Send + Sync` supertrait and the `+ Send` each
/// future-returning method states for its own future, which an `async fn` in a
/// trait does not promise.
pub(crate) trait OwnConnection: Send + Sync {
    /// Run one statement the store issues to itself, on this connection.
    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`] for the gating contract).
    fn checkpoint(
        &self,
        truncate: bool,
    ) -> impl Future<Output = anyhow::Result<CheckpointOutcome>> + Send;

    /// The store file this connection has open.
    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
    /// in the scan 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
    }
}

// ── Reader connections ──────────────────────────────────────────────

/// How many reader connections one store keeps.
///
/// Two bounds fix this count. The floor is two: one read that is slow, or whose
/// caller has already 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
/// in this file that could make a read fail where it used to succeed. The source
/// keeps a handful of frame-valued read marks, four of them for readers, which
/// reads like four positions is all there is (three readers plus the writing
/// connection's own statement); the measurement is what settles it, and it is
/// what this count rests on: `readers_at_distinct_frames_are_all_admitted` holds
/// twenty-four live, only-partly-stepped reads at twenty-four distinct frames at
/// once, and every one of them is admitted — the engine hands a reader the
/// highest read mark at or below its snapshot instead of handing out one
/// position per reader.
///
/// Accepted residual: were the engine ever to deny a reader a position anyway
/// (the retry-then-`Busy` path the source reads like), it would surface as that
/// one read's own engine error after the engine's own retry — never as a state
/// change, and never as a failure of the store.
///
/// The cost is per connection and is accepted: each reader carries its own page
/// cache (2000 pages, ~8 MiB), its own prepared-statement cache (filled from the
/// same SQL the writing connection prepares, so a statement is prepared once per
/// reader) and its own connect — the engine's connect is blocking, so the first
/// read that needs a reader pays for the readers it creates. That steady-state
/// memory 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: every
/// connection carries the per-connection settings it needs.
const BUSY_TIMEOUT: Duration = Duration::from_mins(1);

/// Connect one read-only connection of the open store `db` — a reader
/// ([`ReaderPool`]) or the store's maintenance connection ([`Maintenance`]) —
/// carrying the per-connection settings every read-only connection of this store
/// gets: the busy timeout the writing connection gets, in-memory temp storage
/// (the missing-temp-root guarantee), and the read-only switch, set before any
/// statement is prepared on the connection and never reset.
///
/// The engine's connect is blocking (it reads the store header and page 1 and
/// refreshes its stats snapshot), so it runs off the async worker pool. `what`
/// names the connection in the failure text, so a failure still says which one
/// could not be made.
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 before giving up on waiting.
///
/// A reader serves one read at a time, so the readers fall idle in the time a
/// read takes; the wait only runs long when a read was abandoned by a caller
/// that gave up. Giving up on the wait is what keeps a store repair, and the
/// exit round's checkpoint, from hanging behind such a read.
const READERS_IDLE_WAIT: Duration = Duration::from_secs(5);

/// Why a read issued by the task that holds a transaction is refused.
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. A bracketed or quoted name is the name
/// inside it ([`pragma_form`]), which is also how the validator's tokenizer
/// hands a name over — so the two agree on which name a statement runs. On the
/// inspection path this allowlist is defense-in-depth on top of the engine's own
/// read-only switch; on a reader connection it is what covers the pragmas that
/// switch leaves unclassified (`PRAGMA wal_checkpoint` compacts the store file
/// and `PRAGMA journal_mode` rewrites its header, and neither is refused by
/// it).
///
/// `foreign_key_check` is on the list because this product issues it as a read
/// ([`crate::db::migrations`], after a consolidation import) — the engine does
/// not know the name and answers it with no rows, so it changes nothing either
/// way. The engine's own foreign-key read is `foreign_key_list`, which is 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 ten
/// names the engine routes to its query path for both the call form and the `=`
/// form (its `translate/pragma.rs` match on the name behind `Equals | Call`).
/// That is why `PRAGMA table_info = tickets` reads rather than assigns, and why
/// [`reader_refusal`] lets their assignment form through; every other listed name
/// is taken with a value only as a setter, 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: it is created with
/// `PRAGMA query_only = 1` and the switch is never turned off, so the engine
/// itself refuses every change it classifies as a write when a statement is
/// prepared — DML, DDL, `VACUUM`, `REINDEX` and the pragma setters it
/// classifies as writes. 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
/// statement's 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 does not need to refuse: a pragma absent from the list, and
/// any assignment to a name whose body the engine does not route as a query.
/// Refusing a read costs a caller 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 on a reader ([`ReaderLease::run`]), and the read-only inspection
/// path applies it on the writing-connection fallback
/// ([`Connection::query_readonly`]) — a raw client cannot do on the fallback what
/// a reader turns away. The narrowing that follows for such a client (a no-op
/// setter like `PRAGMA page_size = 8192` is refused where the fallback used to
/// accept it) is intended.
///
/// The call form of a listed name (`PRAGMA page_size(8192)`) is left to the
/// engine: of the listed names only `page_size`, `user_version` and
/// `schema_version` are settable, and against an initialized store the first is
/// a no-op, the third an explicit no-op, and the second a write the read-only
/// switch itself refuses — so a reader cannot change state through one.
///
/// The failure it prevents is a change that succeeds on a reader and is never
/// recorded: change capture runs on the writing connection only, so a change
/// committed anywhere else never reaches the store's own record of changes —
/// which is what the ticket chronicle (`ticket_chronicle`) is materialized
/// from.
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`, an
            // unterminated bracket) is not one this guard can clear: name what
            // was actually 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 — so a bracketed pragma the inspection path accepts
/// is not refused here for being bracketed.
///
/// An unterminated quoting (`PRAGMA [wal_checkpoint`) resolves to no name at
/// all, and the allowlist then refuses the statement — as does the engine,
/// which cannot parse it either.
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 leading 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 `;` (an
/// empty statement is nothing), 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.
///
/// # What they are for
///
/// A read used to be issued on the writing connection and therefore queue behind
/// whatever else the store was doing — a read issued while the periodic
/// integrity verification was under way waited seconds, against an ordinary read
/// cost of milliseconds. A read of its own is served at once instead, and reads
/// do not queue behind one another while a reader is free.
///
/// # 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 the handle outlives the connections made from it.
/// * Readers are created on the first read that needs one, and only after
///   [`Connection::enable_readers`] — so opening a store, including the many
///   stores the checks open, 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 forms the guard refuses — so there is nothing to roll back on one.
///
/// # What is accepted
///
/// * A read waits for a reader only while every reader is busy; one read whose
///   caller has already given up can hold one reader, never the pool.
/// * A read no longer queues behind another task's open state change, so it may
///   see the state as of just before that change is committed — never older than
///   that.
/// * 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 — no writer-side code drops another
///   connection's cache — so a read that follows a commit re-reads what it
///   needs: a read can be slower than it would have been 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 the engine's own retry, and never as a state change.
/// * The pool's steady-state memory (three connections' own caches) and the
///   one-time cost of creating them, paid by the first read that needs one.
struct ReaderPool {
    /// The open store the readers are made from.
    db: Arc<store::Database>,
    /// The free readers, and whether they have been created yet.
    inner: tokio::sync::Mutex<ReaderPoolInner>,
    /// Woken when a reader is given back to `inner.idle`.
    freed: tokio::sync::Notify,
    /// Whether the readers are in service. Reads are served by the writing
    /// connection while it is `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: the store is on its way
    /// down and the readers are gone for good. It is what keeps a repair's
    /// [`QuietReaders`] guard, dropped after the release, from putting readers
    /// back in service during the exit sequence.
    released: AtomicBool,
}

/// [`ReaderPool`]'s state under its lock.
struct ReaderPoolInner {
    /// The free readers — empty until the first read creates them, and while
    /// every reader is serving a read.
    idle: Vec<store::Connection>,
    /// How far the pool has got with creating them.
    state: Readers,
}

/// How far a pool has got with creating its readers.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Readers {
    /// Not created yet: the first read that needs one creates them.
    Uncreated,
    /// Created — in `idle`, or serving a read.
    Created,
    /// Creation failed, and is not retried: every read from then on is served by
    /// the writing connection, which is where reads were served before readers
    /// existed. The reason was logged where the creation failed.
    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),
        }
    }

    /// Put the readers in service — see [`Connection::enable_readers`].
    ///
    /// `send_replace` rather than `send`: the pool holds no receiver of its own,
    /// and a `watch` sender refuses to send while no receiver 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 for a free
    /// one). The caller then serves the read on 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 already
                // stale by the time this call gets the lock, and a read that got
                // past it after a quiet() had drained the pool would create
                // readers and run on one — exactly what the quiet() was for.
                if !*in_service.borrow() {
                    return None;
                }
                match inner.state {
                    Readers::Created => {}
                    // Not retried: a creation that failed stays failed, and the
                    // reads it could not serve 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 work the caller is about to do.
    /// `None` when they did not fall idle within [`READERS_IDLE_WAIT`]: the
    /// caller then defers rather than running against live readers.
    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 of them is idle. `false` when they did
    /// not all fall idle within [`READERS_IDLE_WAIT`]. A reader still out at
    /// that point keeps its own connection (and its reading position) until the
    /// runtime drops it.
    async fn drain_idle(&self) -> bool {
        let deadline = tokio::time::Instant::now() + READERS_IDLE_WAIT;
        loop {
            {
                let mut inner = self.inner.lock().await;
                let all_idle = match inner.state {
                    // Nothing was created, so nothing is out.
                    Readers::Uncreated | Readers::Failed => true,
                    Readers::Created => inner.idle.len() == READER_CONNECTIONS,
                };
                if all_idle {
                    // A pool that had readers is back to not having any: the
                    // next read that needs one creates them again. A failed
                    // creation is not one of those — it 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: the readers are out of service (reads are served by the writing
/// connection) and closed. Dropping the guard puts them back in service — unless
/// the store has already released them for good ([`ReaderPool::release`], the
/// exit path), which a guard dropped late must not undo — and the next read
/// creates them again.
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);
        }
    }
}

/// One read's hold on one reader connection.
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 and the reader returns to the pool when it does.
    /// The statement itself is bounded too — every connection this product
    /// opens carries the per-statement limit
    /// ([`crate::db::store::statement_limit`]), which the engine arms on the
    /// connection and enforces as it steps, so a statement that overruns it is
    /// terminated and the reader stays usable. Nothing here has to stop a
    /// statement in place; abandoning the caller's wait never needs to.
    ///
    /// 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;
            // The reader goes back before a panic is re-raised: the engine's own
            // statement cleanup has run by then, and a reader holds no
            // transaction (the guard above is what keeps one from being opened).
            pool.give_back(conn).await;
            match outcome {
                Ok(inner) => inner,
                Err(payload) => std::panic::resume_unwind(payload),
            }
        };
        join_detached(tokio::spawn(task).await)
    }
}

/// Collect problem rows from `PRAGMA quick_check` (skipping `"ok"` and the
/// known FTS index-cardinality false positive). Used by
/// [`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 result row
/// (`busy`, `log`, `checkpointed`).
///
/// The engine's success path writes `busy == 0`; a checkpoint it could not run
/// (blocked or genuinely failed) leaves the row with `busy` set and the frame
/// columns NULL, and that row is refused by [`parse_checkpoint_row`] — so a
/// completed or partial checkpoint is the only thing parsed into this type, and
/// a partial one is detected via `log > checkpointed` (frames remaining in the
/// WAL).
#[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 (its blocked row
    /// carries none, and the parse refuses it), so this is false for every row
    /// that reaches here — it stays a field of the outcome so the arms that
    /// render 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`; `is_complete` relies on that reset.
    pub log_frames: i64,
    /// Frames backfilled into the database by the checkpoint (`-1` for
    /// non-WAL databases).
    pub checkpointed_frames: i64,
}

impl CheckpointOutcome {
    /// True when every WAL frame was backfilled and no busy condition was hit.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        !self.busy && self.log_frames <= self.checkpointed_frames
    }
}

/// Read an integer column from a checkpoint result row.
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`].
///
/// The engine answers a checkpoint it could not run — blocked by another
/// connection's reading position, or genuinely failed in its pager — with a
/// *successful* statement whose row is `busy` set and the two frame columns NULL:
/// it fills those on the success path only, and emits its own reason as a
/// debug-level event rather than as an SQL error ([`checkpoint_cause`] captures
/// that event when the caller armed a sink). The two answers are therefore
/// indistinguishable from the row, and the NULL frame columns are what says so:
/// the row is refused here, and the captured reason is what tells a blocked
/// attempt from a genuine failure from then on (see
/// [`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 engine reports a checkpoint it could not run as a
/// successful row that cannot carry its reason, so the armed sink is the only
/// source for it — 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 a single transaction.
/// Holds the mutex guard for the entire duration — 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, and
/// `execute_one` for a change that reads its own result back. Each calls the
/// helper behind the [`Connection`] entry point, or the inner
/// `store::Connection`, on the mutex held here; the entry points themselves
/// cannot be used — a write would re-lock that mutex on a detached task and wait
/// forever, and a read is refused outright.
///
/// It is the only place a read can see the
/// transaction's own uncommitted writes, and the connection's read entry refuses
/// a read issued by the task holding the guard (see
/// [`Connection::refuse_transaction_read`]) precisely so that 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 operation. Set to None when the transaction
    /// has been explicitly committed or rolled back, preventing Drop from
    /// flagging a dangling transaction.
    has_dangling_tx: Option<Arc<AtomicBool>>,
    /// The parent's owning-task record, cleared with the flag above so the
    /// connection's 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 caller that wraps
    /// the error must render the whole 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
    }

    /// Execute multiple SQL statements (e.g. a schema) inside the transaction.
    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. Returns an empty Vec when no rows match.
    ///
    /// This is the only read that sees what the transaction itself has written,
    /// and the connection's read entry refuses a read issued by this task while
    /// the transaction is open (see
    /// [`Connection::refuse_transaction_read`]) — so the transaction's own work
    /// reads here.
    pub async fn query(
        &self,
        sql: &str,
        params: impl IntoParams + Send + 'static,
    ) -> turso::Result<Vec<Row>> {
        Connection::query_impl(&self.conn, sql, params).await
    }

    /// Execute a **change** of the transaction's own work that returns exactly
    /// one row.
    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
    }

    /// Execute a read of the transaction's own work, mapping each row, failing on
    /// the first per-row error.
    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))
    }

    /// Commit the transaction and release the lock.
    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(())
    }

    /// Rollback the transaction and release the lock.
    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: from here on
    /// the task's reads are ordinary reads again. Guard-side only — the parent's
    /// flag itself is left to the write path (see [`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 Connection so the next
        // write operation (execute, begin_tx) will issue a ROLLBACK first.
        // This is a deferred pattern — we can't call async methods from Drop,
        // but the lock isn't released yet (MutexGuard is still alive), so
        // no other task can execute a 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 itself is left
        // for the deferred rollback: a task that dropped its guard no longer has
        // a transaction's own work to read.
        self.release_task_record();
    }
}

// Schema / index management

/// Ensure a full-text search index exists with the correct tokenizer.
/// Drops and recreates if the existing index has a different tokenizer.
///
/// 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
        // store's readers off exactly as the corruption rebuilds do — see
        // [`Connection::quiet_readers`] for the premise. At open time this costs
        // nothing: the readers are created by the first read, and this hook runs
        // before any read is served — but the guard is what the code rests on,
        // not that ordering. A read in flight makes the migration wait for the
        // readers to fall idle, and a reader that does not fall idle in time
        // leaves the index as it is: the store still opens, and the next open
        // retries the migration.
        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` prevents failure when two
        // connections run schema init concurrently (e.g. parallel tests).
        conn.execute(ddl, ()).await?;
    }

    Ok(())
}

/// Probe term for the MATCH smoke probe — a plain alphanumeric token, valid
/// for any ngram width; returns zero rows on an empty index but still proves
/// the FTS 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 either names the user-visible index or the internal FTS backing
/// dir (the benign exact count-mismatch message is already filtered by
/// `scan_integrity_rows`; any other internal-dir row is real corruption).
/// core.db carries exactly one FTS index, so internal-dir rows cannot belong
/// to anything 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). Part of the index repair, so it reads
/// through [`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`]) — imported by
/// `crate::pipeline::board::after_open`. The append-only migrations catalog
/// independently carries its own raw-SQL schema entry (by design); the const
/// pair is the authoritative known-good form.
pub(crate) const TICKETS_FTS_INDEX_NAME: &str = "idx_tickets_title_fts";

/// Known-good DDL for the ticket-title FTS index. The const pair is the single
/// shared known-good copy used by [`crate::db::ensure_fts_index`] and the
/// repair — never rebuilt from `sqlite_master`, whose stored DDL for a corrupt
/// index is untrusted. It is imported by `crate::pipeline::board::after_open`.
/// The append-only migrations catalog carries its own raw-SQL schema 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 query proves the index is readable (the incident's corruption also
/// failed plain MATCH queries while quick_check looked clean apart from
/// masked rows). An Err is a detection signal, not a row-count assertion.
/// Upkeep: part of the index repair, so it reads through [`Upkeep`].
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
/// corruption signature is present, `None` when healthy. It reads only the
/// probe query — a caller that has just scanned the store never scans it
/// again — and the probe is what 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 against a token drawn 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: a token drawn from a title
    // 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(())
}

/// Drop+CREATE and post-rebuild verification results, returned for callers
/// that need to branch on them (the runtime recovery).
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), not from `sqlite_master` — the stored DDL of a corrupt index
/// must not be trusted to be the right shape, and the known-good DDL is
/// already threaded in. 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 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 deliberately keeps it
/// away from, and the boot repair's own start leaves its checkpoint to the exit
/// path like every other write of that start. The rebuilt index's 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
    // (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,
    }
}

/// Outcome of the runtime (periodic-round) ticket-title FTS repair.
#[derive(Debug)]
pub(crate) enum TicketTitleFtsRuntimeRepair {
    /// Store carries no ticket-title FTS index — nothing to repair.
    NotApplicable,
    /// Index present and healthy — nothing about this attempt was FTS-attributable.
    Healthy,
    /// Corruption detected and the rebuild ran; payload summarizes detection
    /// evidence and repair outcome for the caller's report.
    Rebuilt(String),
    /// The repair was not attempted: the store's readers did not fall idle, so
    /// the rebuild could not be run with the store quiet. Reported as itself,
    /// never as a failure — the next round tries again.
    Deferred(String),
    /// Detection errored/panicked or the rebuild panicked — repair incomplete.
    Failed(String),
}

impl TicketTitleFtsRuntimeRepair {
    /// Compact human-readable summary for the failure report (the enum's
    /// derived Debug keeps the shape but is not report-friendly). Reads the
    /// payload variants so the detection/repair evidence is 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 runs its
/// own `quick_check` for verification and hands the result to no 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`], which shares the
/// rows it already read.
///
/// Execution is synchronous and holds the writing connection, so the store
/// serves nothing else while the repair runs — acceptable for this rare recovery
/// path. Its statements are ordinary statements: the per-statement limit applies
/// to the rebuild exactly as to everything else, and a rebuild that outran it is
/// cut like any other statement. The `sqlite_master` presence check
/// first makes stores that carry no ticket-title FTS index (e.g. logs.db)
/// no-ops. Panics are caught per probe so one caller can never escape.
///
/// # What else may be in flight
///
/// The rebuild drops and recreates the index inside one transaction, and its
/// premise is that nothing else is in flight against the store. The writing
/// connection's own mutex gives that for the product's writers. The periodic
/// round runs its compaction and verification on the store's maintenance
/// connection — a sibling connection, outside that mutex — and the round is held
/// off by construction: its body reaches this repair only after the attempt loop
/// that used that connection has returned, never beside it. The maintenance
/// connection itself is named for the same reason it is safe: it holds no reading
/// position across the repair — it is idle for it, and its next statement is the
/// verification that follows — and an idle sibling connection is not left on the
/// old pages. On its next statement's read transaction the engine sees the WAL
/// has moved, drops that connection's page cache and its cached schema cookie,
/// and the statement then adopts the writer's committed schema, so it cannot read
/// the index's old btree. 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 after the repair creates
/// fresh readers. A reader that does not fall idle in time defers the whole
/// 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 is not paid for
    // with a full pass over the store.
    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>),
    /// The caller's own scan panicked — corruption evidence, so the rebuild is
    /// attempted on it.
    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 the store twice.
///
/// The callers own the readers: [`repair_ticket_title_fts_runtime`] takes them
/// out of service 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 record-and-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 {
                // Present and probe-clean → nothing about this attempt was FTS-shaped.
                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 (verify_rebuilt warns on residual
    // quick_check problems) and the caller's terminal report runs its own
    // panic-guarded quick_check — no extra probe here, keeping this path
    // panic-free by construction.
    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 (e.g. `no such column: ticket_id`) and was
    // how a schema-DDL failure against a readable store went undiagnosed.
    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.
///
/// # Consolidated layout
///
/// The domain stores (`DOMAIN_STORE_NAMES`) are consolidated into ONE file
/// ([`CONSOLIDATED_DB_NAME`]); the logs store remains its own file. So this
/// function maps every domain name (and the canonical
/// [`CONSOLIDATED_DB_NAME`] itself) 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 store 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 store name
/// lives in — [`store_stem`]'s rule read one step on, so the layout decides the
/// catalog and not a second copy of it.
#[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 the service keeps of them. The one place
/// the layout is spelled: a rule that decides anything by location (the
/// live-store refusal, the forensic listing) asks here rather than joining
/// `db` itself.
#[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}`,
/// written beside the store it is rebuilding. The tool guard recognises a
/// rebuild temp as one of the service's own files 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: it can hold committed-but-uncheckpointed frames, so it is moved aside
/// with the store by the quarantine and by the rebuild swap, and it is 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) — ENOSPC/EMFILE/OOM/permission must not be
/// 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`]. The engine
/// reports another process holding a store as the open-time whole-file lock
/// (the `Locking error:` step marker, whatever the platform's contention
/// wording — see [`is_open_time_lock_error`]), a locked table, or a busy
/// database. All of them are 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 (the
/// engine's open-time file lock, a locked table, a busy database). Neither is
/// damage, so the repair path propagates them loud rather than reporting a
/// spurious repair 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 that
/// hold probe text rather than a rendered 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 (an unclean previous end, a
/// recorded runtime integrity failure, or a pending schema change); only a repair
/// that *fails* refuses — a condition the repairs deliberately leave report-only
/// (an unknown quick_check signature) opens the store exactly as it does today.
/// Per-store `open()` constructors are generated by [`crate::define_store!`] on top
/// of [`open_consolidated_store`] (which calls this function for the consolidated
/// file).
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 over the store, 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, which leaves the `-wal` at zero bytes (see
///   [`crate::db::checkpoint`]); a journal larger than its own header carries
///   frames — committed work that run wrote but never checkpointed — so the
///   previous run ended without reaching that checkpoint and left the pair in a
///   state this start is the first to open since.
/// - **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, so the next open is where that repair happens, before any
///   reader exists. A scan that completes every repair clears the marker; one
///   whose ticket-title FTS rebuild did not complete re-arms it, so the next start
///   retries ([`run_repairs`]).
/// - **The catalog still has entries to apply to this store.** This start is
///   about to write schema DDL into the store (the catalog runs right after this
///   open, see [`open_consolidated_store`] and [`crate::logs`]), so a store that
///   is already unreadable 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`]), which runs
/// every ten minutes and is 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 behind. A journal of 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 of this product 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 a store left before its first catalog run) and must
/// not have a schema built inside it.
///
/// The ledger is the marker for every install this product ever created (the
/// catalog has owned it since before the retired `1`–`23` chain), so an older
/// install is not refused: it 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; every repair that preserves the data keeps handling
/// exactly what it handles today.
///
/// 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, never two. A start that does
/// repair pays for that scan plus the repair's own verification — the FTS rebuild
/// re-checks the index it just rebuilt (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
    // overflow-aliasing 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
            // (resource/permission condition or lock contention) 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, not as an unusable store.
            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 for recovery 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 store's recorded DDL, filled by
    // the row copy and then verified by its own quick_check: nothing the old
    // file's scan found survives into it, 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 own detection reaches a
    // MATCH-only breakage that `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 (they are enabled once the store is final), so no
    // reader has to be taken out of service for the rebuild. 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 is marked as
    // still owing a scan, so the next start retries what could not be completed
    // here whatever the reason for this scan was.
    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.
///
/// This is the canonical open for the domain stores: it opens the one
/// consolidated file ([`store_db_path`] mapping all domain names to
/// [`CONSOLIDATED_DB_NAME`]) and applies the append-only schema 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`] (production) and each store's `open` (isolated
/// tests).
///
/// # Catalog, not SCHEMA
///
/// The catalog is a current-shape baseline: the entries create the exact
/// current schema directly (every statement `IF NOT EXISTS`), so a fresh
/// install converges in one pass and an existing install is a no-op except
/// the upfill deltas. The baseline ids, the upfill deltas, and the resume
/// point live in the [`crate::db::migrations`] module doc — the single owner
/// of that list. The only control flow is the id-based applied check (skip if
/// the id is already recorded, otherwise run and record). A catalog failure
/// is a hard boot failure — it is never a repair finding and never a reason
/// to replace the store.
///
/// # Why tables → ALTER → indexes is baked into the catalog order
///
/// The historical 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 to create in the same batch.
///
/// Returns a **fresh** connection. Production shares it across all domain
/// stores via [`DOMAIN_CONN`]; isolated test opens (`open_test_store!`) drop it
/// with the store. There is deliberately 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 and never a reason to replace the store. A fresh store is empty
    // until the catalog builds the full current shape.
    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 (open_test_store! and
    // init_test_stores both call open_consolidated_store).
    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 is opened by `logs::init_tracing`, never here, and keeps
    // its own writing connection without readers.)
    conn.enable_readers();

    Ok(conn)
}

/// Outcome of the class-B btree-index repair.
enum RepairOutcome {
    /// No repair needed: quick_check passed, or a report-only condition
    /// (unknown signature / failed in-place repair / aborted rebuild left for
    /// operator review). The store opens normally either way.
    NoRepair,
    /// REINDEX (or the DROP+CREATE fallback) cleared the desync.
    Repaired,
    /// Overflow-aliasing: the store's data was rebuilt in a fresh file and
    /// swapped into place (the in-file DROP of the aliased b-trees would
    /// double-free the shared overflow page and re-corrupt the freelist).
    /// The returned connection is the reopened, verified store.
    Migrated,
    /// The table is unreadable (quick_check scan failure) — the store is
    /// refused, never recreated.
    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 {
    /// The table cannot be scanned ("Invalid page type"/"short read") — the
    /// store is refused.
    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 the store data-preservingly.
    OverflowAliasing,
    /// A specific non-FTS btree index is desynced — in-place repair.
    Index(String),
    /// No recognizable signature — report only.
    Unknown,
}

/// Classify the full quick_check problem list for the class-B repair.
///
/// Ordering is deliberate and structural: unreadable-table signatures win
/// over everything (the table cannot be scanned at all); overflow-aliasing
/// anywhere in the list vetoes the REINDEX even when an earlier row names an
/// index desync (quick_check can surface both 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 — 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` problem list names only conditions the
/// boot path deliberately leaves report-only (an unrecognised signature) rather
/// than damage it acts on (repair or refusal). 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 the coupling.
#[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
/// store's original bytes, and a store the engine cannot vacuum gets no snapshot
/// at all — the caller only warns, since the artifact exists for the
/// REINDEX-bakes-a-worse-error case and an engine that cannot read the store
/// cannot REINDEX it either.
///
/// Panic-absorbed: the vacuum walks every btree of an already-damaged store,
/// which is 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, in service by the time the
    // store-lock check runs this, 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 (§ "FTS Drop"); the same scan hands FTS detection its
/// rows right after ([`run_repairs`]). Returns `Ok(([`RepairOutcome`], conn))`:
/// a scan that cannot run at all, and a problem naming an unreadable table, are
/// [`run_repairs`]'s refusals — this path observes neither.
///
/// Preconditions are satisfied by construction at boot: single-writer,
/// exclusive access, and a snapshot (engine-produced `VACUUM INTO`) taken before
/// the REINDEX. The overflow-aliasing signature ("referenced multiple times" /
/// shared overflow pages, fresh or baked as "short read on page 167772160") is
/// **never** REINDEXed — that bakes a worse error; the store is rebuilt
/// data-preservingly instead (see [`migrate_overflow_aliased_store`]).
/// Unreadable tables surface as quick_check scan failures ("Invalid page
/// type"/"short read") 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 ("short read on
        // page …"). 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 quick_check signature is not
        // proof that the data is unusable, so the store boots exactly as it does
        // today — never a refusal, and 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 before this list is built), 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, which this same scan runs after this (see
            // [`run_repairs`]); 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, produced by the engine
    // rather than copied (see [`snapshot_store_via_engine`] for why). Best
    // effort: the snapshot is evidence, not a precondition for the repair.
    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 the
/// helper 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 store's 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 (the "baked short read"
/// mechanism). A fresh file is the only path that verifies clean (index valid,
/// data intact).
///
/// Preconditions hold at boot: single-writer, exclusive access before any
/// live traffic. The original family is quarantined (renamed aside, never
/// deleted — the forensic record) before the swap, so the original data is
/// preserved even when the rebuild aborts. Returns
/// `Ok(([`RepairOutcome::Migrated`], reopened))` on success. Before the swap a
/// constraint violation during the data copy (a data-integrity finding, not
/// damage) or a fresh store that cannot be built leaves the original untouched
/// and reports only (`NoRepair`). A table that cannot be read propagates as
/// `Err` (the store is refused). A swap that could not complete — a partial
/// quarantine with the main file already moved, a failed main-file rename, or a
/// rebuilt store that will not reopen — propagates as `Err`, which refuses the
/// store rather than replacing it with an empty one. Actionable resource
/// conditions (ENOSPC/EMFILE/permission) also propagate as `Err`.
#[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)> {
    // multiprocess_wal was removed: there is no shared WAL frame index to reset
    // before a rebuild.

    // ── 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 which refuses the store.
        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, not the store — 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"))
                });
            }
        }
    }

    // ── Build the fresh store at a sibling temp path ──
    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));
        }
    };
    // Schema replay (old creation order) + data copy.
    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 full rebuild attempt
            // (fresh-store open + DDL replay + data copy) before falling back to
            // NoRepair — the operator-facing signal to intervene (e.g. restore
            // from backup), filed durably until such a start runs.
            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))
            }
        };
    }

    // ── Swap: quarantine the original family (forensic, never deleted), move
    // the fresh family into place, reopen with the module schema. ──
    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; sibling renames normally fail together, so main-in-place
        // means the original main is preserved (reopening it reads the main
        // file plus its `-wal`) and 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 (see
    // `checkpoint_rebuilt_before_swap`), so its main file alone holds every row;
    // when the pre-shrink gate refused that checkpoint 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 the quarantine. Bail loudly (the store's boot fails)
        // instead of opening a fresh empty store over the abandoned migrated
        // data; the temp guard discards the migrated family.
        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 over a healthy rebuild).
    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 (the
            // "lost data" diagnostic must not fire on a read failure).
            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 reported above): the swap
        // succeeded and the store is in place — the periodic integrity round is
        // what 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 simply skips the
/// checkpoint and the swap proceeds without the fold-in, leaving those two
/// renames as the crash window — the gate owns what a refusal means and where it
/// is recorded (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 signal (resource/permission or lock contention) — propagate.
    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 helper adds the surrounding double quotes.
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 data copy and maintained incrementally by the inserts.
/// Counts are verified per table; a mismatch or a 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 here is an engine
        // anomaly; fail closed rather than silently skipping the object
        // (mirrors the counts loop's fail-closed 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; copy its rows so the old watermark survives the
    // explicit-id copy (WAL-mode explicit-rowid inserts advance, never
    // clobber) — deleted high ids must not be re-issued after migration
    // (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 (the
        // 324 MB-class sessions store), 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` runs statements in autocommit, 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 — 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`), so the
    // uncommitted DROP is undone before any further DB access.
    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>`). Returns `None` for any other
/// message shape (overflow-aliasing, unreadable table — the FTS false
/// positive is already filtered by [`scan_integrity_rows`] before quick_check
/// surfaces an error).
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 WAL 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 file 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 first
/// ([`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. Returns 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 to never
/// clobber 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).
///
/// Returns true when every existing source was moved aside — a partial
/// quarantine means a subsequent clobbering rename would destroy part of the
/// forensic record, so the migration path aborts instead (the un-moved files
/// stay in place).
#[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` accepts any `&str` including dynamic temporaries from
/// `format!` — it is intentionally not `&'static str` to allow callers to
/// include dynamic context (e.g. phase transitions, short hashes) in log
/// messages. Use a verb phrase for natural reading (e.g. "add comment",
/// "record sanitation failure") rather than a bare noun.
///
/// Uses `ticket_id` (or any identifying label) and `action_label` for
/// structured warn-level logging on failure.
///
/// Thin adapter over [`with_tx_outcome`]: commits whenever `work` returns
/// `Ok`, inheriting its transaction lifecycle and warning semantics.
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, and report it.
///
/// `work` returns `anyhow::Result<bool>`:
/// - `Ok(true)` — commit the transaction.
/// - `Ok(false)` — roll back **without** a warning: the work deliberately
///   aborted and nothing must be written. This follows the board layer's
///   claim convention for expected no-ops (e.g. a CAS phase-guard miss when
///   the ticket moved externally while a stage was finishing).
/// - `Err(e)` — roll back and log the standard warn-level messages,
///   including `"{action_label}: transaction rolled back"`.
///
/// Returns `Ok(true)` when the transaction committed, `Ok(false)` when it
/// was 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`, pid = process
/// id). Parse side shape-validates it via `debug::is_family_stamp` — the writer round-trip
/// test locks the coupling. Bind once per family: 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`]): the store's own `PRAGMA page_count`
    /// answers 0 while its main file holds real pages and it still reads its rows —
    /// so an ungated reclaiming checkpoint would truncate it to nothing.
    ///
    /// A real store is checkpointed (TRUNCATE, leaving the pages in the main
    /// file and the journal reclaimed) 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` (turso takes no
    /// checkpoint on drop), 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 in this state — and discards
    /// the orphan journal as it opens the store: turso 0.8.0 answers 0 pages and
    /// empties a journal it cannot apply to an empty main file. The state is a
    /// boot refusal, and this fixture pins that it never reaches a reclaiming
    /// round (see the checkpoint tests).
    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 frame 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 WAL's frame chain from that frame to the
    /// end (the stored checksums of the frames after it are seeded by it).
    ///
    /// A test fixture may write these bytes; the product may not (wal_guard's lock
    /// rule) — this runs on a hermetic fixture the engine is not holding.
    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 it is not, this helper's algorithm does
        // not match the engine's and any patch it wrote 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 are unchanged and recompute to the values already
        // stored, so only the patched frame and the frames 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 client's refusal text. Only ever
    /// 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.
    ///
    /// Both assertions matter — a non-zero exit alone is not proof, because a lost
    /// lock lets `sqlite3` reach the schema, where turso's FTS DDL (`CREATE INDEX …
    /// USING fts`) is unparseable and also exits non-zero. Assert on the lock/busy
    /// substring, never on a byte-exact message: the wording varies by version.
    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 here is what 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. The experiment flags and
    /// the per-statement limit live on the connection [`crate::db::store`]
    /// creates, so a store handle built anywhere else — through the SDK kit
    /// (`TursoDatabase::new`) or through the low-level core API
    /// (`turso::core::Database::open*`) — would be a connection with neither of
    /// them, 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, neither of which the connection layer offers (it opens
    /// read-write with the default flags and steps asynchronously), so the CLI
    /// opens and drives the engine itself and arms the limit on the connection it
    /// makes.
    ///
    /// This is a source-scanning tripwire, not a security boundary: it covers
    /// every way this tree's dependencies open a store handle — the SDK kit's
    /// `TursoDatabase::new`, the facade's `Builder::new_local`, and the core
    /// API's `turso::core::Database::open*` — so any new module that opens one or
    /// arms the limit directly fails this test 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 the very place 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, but nothing outside the
        // connection layer may build a store 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 (// and ///) 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 all share one opening path: the writing connection
    /// (`Connection::open`) sets the pragma itself, while every read-only
    /// connection of a store — the readers and the maintenance connection — is
    /// made by `read_only_connection`, so those two have ONE place to keep it
    /// right. The debug CLI's separate read-only path (`connect_readonly` in
    /// src/db/debug.rs) has its own opening path. If one regresses, the
    /// guarantee silently breaks; this source-scanning tripwire reads each
    /// carrier's own 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)?])
    }

    #[test]
    fn test_sanitize_fts_query() {
        let cases = [
            // Basic cases
            ("hello world", "hello world"),
            // All Tantivy special chars → empty string (triggers caller short-circuit)
            ("+-~", ""),
            // Curly braces and backticks stripped, $ preserved
            ("`Hello ${name}`", "Hello $ name"),
            // Email preserved
            (
                "contact user@example.com now",
                "contact user@example.com now",
            ),
            // Punctuation preserved except apostrophe (phrase delimiter)
            (
                "hello, world! How's it going?",
                "hello, world! How s it going?",
            ),
            // Non-special punctuation all preserved
            ("!@#$%", "!@#$%"),
            // Identifiers with underscores preserved
            ("my_function", "my_function"),
            // Tags preserved
            ("#381", "#381"),
            // Version strings preserved
            ("v1.2.3", "v1.2.3"),
            // Paths preserved (no leading slash)
            ("feature/x", "feature/x"),
            // Leading slash stripped to prevent Tantivy regex parsing
            ("/something", "something"),
            // Leading - (MustNot) stripped via special-char → space → split
            ("-hello", "hello"),
            // Hyphen in middle becomes space (word boundary)
            ("hello-world", "hello world"),
            // Leading + (Must) stripped
            ("+term", "term"),
            // Apostrophe in word stripped (prevents phrase parsing)
            ("don't", "don t"),
        ];
        for (input, expected) in cases {
            assert_eq!(sanitize_fts_query(input), expected, "input: {input:?}");
        }
    }

    // ── parse_utc_timestamp tests ─────────────────────────────────────

    #[test]
    fn test_parse_utc_timestamp() {
        let valid_cases = [
            ("2024-01-15T10:30:00Z", "2024-01-15T10:30:00+00:00"),
            ("2024-06-15T14:30:00+05:00", "2024-06-15T09:30:00+00:00"),
            ("2024-12-25T20:00:00-08:00", "2024-12-26T04:00:00+00:00"),
        ];
        for (input, expected) in valid_cases {
            let ts = parse_utc_timestamp(input)
                .unwrap_or_else(|e| panic!("parse_utc_timestamp({input:?}) failed: {e}"));
            assert_eq!(ts.to_rfc3339(), expected, "input: {input:?}");
        }

        for invalid in ["garbage", "", "2024-01-15"] {
            assert!(
                parse_utc_timestamp(invalid).is_err(),
                "expected error for: {invalid:?}",
            );
        }
    }

    // ── quick_check tests ────────────────────────────────────────────

    /// Verify that checkpoint reports a complete outcome on a healthy database
    /// for both TRUNCATE and PASSIVE modes, and that the outcome is parsed from
    /// the result row (not silently discarded as success).
    #[tokio::test]
    async fn test_checkpoint_reports_complete_outcome() {
        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:?}"
        );
    }

    /// Exercise the busy/partial detection directly: `is_complete` is false for
    /// a busy condition or when WAL frames remain uncheckpointed (`log >
    /// checkpointed`), and true only for a fully backfilled, non-busy outcome.
    #[test]
    fn checkpoint_outcome_completeness_predicate() {
        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"
        );
    }

    /// Verify that quick_check returns Ok on a healthy (empty) database.
    #[tokio::test]
    async fn test_quick_check_passes_on_healthy_db() {
        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.quick_check()
            .await
            .expect("quick_check should pass on a healthy empty database");
    }

    /// 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));
    }

    /// 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);
        }

        // First launch: no data file — the store is created.
        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 byte-for-byte as it was.
    ///
    /// The scan itself is only on the boot path when the start has a reason for
    /// it (see `open_present_store`); this exercises the scan's own outcome, the
    /// same 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 the scan
    /// repairs here is the ticket-title FTS index, which the open reaches only
    /// through the warranted scan.
    #[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 — the start after
    /// that is ordinary again.
    #[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")
        );
        // FTS false positive — masked upstream, never REINDEXed here.
        assert!(
            desynced_index_name(
                "wrong # of entries in index __turso_internal_fts_dir_idx_tickets_title_fts_key"
            )
            .is_some()
        );
        // Overflow-aliasing and unreadable-table signatures.
        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 operation that bakes the worse error). The
    /// matcher covers turso's real message shape ("Page N referenced multiple
    /// times (references=[...], page_category=...)") 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(),
        ]));
        // A clean check names nothing to act on; the caller matches it first.
        assert!(is_tolerated_integrity_report(&[]));
    }

    /// 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 (constraint violation) must leave the original index
    /// in place, not silently dropped. 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 — 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");
        // The restored index is functional and the store is consistent.
        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);
    }

    // ── An open transaction must not survive into the next access ──────

    /// 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)
    }

    /// The rows currently in `t`, in order.
    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 really 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 on every later access.
    #[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]);
    }

    // ── Reader connections ────────────────────────────────────────────

    /// The debug validator — which the read-only inspection path applies before
    /// a query is sent anywhere — takes the reader guard's verdict as its own, so
    /// a query the inspection path 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})"
            );
        }
        // And the read forms that do reach a reader pass both.
        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 own read-only switch already refuses (DML/DDL) and the
    /// ones it does not, which is what the reader guard exists for: 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 ones the engine's
        // read-only switch does not cover. 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}"
        );
        // ...and the bracketed form of a listed read pragma is that read.
        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 it 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 issued
    /// by 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 of
    /// them 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
    /// that was written to again before the next one opened its snapshot, are
    /// every one of them 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 instead of handed out one per reader.
    ///
    /// So a reader of ours cannot be denied a position at
    /// [`READER_CONNECTIONS`] (nor at many times that count), which is what makes
    /// the count safe to fix. Were the engine ever to deny one anyway, it would
    /// arrive as that one read's own engine error after the engine's own retry —
    /// never as a state change, and accepted as such.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn readers_at_distinct_frames_are_all_admitted() {
        // Many times the count the store runs, on purpose.
        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 it with the same
    /// wordless row it uses for a genuine pager failure (`busy`, no frame
    /// counts), and the parse refusing that row is what keeps a blocked attempt
    /// out of the completed arm — the engine's own captured reason is what then
    /// tells it from a real failure, so the round retries it instead of counting
    /// it. The attempt is a deferral, not a state failure: the journal stays
    /// unfolded until a later attempt, which is why the retry here completes.
    #[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 the index under it — and
    /// the store keeps serving (the pool goes back in service, and the reader
    /// that was held is returned to it the way a read returns one).
    #[tokio::test]
    async fn the_runtime_repair_defers_while_a_reader_is_still_out() {
        let (_tmp, conn) = open_reader_store().await;
        // 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, rather
    /// than dropping and recreating the index under a reader's own snapshot.
    ///
    /// 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 — no assertion here depends on the
    /// engine refusing anything.
    #[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;
        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"
        );
        // 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");

        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"
        );
    }

    /// Whether the schema carries an index of this name.
    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 own 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 the read still holds cannot stop the next
    /// read or the next change.
    /// Multi-threaded on purpose: a read heavy enough to outlive its caller runs
    /// its steps in one poll, which on the current-thread test runtime would also
    /// 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");
    }

    // ── Overflow-aliasing rebuild (data-preserving migration) ─────────

    /// Synthesize the 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"). The 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 (more
                // columns → different hdr byte and serial order), 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 via a fresh connection (the writer connection'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 post-swap 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 long-value column.
    ///
    /// This test is `#[ignore]` by default because it performs real overflow-aliasing page surgery on a multi-MB database fixture (~4 s). Run it
    /// explicitly with:
    ///
    /// ```sh
    /// 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 the MATCH assertion 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)"
        );
        // A write on the rebuilt store stays clean (no freelist landmine).
        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.
    ///
    /// This test is `#[ignore]` by default because it performs real overflow-aliasing page surgery on a multi-MB database fixture (~4 s). Run it
    /// explicitly with:
    ///
    /// ```sh
    /// cargo test overflow_aliasing_rebuild_constraint_finding_aborts -- --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_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 the post-swap
    /// verification, `sqlite_sequence` is carried over, and the fresh
    /// watermark advances past the copied max ids via the explicit-id copy.
    /// 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.
    ///
    /// This test is `#[ignore]` by default because it performs real overflow-aliasing page surgery on a multi-MB database fixture (~4 s). Run it
    /// explicitly with:
    ///
    /// ```sh
    /// 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");
        // The backing seq table is recreated by the DDL replay and advanced
        // by the explicit-id copy + carry-over — the next implicit-id insert
        // must be 5001, not a reused 4001.
        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"
        );
        // The sqlite_sequence mirror is carried over from the old store and
        // follows the advanced watermark.
        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 really 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"
        );
    }

    // ── ticket-title FTS repair tests ──────────────────────────────────

    /// Classification of quick_check problems as attributable to the
    /// ticket-title FTS index (user-visible index name or the internal FTS dir).
    #[test]
    fn names_ticket_title_fts_classification() {
        let index = "idx_tickets_title_fts";
        assert!(names_ticket_title_fts(
            "wrong # of entries in index idx_tickets_title_fts",
            index
        ));
        assert!(names_ticket_title_fts(
            "row 5 missing from index __turso_internal_fts_dir_3_key",
            index
        ));
        // Already filtered upstream by scan_integrity_rows (exact count
        // mismatch), but the predicate still classifies it as FTS-attributable.
        assert!(names_ticket_title_fts(
            "wrong # of entries in index __turso_internal_fts_dir_3_key",
            index
        ));
        assert!(!names_ticket_title_fts(
            "wrong # of entries in index idx_sessions_created",
            index
        ));
        assert!(!names_ticket_title_fts(
            "cell_index_read_payload_ptr called on non-index page",
            index
        ));
    }

    /// `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);
    }

    /// A healthy FTS index (with content) is a clean no-op: the repair reports
    /// the index healthy and touches nothing.
    #[tokio::test]
    async fn healthy_title_fts_is_not_rebuilt() {
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = open_consolidated_store(tmp.path()).await.unwrap();
        insert_fts_ticket(&conn, "t-1", "Important bug fix").await;
        let outcome = repair_ticket_title_fts_runtime(&conn).await;
        assert!(
            matches!(outcome, TicketTitleFtsRuntimeRepair::Healthy),
            "healthy FTS index must not report corruption: {outcome:?}"
        );
    }

    /// 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);

        // Simulate the post-detection repair (real pager-level corruption
        // cannot be fabricated deterministically).
        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;

        // Idempotent re-run safety: healthy again after the rebuild.
        let after = repair_ticket_title_fts_runtime(&conn).await;
        assert!(
            matches!(after, TicketTitleFtsRuntimeRepair::Healthy),
            "rebuilt FTS index must be healthy: {after:?}"
        );

        // MATCH smoke on the known title returns that ticket.
        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");

        // Ticket rows untouched by the FTS rebuild.
        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");

        // Index present in sqlite_master.
        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 — the index is FTS-shaped
    /// again from the known DDL, MATCH works again, ticket rows survive, and a
    /// re-run of the probe is clean (idempotent). Real pager-level corruption of
    /// an FTS-shaped index cannot be fabricated deterministically; substituting a
    /// same-named plain btree index is the closest deterministic stand-in for
    /// "MATCH unusable" (in a real boot, ensure_fts_index would fix this exact
    /// 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;

        // Break it: replace the FTS index with a same-named plain btree.
        conn.execute_batch(&fts_corruption_ddl()).await.unwrap();
        assert!(!is_fts_index(&conn, "idx_tickets_title_fts").await);

        // The one repair entry point: detection must fire and the rebuild run.
        assert!(matches!(
            repair_ticket_title_fts_runtime(&conn).await,
            TicketTitleFtsRuntimeRepair::Rebuilt(_)
        ));

        // Index is FTS-shaped again and MATCH finds the known ticket.
        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");

        // Probe is clean afterwards (idempotent re-run safety) and rows survived.
        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
        ));
    }
}