mahbot 0.10.1

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
//! WAL checkpointing for all Turso database stores.
//! The daemon runs in turso's default single-process mode (no `multiprocess_wal`): one process
//! holds the sole writer connection, and each store file has one `Database` every connection of
//! that store comes from — the core store reads on a few of its own reader connections (see
//! [`crate::db::Connection`]), the log store on its single connection, and a periodic round adds
//! the store's maintenance connection ([`crate::db::Maintenance`]) while it runs. Checkpoints are
//! hygiene, not durability: commits are durable at COMMIT (fsync'd WAL frames), and a checkpoint
//! only compacts those frames into the main file, reclaims WAL space and resets the shared frame
//! index.
//!
//! TRUNCATE at exit leaves the journal reclaimed — this engine truncates the `-wal` to zero bytes,
//! not to a header — for a clean store handoff. It is avoided under live writers because resetting
//! the shared WAL frame index while a writer is live is the corruption vector; the periodic loop
//! uses PASSIVE below the 32 MiB cap instead. Known turso reopen defect: a crash mid-transaction
//! can leave un-published frame-index entries that abort the next append ("shared WAL frame ids
//! must increase monotonically") — a defect in turso's WAL reopen, not a loss of committed data.
//!
//! The canonical entry points are [`checkpoint_all_databases`] — TRUNCATE, for exit-time paths;
//! self-update restart is single-writer, agents cancelled and shutdown signalled first, and browser
//! sessions are not closed on the way out (see `chrome::cli_sessions`) — and
//! [`periodic_checkpoint_and_verify`] — PASSIVE below the WAL-size cap, TRUNCATE above, plus an
//! independent per-store integrity verification. Both release the store's readers before the round:
//! a reading position cannot then be in the truncate's way, and a reader still in flight can only
//! make the attempt answer blocked, a warn and never a filed failure.
//!
//! A compaction the engine could not run — blocked by another connection's reading position, or
//! genuinely failed in its pager — comes back as one wordless row the parse refuses; the engine's
//! captured reason tells the two apart ([`crate::db::checkpoint_cause`]). A blocked attempt is
//! never a failure: it is retried, and a store blocked through the budget keeps serving with its
//! journal unfolded. Live readers and writers make that answer more frequent — a held position or a
//! writer's own statement defers the reclaiming checkpoint — which is accepted: the journal may
//! grow while long work is open, and the protection is unchanged.
//!
//! A periodic round makes up to [`CHECKPOINT_ATTEMPTS`] attempts — the original plus one retry per
//! entry in the growing [`CHECKPOINT_RETRY_PAUSES`] schedule — for EVERY store, with or without a
//! search index; the engine's answer decides it arm by arm ([`periodic_checkpoint_inner`]), while
//! the exit-time round keeps its single attempt and never recovers or drains ([`exit_checkpoint`]).
//!
//! # A failing round never stops the service by itself
//!
//! A genuine failure no completion follows opens (or extends) a per-store *failure window*: the run
//! of consecutive failing rounds it has lasted, with its cumulative attempts and opening cause.
//! Only a window that spanned both floors — [`CHECKPOINT_FAILURE_MIN_ROUNDS`] rounds AND
//! [`CHECKPOINT_FAILURE_WINDOW`] of elapsed time — decides the stop, and then once, filing those
//! facts. The window is in-memory and bounded, and its retry pause races the daemon's shutdown
//! ([`crate::shutdown::sleep_or_shutdown_or_drain`]), so a round the drain cuts short decides
//! nothing and the draining store can leave a sibling's open window unfiled. A round that keeps
//! failing spends the whole retry schedule before it decides — the accepted cost.
//!
//! A round reports itself once, never per attempt: a genuine failure's per-attempt lines are DEBUG
//! only, and a failing round keeps one warning carrying its first failure as the cause, while a
//! round the shutdown cuts short keeps the cut-short warning, its only trace; the exit round's
//! single attempt keeps its own warning. A completion is DEBUG only too: a failure a later attempt
//! cures is the routine heal the retries exist for, so a transient hiccup that heals leaves no
//! record — its accepted price.
//!
//! The only cure is a completed checkpoint, closing the window wherever it happens — first attempt,
//! retry, or a later round. A round ending without a genuine failure closes it too: a blocked or
//! partially folded round is neither cure nor failure, and counting it as failing would let
//! non-consecutive failures stop the service. The recorded cost is the mirror case — a store
//! interleaving genuine failures with blocked attempts closes its window every time and keeps
//! serving undecided, busy-ness keeping its long-standing exemption.
//!
//! Two consequences are deliberate. The classification and stop rule are unchanged, so a persistent
//! refusal still exhausts the window and stops the service: a retry policy cannot tell a transient
//! engine refusal from a persistent one except by observing whether a later attempt succeeds, and
//! the terminal block states that limit in as many words. And no cause and no store is carved out:
//! EVERY genuine cause — ENOSPC, an I/O error, a removed volume — is served out for the whole
//! window before the stop, which the window delays, never weakens.
//!
//! The round's only recovery step runs after a first attempt that failed or answered busy —
//! whatever held that attempt back can be what lets a retry complete: the ticket-title FTS index is
//! detect+repaired (see [`crate::db::repair_ticket_title_fts_runtime`]) before the second attempt,
//! and the round is not decided by it.
//!
//! A reclaiming checkpoint the pre-shrink gate refuses is not one of those attempts: the refusal
//! ends the round, since the gate would refuse another probe — what a refusal is and is not is
//! [`crate::db::shrink_gate`]'s to state. A refusal never stops the service by itself: a round in
//! which nothing else ran keeps serving and closes any open window, while a genuine failure from an
//! earlier attempt of the same round still counts it failing.
//!
//! # Where the round's upkeep runs, and what could not move
//!
//! Compaction and integrity verification run on the maintenance connection, not the writing
//! connection, so no ordinary read or write waits for that connection's mutex behind them; a store
//! that cannot give the round one issues both on its writing connection, so none is left unupkept.
//! The one hold the round still takes is an above-cap reclaim: the engine serializes its TRUNCATE
//! against live writers, so a write issued in that window waits on the engine's writer lock and is
//! retried by the connection's busy handler, and the journal stays above its shrink threshold while
//! long work is open. The search-index repair is reached exactly after a first attempt that failed
//! or answered blocked, so under load its detection — a full `quick_check` scan on the writing
//! connection — is reached more often.
//!
//! What could not move: the runtime search-index repair, because no other operation may be in
//! flight while the index is dropped and recreated
//! ([`crate::db::repair_ticket_title_fts_runtime`]); and the exit/self-update round, whose
//! checkpoint stays on the writing connection as the process goes away. Its TRUNCATE is not alone
//! even so: a periodic round's statement runs in a DETACHED task and `spawn_cancellable` drops only
//! the loop future, so one already issued can still be in flight and answer blocked — bounded and
//! harmless (blocked → warn, and the replacement daemon replays the journal, committing nothing on
//! its own). The pre-shrink gate's probe cannot stay on the writing connection either: its
//! protection is exactly that the store's own answer and the shrink it decides come from ONE
//! connection, so it travels with the checkpoint it gates.
//!
//! Both rounds and the periodic integrity check record durably: an exit-round checkpoint failure
//! (which cannot drain or recover) is its own block, and a failing periodic `quick_check` records a
//! block once per store per process — every further failing round only warns with the running
//! count, so a persistent condition cannot append a block every 10 minutes. The checkpoint block
//! follows that shape for the same reason: every failing round short of the terminal one would
//! otherwise file a block 10 minutes apart.
//!
//! # Reclaiming checkpoints are gated before they run
//!
//! Every reclaiming checkpoint this module issues — the exit round's attempt, the periodic round's
//! first attempt and each retry — goes through [`checkpoint_attempt`], which runs the pre-shrink
//! gate first; [`crate::db::shrink_gate`] owns what it checks and accepts. The boot rebuild site
//! gates itself, and `Connection::checkpoint_ungated()` is the raw engine call that must not carry
//! a reclaiming checkpoint outside the gate.
//!
//! # The engine's real cause is kept
//!
//! [`crate::db::wal_checkpoint`] arms a per-call sink so the engine's own reason for a failed
//! checkpoint travels with the error — see [`crate::db::checkpoint_cause`] for how it is obtained
//! and what it costs. The arm keeps a blocked attempt from being read as a failure wherever the
//! checkpoint runs, the maintenance connection included. A failing round's warning and the durable
//! record render the error's whole chain; the DEBUG lines print its outermost message only. That
//! reason is also what tells a blocked attempt, never counted towards a stop, from a genuine pager
//! error ([`crate::db::checkpoint_cause::is_blocked_checkpoint`]).

use futures_util::future::{FutureExt, join_all};
use std::collections::HashMap;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};
use tracing::{debug, error, info, warn};

use crate::db::failure_record::{self, FailureKind, FailureReport, RoundCounter};
use crate::db::{
    CheckpointOutcome, Connection, OwnConnection, TicketTitleFtsRuntimeRepair, checkpoint_cause,
    shrink_gate,
};
use crate::util::UnwrapPoison;

/// Cap on a store's on-disk `-wal` size (bytes) for the periodic mode. Below it the loop runs
/// non-truncating (PASSIVE) checkpoints; a TRUNCATE runs only above, bounding WAL growth while
/// keeping the frame-index reset (the live-writer corruption vector) rare instead of 10-minutely.
const WAL_CHECKPOINT_CAP_BYTES: u64 = 32 * 1024 * 1024;

/// Default minimum free disk space (bytes) below which TRUNCATE checkpoints are skipped (only
/// PASSIVE runs). `MAHBOT_CHECKPOINT_MIN_FREE_BYTES` overrides it, `0` disables the gate; ENOSPC is
/// never corruption, it is an actionable signal, not evidence about the store.
const DEFAULT_CHECKPOINT_MIN_FREE_BYTES: u64 = 64 * 1024 * 1024;

/// Total attempts a periodic round makes for a store before it decides: the original plus one retry
/// per entry in [`CHECKPOINT_RETRY_PAUSES`] (whose length is this count less one).
const CHECKPOINT_ATTEMPTS: usize = 6;

/// The real pause before each retry of a periodic round, in attempt order: the entry at index `i`
/// spaces the retry after attempt `i + 1`, so the schedule's length *is* the round's retry count,
/// one fewer than [`CHECKPOINT_ATTEMPTS`]. The spacing grows to a 60 s ceiling — 1, 5, 15, 30, 60
/// s, ~111 s for the whole round — because the failures it spaces are the engine's own transient
/// refusals, which clear by themselves; a retry against unchanged in-memory engine state is worth
/// only its spacing. It is a fixed, hard bound, never an unbounded wait, so the waiting can never
/// hang a round (an attempt's own duration is bounded as little as before); the span it adds to the
/// 10-minute cadence is the price.
const CHECKPOINT_RETRY_PAUSES: [Duration; CHECKPOINT_ATTEMPTS - 1] = [
    Duration::from_secs(1),
    Duration::from_secs(5),
    Duration::from_secs(15),
    Duration::from_secs(30),
    Duration::from_secs(60),
];

/// Consecutive failing rounds a store's failure window must span before a genuine failure may
/// decide the stop — one failing round never stops a healthy service.
const CHECKPOINT_FAILURE_MIN_ROUNDS: u64 = 2;

/// Span, since a window's first failure, the window must cover before a genuine failure may decide
/// the stop: the "several minutes" the rule asks for, next to the round count. At the 10-minute
/// cadence [`CHECKPOINT_FAILURE_MIN_ROUNDS`] alone spans more, so the floor binds only back-to-back
/// rounds, which no production path runs.
const CHECKPOINT_FAILURE_WINDOW: Duration = Duration::from_secs(120);

/// The `record` field's value when the durable block could not be filed: the whole block already
/// went to stderr (see [`failure_record::record`]).
const BLOCK_ON_STDERR: &str = "(could not be filed — block on stderr)";

fn checkpoint_min_free_bytes() -> u64 {
    std::env::var("MAHBOT_CHECKPOINT_MIN_FREE_BYTES")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(DEFAULT_CHECKPOINT_MIN_FREE_BYTES)
}

fn available_free_bytes(path: &Path) -> u64 {
    crate::util::disk::free_and_capacity(path).map_or(0, |(free, _)| free)
}

/// True when the store's disk has enough free space for a TRUNCATE checkpoint. Below the threshold
/// only PASSIVE checkpoints run; the condition is logged (an actionable signal, never corruption).
fn truncate_allowed(root: &Path) -> bool {
    let min = checkpoint_min_free_bytes();
    if min == 0 {
        return true;
    }
    let free = available_free_bytes(root);
    let allowed = free >= min;
    if !allowed {
        warn!(
            free_bytes = free,
            min_free_bytes = min,
            "Free disk space below TRUNCATE checkpoint threshold — running PASSIVE only",
        );
    }
    allowed
}

#[derive(Debug, Clone, Copy)]
enum CheckpointPolicy {
    /// TRUNCATE every checkpoint (exit-time paths; the round releases the store's readers first,
    /// and a reader in flight can only make the attempt answer blocked → warn, not corruption).
    Truncate,
    PassiveCapped(u64),
}

impl CheckpointPolicy {
    fn periodic() -> Self {
        Self::PassiveCapped(WAL_CHECKPOINT_CAP_BYTES)
    }
}

/// Iterate all stores via [`crate::db::iter_checkpoint_stores`] and run an async operation on each
/// initialised store in parallel — the shared pattern behind both public entry points (via
/// [`checkpoint_stores`]); a store with no connection yet is silently skipped. The closure gets
/// `(&'static str, &'static Connection)` — the store name and its canonical connection — and
/// returns a future that completes the operation and logs the result. Each per-store operation is
/// wrapped in `catch_unwind` (per store, not around the whole loop), which on Tokio worker threads
/// covers the storage-layer panics that unwind through a poll, so one store cannot abort the
/// others.
async fn for_each_store<F, Fut>(op: F)
where
    F: Fn(&'static str, &'static crate::db::Connection) -> Fut,
    Fut: Future<Output = ()>,
{
    let futs: Vec<_> = crate::db::iter_checkpoint_stores()
        .filter_map(|(name, conn_opt)| {
            let conn = conn_opt?;
            let fut = AssertUnwindSafe(op(name, conn)).catch_unwind();
            Some(async move {
                if let Err(payload) = fut.await {
                    error!(
                        panic = %crate::util::panic_message(&*payload),
                        db = name,
                        "Store operation panicked — isolated to this store",
                    );
                }
            })
        })
        .collect();
    join_all(futs).await;
}

/// Checkpoint all Turso database stores before hard process termination: `std::process::exit(0)`
/// bypasses destructors, so WAL connections are never properly closed. Runs TRUNCATE checkpoints,
/// leaving the journal reclaimed for a clean handoff — why TRUNCATE is safe here and avoided by the
/// periodic loop is the module invariant above — downgraded to PASSIVE below the ENOSPC gate
/// (`truncate_allowed`). Stores never initialised are skipped; a panicking store operation is
/// isolated to that store (see [`for_each_store`]); an exit-round failure is filed durably
/// ([`record_store_failure`]) because the exit path can neither recover nor drain. The store list
/// is [`crate::db::iter_checkpoint_stores`]; periodic checkpointing is
/// [`periodic_checkpoint_and_verify`].
pub async fn checkpoint_all_databases() {
    checkpoint_stores(CheckpointRound::Exit).await;
}

/// One 10-minute hygiene round: the periodic inspection — WAL checkpoint and an independent
/// `quick_check` per store. PASSIVE below the WAL-size cap, TRUNCATE above it: TRUNCATE resets the
/// shared WAL frame index (the live-writer corruption vector) and is the only thing that shrinks
/// the WAL file (turso's own auto-checkpoint is PASSIVE-only). A round's attempts, the runtime FTS
/// repair after a failed or busy first attempt, and the genuine-failure-only stop are
/// [`periodic_checkpoint_inner`]'s.
pub async fn periodic_checkpoint_and_verify() {
    checkpoint_stores(CheckpointRound::Periodic).await;
}

/// Discriminates the two [`checkpoint_stores`] rounds: Periodic implies integrity verification and
/// the retry/recovery rule [`periodic_checkpoint_inner`] owns; Exit is the TRUNCATE exit-time path
/// and must never trigger recovery/shutdown (the process is already exiting).
#[derive(Clone, Copy)]
enum CheckpointRound {
    /// Exit-time round: TRUNCATE; a failure is recorded durably, never recovered.
    Exit,
    Periodic,
}

async fn checkpoint_stores(round: CheckpointRound) {
    let root = crate::config::CONFIG.try_storage_root();
    let truncate_gate =
        crate::util::with_block_in_place(|| root.as_deref().is_none_or(truncate_allowed));
    let policy = match round {
        CheckpointRound::Exit => CheckpointPolicy::Truncate,
        CheckpointRound::Periodic => CheckpointPolicy::periodic(),
    };
    for_each_store(|name, conn| {
        let root = root.clone();
        async move {
            // There is no external writer in single-process mode, so there is no coordination
            // identity to re-check and no structural-corruption class decides here: the checkpoint
            // is attempted and its failure logged like any other, the pre-shrink gate being the
            // only condition that withholds a reclaiming attempt. The only consumer of an
            // inspection is the periodic round's TRUNCATE-vs-PASSIVE cap (WAL size), which must be
            // STAT-ONLY (wal_guard's lock rule); the exit round needs no inspection at all.
            let truncate = match policy {
                // Exit-time TRUNCATE (self-update handoff / shutdown): the ENOSPC gate applies here
                // too, since a TRUNCATE that runs out of space mid-way is worse than the passive
                // compaction it skips. The handoff contract (release flock, spawn the replacement)
                // is unchanged; only the reclaimed-journal handoff is dropped — a hygiene nicety,
                // not a durability requirement (committed frames are fsync-durable at COMMIT).
                CheckpointPolicy::Truncate => truncate_gate,
                CheckpointPolicy::PassiveCapped(cap) => {
                    // PASSIVE while the WAL is absent/unmeasurable (an unresolvable root) or below
                    // the cap; TRUNCATE only above it. `truncate_gate` adds the free-space check
                    // for resolvable roots, moot when the inspection yields nothing.
                    root.as_deref()
                        .map(|r| {
                            let db_path = crate::db::store_db_path(r, name);
                            crate::db::wal_guard::wal_size(&db_path)
                        })
                        .is_some_and(|wal_size| wal_size > cap)
                        && truncate_gate
                }
            };
            match round {
                CheckpointRound::Exit => {
                    exit_checkpoint(name, conn, truncate, root.as_deref()).await;
                }
                CheckpointRound::Periodic => {
                    periodic_store_round(name, conn, truncate, root.as_deref()).await;
                }
            }
        }
    })
    .await;
}

/// The periodic round's integrity verification, independent of the checkpoint. No in-place action:
/// a round must not repair under live readers, so runtime-detected btree/index desync is recorded
/// durably and the store marked as owing a scan ([`record_integrity_failure`]) — the next start
/// runs that scan before its readers exist and clears the marker (see
/// [`crate::db::open_present_store`]), which is where the repair happens. The known FTS
/// count-mismatch false positive is filtered by the `quick_check` row scan.
async fn verify_integrity(name: &'static str, conn: &impl OwnConnection, root: Option<&Path>) {
    // The filtered problem list, not `quick_check()`: a condition the boot path leaves report-only
    // is tolerated here too, and only a check that cannot run or names actionable damage is
    // recorded.
    match conn.quick_check_problems().await {
        Ok(problems) if problems.is_empty() => {
            debug!(db = %name, "Database integrity check passed");
        }
        Ok(problems) if crate::db::is_tolerated_integrity_report(&problems) => {
            // A tolerated finding is neither filed nor a stop — but it must not be silent either.
            // `warn` deliberately: the signature may be a corruption report the boot path has not
            // learned yet, so it stays visible at a level operators watch, below a filed failure's
            // error.
            warn!(
                db = %name,
                problems = %problems.join("; "),
                "Database integrity check reported only tolerated findings — not recorded, not fatal",
            );
        }
        Ok(problems) => {
            record_integrity_failure(
                name,
                conn.db_path(),
                &anyhow::anyhow!("{}", problems.join("; ")),
                root,
            );
        }
        Err(e) => record_integrity_failure(name, conn.db_path(), &e, root),
    }
}

enum Attempted {
    Ran(anyhow::Result<CheckpointOutcome>),
    /// The pre-shrink gate refused the reclaiming checkpoint: none was issued (the gate said so
    /// loudly).
    ShrinkRefused,
}

/// One checkpoint attempt, panic-guarded: a panic is a failed attempt, never something that escapes
/// the round and leaves the service running on a store it has proven it cannot write.
async fn guarded_checkpoint(
    attempt: impl Future<Output = anyhow::Result<CheckpointOutcome>>,
) -> anyhow::Result<CheckpointOutcome> {
    match AssertUnwindSafe(attempt).catch_unwind().await {
        Ok(result) => result,
        Err(panic) => Err(anyhow::anyhow!(
            "checkpoint attempt panicked: {}",
            crate::util::panic_message(&*panic)
        )),
    }
}

/// One checkpoint attempt: the pre-shrink gate first when the attempt is reclaiming (see
/// [`crate::db::shrink_gate`]), then the engine's own call through the panic guard. Both rounds
/// issue every reclaiming checkpoint here, so a retry is gated exactly like the first attempt (the
/// boot repair site gates itself).
async fn checkpoint_attempt(
    name: &'static str,
    conn: &impl OwnConnection,
    truncate: bool,
    root: Option<&Path>,
) -> Attempted {
    if truncate && !shrink_gate::shrink_allowed(conn, name, root).await {
        return Attempted::ShrinkRefused;
    }
    Attempted::Ran(guarded_checkpoint(conn.checkpoint(truncate)).await)
}

/// The exit/self-update round's one attempt: one outcome, no retry, no drain, plus the step
/// releasing the store's readers first. A failure is filed durably — the process is going away, so
/// the record is the only place it can surface.
///
/// The readers go first (the writing connection is a handle that is never dropped, hence the
/// deliberate step): a reader still holding a position would make the reclaiming checkpoint answer
/// blocked, and one that does not fall idle in time is left to the runtime, the attempt answering
/// blocked — the warn this round reports, never a failure
/// ([`crate::db::checkpoint_cause::is_blocked_checkpoint`]).
///
/// The attempt is panic-guarded like the periodic round's ([`checkpoint_attempt`]), so a panic
/// becomes this round's error and reaches the durable record rather than only `for_each_store`'s
/// panic line.
async fn exit_checkpoint(
    name: &'static str,
    conn: &Connection,
    truncate: bool,
    root: Option<&Path>,
) {
    conn.release_readers().await;
    match checkpoint_attempt(name, conn, truncate, root).await {
        Attempted::ShrinkRefused => {}
        Attempted::Ran(Ok(o)) if o.is_complete() => {
            debug!(
                db = %name,
                log = o.log_frames,
                checkpointed = o.checkpointed_frames,
                "Database WAL checkpointed",
            );
        }
        Attempted::Ran(Ok(o)) => {
            warn!(
                db = %name,
                busy = o.busy,
                log = o.log_frames,
                checkpointed = o.checkpointed_frames,
                "Checkpoint busy or partial — WAL frames left uncheckpointed",
            );
        }
        Attempted::Ran(Err(e)) if checkpoint_cause::is_blocked_checkpoint(&e) => {
            // A blocked attempt: the engine's wordless row (busy, no frame counts) is refused by
            // the parse, so a compaction that could not run arrives as this error and the captured
            // reason says it was blocked rather than broken. A warn, no record: the exit round has
            // one attempt.
            warn!(error = %e, db = %name, "Checkpoint blocked — WAL left uncheckpointed");
        }
        Attempted::Ran(Err(e)) => {
            warn!(error = %e, db = %name, "Failed to checkpoint database WAL");
            record_store_failure(
                FailureKind::ExitCheckpointFailure,
                "exit checkpoint failure",
                name,
                conn.db_path(),
                &e,
                root,
            );
        }
    }
}

/// One store's periodic round: its upkeep runs on the store's own maintenance connection where the
/// store can give one, so ordinary work does not wait behind it. A store that cannot is still
/// upkept, on the writing connection (see the module header on what could not move).
async fn periodic_store_round(
    name: &'static str,
    conn: &Connection,
    truncate: bool,
    root: Option<&Path>,
) {
    match conn.maintenance().await {
        Ok(maintenance) => periodic_round(name, conn, &maintenance, truncate, root).await,
        Err(e) => {
            warn!(
                db = %name,
                error = %e,
                "The store could not give the round a maintenance connection — \
                 this round runs on the writing connection"
            );
            periodic_round(name, conn, conn, truncate, root).await;
        }
    }
}

async fn periodic_round(
    name: &'static str,
    writer: &Connection,
    upkeep: &impl OwnConnection,
    truncate: bool,
    root: Option<&Path>,
) {
    periodic_checkpoint(name, writer, upkeep, truncate, root).await;
    verify_integrity(name, upkeep, root).await;
}

/// The periodic round: the attempt loop over the engine's real checkpoint plus the failure-window
/// bookkeeping. `writer` is the writing connection, which owns the window's key and the runtime
/// search-index repair ([`periodic_checkpoint_inner`]); `upkeep` is the connection the compaction
/// and verification run on (see the module header); `root` is the storage root the report is
/// written under.
async fn periodic_checkpoint(
    name: &'static str,
    writer: &Connection,
    upkeep: &impl OwnConnection,
    truncate: bool,
    root: Option<&Path>,
) {
    periodic_checkpoint_inner(
        name,
        writer,
        upkeep,
        root,
        CHECKPOINT_RETRY_PAUSES,
        CHECKPOINT_FAILURE_WINDOW,
        || checkpoint_attempt(name, upkeep, truncate, root),
    )
    .await;
}

/// What has accumulated for one store since the failure that opened its window: the run of
/// consecutive failing rounds a genuine failure is decided on (see the module header). Closed by a
/// round that cures or ends without a genuine failure.
#[derive(Clone)]
struct FailureWindow {
    rounds: u64,
    attempts: u64,
    since: Instant,
    first_failure: String,
}

impl FailureWindow {
    fn extend(&mut self, attempts: u64) {
        self.rounds += 1;
        self.attempts += attempts;
    }

    fn elapsed(&self) -> Duration {
        self.since.elapsed()
    }

    /// True when the window has spanned BOTH floors — the only condition under which a genuine
    /// failure decides the stop. `span` is the round's span floor.
    fn exhausted(&self, span: Duration) -> bool {
        self.rounds >= CHECKPOINT_FAILURE_MIN_ROUNDS && self.elapsed() >= span
    }

    fn summary(&self) -> String {
        format!(
            "failure window: {} attempts (blocked and partial ones included) over {} consecutive \
             failing rounds, {:.1}s since the first failure",
            self.attempts,
            self.rounds,
            self.elapsed().as_secs_f64(),
        )
    }
}

/// Open failure windows, keyed by the failing store's own db path: unique per store file, so two
/// stores — or two tests' temp stores sharing store names — never share a window.
static FAILURE_WINDOWS: LazyLock<Mutex<HashMap<PathBuf, FailureWindow>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

fn failure_window_key(conn: &Connection) -> PathBuf {
    conn.db_path().to_path_buf()
}

/// Count one failing round for `key` and decide it in the same step, under one lock: the round
/// returns the window's state and whether it is exhausted, so no window is decided while another
/// round extends it. An exhausted window is spent and not put back, so its block is filed once.
/// `key` is by value because it goes back into the map unless the window is exhausted; `since` and
/// `first_failure` are the round's own first failure, kept only when this round opens the window;
/// `span` is the round's span floor, so a test can compress it. Deciding and filing are outside the
/// lock, which only lets two rounds of one store race there — the daemon runs one round per store
/// at a time.
fn extend_failure_window(
    key: PathBuf,
    attempts: u64,
    since: Instant,
    first_failure: &str,
    span: Duration,
) -> (FailureWindow, bool) {
    let mut windows = FAILURE_WINDOWS.lock().unwrap_poison();
    let mut window = windows.remove(&key).unwrap_or_else(|| FailureWindow {
        rounds: 0,
        attempts: 0,
        since,
        first_failure: first_failure.to_string(),
    });
    window.extend(attempts);
    let exhausted = window.exhausted(span);
    if !exhausted {
        windows.insert(key, window.clone());
    }
    (window, exhausted)
}

/// Drop the store's window when a round it was open for ends without a genuine failure, warning
/// with the cumulative facts it accumulated: a closed window is the whole trace a failure that did
/// not last leaves (only an exhausted window files a durable block). Borrows the key, unlike
/// [`extend_failure_window`]: a round that closes never puts a window back. A round a completion
/// cured closes its window through [`cure_failure_window`] instead, at DEBUG.
fn close_failure_window(name: &'static str, key: &Path, reason: &'static str) {
    let Some(window) = FAILURE_WINDOWS.lock().unwrap_poison().remove(key) else {
        return;
    };
    warn!(
        db = %name,
        window_attempts = window.attempts,
        window_rounds = window.rounds,
        elapsed_ms = window.elapsed().as_millis(),
        reason,
        "Checkpoint failure window closed — continuing",
    );
}

/// A completed checkpoint is the cure: drop the store's window if one is open. A completion that
/// followed a genuine failure — this round's or an earlier round's — is the routine heal the
/// retries exist for, so it is recorded at DEBUG, the level the per-attempt failures it cures are
/// recorded at; a plain healthy completion with nothing to cure is left entirely to the round's own
/// DEBUG line.
fn cure_failure_window(name: &'static str, key: &Path, round_failures: usize) {
    let Some(window) = FAILURE_WINDOWS.lock().unwrap_poison().remove(key) else {
        if round_failures > 0 {
            debug!(db = %name, round_failures, "Checkpoint completed on a retry");
        }
        return;
    };
    debug!(
        db = %name,
        round_failures,
        window_attempts = window.attempts,
        window_rounds = window.rounds,
        elapsed_ms = window.elapsed().as_millis(),
        "Checkpoint completed — failure window closed",
    );
}

/// The periodic round's decision table: its arms own what each engine answer means and
/// [`crate::db::shrink_gate`] owns what a refusal is.
///
/// `attempt` is a parameter because a genuinely failing engine checkpoint cannot be provoked in
/// this process — one serialised writing connection per store, and no fault injection into the
/// engine ([`crate::db::failure_record`]) — so the table takes each engine answer directly:
/// [`periodic_checkpoint`] is the single caller and always passes the gate + engine attempt. It,
/// and the two timing parameters — `retry_pauses`, the real pauses before the retries, and `span`,
/// how long a store's failure window must have been open — are the round's only seam: the tests
/// compress both, production passes the two constants. Nothing outside this module can reach it,
/// and its arms are the failure window's whole rule.
///
/// `conn` is the writing connection — the store's own, which owns the failure window's key and must
/// run the runtime search-index repair — and `upkeep` is the connection the round's own upkeep runs
/// on (see [`periodic_checkpoint`]), which is the one the terminal report's integrity probe is
/// taken through.
/// The attempt future is `Send` because the periodic round runs inside the process's spawned task
/// set.
#[expect(clippy::too_many_lines)] // one arm per engine answer, each owning its own window step, reads as one flow
async fn periodic_checkpoint_inner<'a, Fut>(
    name: &'static str,
    conn: &'a Connection,
    upkeep: &'a impl OwnConnection,
    root: Option<&Path>,
    retry_pauses: [Duration; CHECKPOINT_ATTEMPTS - 1],
    span: Duration,
    mut attempt: impl FnMut() -> Fut,
) where
    Fut: Future<Output = Attempted> + Send + 'a,
{
    let key = failure_window_key(conn);
    let mut failures: Vec<(usize, anyhow::Error)> = Vec::new();
    let mut repair: Option<TicketTitleFtsRuntimeRepair> = None;
    let mut attempts_made = 0u64;
    // When this round's first genuine failure was seen: the instant a window it opens dates from,
    // not the round's end.
    let mut first_failure_at: Option<Instant> = None;
    for attempt_no in 1..=CHECKPOINT_ATTEMPTS {
        match attempt().await {
            // A refusal is never an attempt: the gate recorded it and nothing was issued. It never
            // stops the service by itself, so with no genuine failure the round ends here and
            // closes the window — a round without a failure must not be counted as a failing one.
            Attempted::ShrinkRefused => {
                if failures.is_empty() {
                    close_failure_window(
                        name,
                        &key,
                        "round ended on a refused shrink with no failure",
                    );
                    return;
                }
                break;
            }
            // A completed checkpoint keeps the service serving, on any attempt and in any round:
            // this completion — never the repair's outcome — is what cures a failure, wherever it
            // was recorded.
            Attempted::Ran(Ok(o)) if o.is_complete() => {
                debug!(
                    db = %name,
                    log = o.log_frames,
                    checkpointed = o.checkpointed_frames,
                    "Database WAL checkpointed",
                );
                cure_failure_window(name, &key, failures.len());
                return;
            }
            // Not a completion, so a partially folded journal: normal — a reader (this process's
            // own reads included) capped how far the fold could go. The round does nothing: no
            // retry, no record, just an INFO line (the level the log store retains) — and with no
            // genuine failure pending it ends the round, closing any window an earlier round
            // opened. After a genuine failure the retries still run. An attempt the engine could
            // not run at all arrives as the error below, its row carrying no frame counts to parse.
            Attempted::Ran(Ok(o)) => {
                info!(
                    db = %name,
                    log = o.log_frames,
                    checkpointed = o.checkpointed_frames,
                    "Checkpoint folded the journal partially",
                );
                if failures.is_empty() {
                    close_failure_window(name, &key, "round folded partially with no failure");
                    return;
                }
            }
            // A blocked attempt: retried like any failure, told from a genuine pager error by the
            // reason it carries (see [`crate::db::checkpoint_cause`]). A store blocked through the
            // budget keeps serving with its journal unfolded — the accepted trade for never
            // stopping on busy-ness — so its WAL keeps growing until it unblocks.
            Attempted::Ran(Err(e)) if checkpoint_cause::is_blocked_checkpoint(&e) => {
                info!(attempt = attempt_no, error = %e, db = %name, "Checkpoint blocked — retrying");
            }
            // A genuine failure: kept for the report, retried after the pause, and — once the
            // window is exhausted — the reason the service stops. DEBUG: the round reports itself
            // once.
            Attempted::Ran(Err(e)) => {
                debug!(
                    attempt = attempt_no,
                    error = %e,
                    db = %name,
                    "Failed to checkpoint database WAL"
                );
                first_failure_at.get_or_insert_with(Instant::now);
                failures.push((attempt_no, e));
            }
        }
        attempts_made += 1;
        // The runtime FTS repair runs after a first attempt that failed or was answered busy; its
        // outcome is reported, never used to decide. A reader holding a position answers a TRUNCATE
        // checkpoint busy (the long-standing rule, unchanged), so more rounds reach this repair
        // than before readers existed — and each pays the repair's own reads on the writing
        // connection (a filtered quick_check scan plus a MATCH probe). Accepted rather than hidden:
        // a blocked round is exactly the round this recovery step is for.
        if attempt_no == 1 {
            repair = Some(crate::db::repair_ticket_title_fts_runtime(conn).await);
        }
        // Every path here leads to a retry (a completion and a lone partial fold return, a refusal
        // breaks), spaced in real time by the next schedule entry — never back to back against
        // unchanged in-memory engine state; the schedule's length is the retry count, so the last
        // attempt has no pause. The pause races the daemon's shutdown, so a round the shutdown or
        // drain cuts short decides nothing: the window is left as it was, and this round's failures
        // reach no window at all, a drain meaning the process is on its way out while a window is a
        // claim about one that keeps serving.
        if let Some(pause) = retry_pauses.get(attempt_no - 1).copied()
            && !crate::shutdown::sleep_or_shutdown_or_drain(pause).await
        {
            // This warning is the round's only record, so the failure it already made rides it as
            // the cause.
            let cause = failures.first().map(|(_, e)| format!("{e:#}"));
            warn!(
                db = %name,
                round_attempts = attempts_made,
                error = cause.as_deref(),
                "Checkpoint round cut short by the daemon's own shutdown — failure window not decided",
            );
            return;
        }
    }
    // The budget ran out with nothing but blocked/partial answers (a lone one returns above): not a
    // failure, nothing recorded — the next round tries again, and any open window closes here.
    if failures.is_empty() {
        info!(db = %name, "Checkpoint round ended without a completion — continuing");
        close_failure_window(name, &key, "round ended without a failure or a completion");
        return;
    }
    let (_, first) = failures
        .first()
        .expect("the window is only extended after a failed attempt");
    let first_failure = format!("{first:#}");
    let (window, exhausted) = extend_failure_window(
        key,
        attempts_made,
        first_failure_at.expect("a failed attempt set the round's first failure instant"),
        &first_failure,
        span,
    );
    // Not yet terminal: one failing round never stops a healthy service. This warning is the whole
    // record such a round leaves, carrying its first failure as the cause — the one the window is
    // dated from and the terminal block renders. The durable block is filed once, when the window
    // is exhausted and the stop decided.
    if !exhausted {
        warn!(
            db = %name,
            round_attempts = attempts_made,
            window_attempts = window.attempts,
            window_rounds = window.rounds,
            elapsed_ms = window.elapsed().as_millis(),
            error = %first_failure,
            "Genuine checkpoint failure with no completion — failure window not exhausted, continuing",
        );
        return;
    }
    // The window is exhausted: this is the stop. The report is written (synchronously) before the
    // drain, and the repair outcome has no say in it. Nothing restarts the process and the app
    // shows no reason of its own, so this record and the log line below are the only trace. Filed
    // once per condition ([`failure_record::record`]).
    let report = build_failure_report(name, &failures, repair.as_ref(), &window, upkeep).await;
    let pointer = failure_record::recorded_pointer(
        "checkpoint failure",
        failure_record::record(root, &report.render()),
    );
    error!(
        db = %name,
        record = pointer.as_deref().unwrap_or(BLOCK_ON_STDERR),
        window_attempts = window.attempts,
        window_rounds = window.rounds,
        elapsed_ms = window.elapsed().as_millis(),
        "Genuine checkpoint failure with no completion across the failure window — recorded, \
         initiating graceful shutdown",
    );
    crate::shutdown::drain_begin();
}

/// The common body of a per-store runtime failure report: the store, its db path, the reason, the
/// environment note and the artifact state — shared so the blocks cannot drift apart.
fn store_failure_report(
    kind: FailureKind,
    name: &'static str,
    e: &anyhow::Error,
    db_path: &Path,
) -> FailureReport {
    let report = FailureReport::new(kind)
        .store(name)
        .reason(format!("{e:#}"))
        .environment(crate::db::is_actionable_signal(e));
    with_store_file_state(report, db_path)
}

/// Add the store's db path and its stat-only artifact state — the `-wal` size from
/// [`crate::db::wal_guard::stat_size`], never a header read: wal_guard's lock rule puts one out of
/// reach in a process that holds the store; a failing stat is reported as not obtainable, the
/// spelling the pre-shrink gate's block uses. `db_path` is the file the failing connection has open
/// ([`Connection::db_path`]), so the record names the very file whose state it reports.
fn with_store_file_state(report: FailureReport, db_path: &Path) -> FailureReport {
    let wal_bytes = crate::db::wal_guard::stat_size(&crate::db::wal_path(db_path)).ok();
    report
        .db_path(db_path.to_path_buf())
        .extra(failure_record::artifact_state_line(wal_bytes))
}

fn record_store_failure(
    kind: FailureKind,
    what: &str,
    name: &'static str,
    db_path: &Path,
    e: &anyhow::Error,
    root: Option<&Path>,
) {
    let report = store_failure_report(kind, name, e, db_path);
    failure_record::record_and_point(root, what, &report);
}

static INTEGRITY_FAILURE_ROUNDS: RoundCounter = RoundCounter::new();

/// Record a failed periodic integrity check: the first failing round of a store files a
/// [`FailureKind::RuntimeIntegrityFailure`] block, every further round only warns; no drain and no
/// other behaviour change, filed once per condition ([`failure_record::record`]). The same call
/// marks the store as owing a scan ([`crate::db::wal_guard::note_integrity_scan_owed`]): the round
/// must not repair under live readers, so the next start repairs before its readers exist (see
/// `crate::db::open_present_store`).
fn record_integrity_failure(
    name: &'static str,
    db_path: &Path,
    e: &anyhow::Error,
    root: Option<&Path>,
) {
    let further_rounds = INTEGRITY_FAILURE_ROUNDS.prior_rounds(name);
    if further_rounds > 0 {
        warn!(
            error = %e,
            db = %name,
            further_rounds,
            "Database integrity check failed again — already recorded on its first failure",
        );
        return;
    }
    error!(error = %e, db = %name, "Database integrity check failed");
    record_store_failure(
        FailureKind::RuntimeIntegrityFailure,
        "runtime integrity failure",
        name,
        db_path,
        e,
        root,
    );
    crate::db::wal_guard::note_integrity_scan_owed(db_path);
}

/// Multi-line failure report for the genuine-failure terminal path. The engine's own reason travels
/// with each attempt's error when it reported one (attached by [`crate::db::wal_checkpoint`] via
/// [`crate::db::checkpoint_cause`]), so the report needs no fold-in. Every diagnostic is
/// best-effort — a failing OR panicking probe must never prevent the report or its write: the
/// `quick_check` probe is panic-guarded so a turso panic cannot escape to the outer
/// `for_each_store` `catch_unwind` (which would skip the drain and leave the service running on a
/// persistently failing checkpoint). The artifact state comes from the stat-only
/// [`crate::db::wal_guard::stat_size`] (wal_guard's lock rule: no header read), so it reports the
/// `-wal` size — or the shared not-obtainable line when that stat fails — and deliberately no
/// corruption class, which the lock rule puts out of reach; the `quick_check` section carries the
/// integrity detail. `upkeep` is the connection the round's upkeep runs on — the terminal path is
/// still the round, so its probe is taken there too, off the writing connection (see
/// [`periodic_checkpoint`]).
async fn build_failure_report(
    name: &'static str,
    failures: &[(usize, anyhow::Error)],
    repair: Option<&TicketTitleFtsRuntimeRepair>,
    window: &FailureWindow,
    upkeep: &impl OwnConnection,
) -> FailureReport {
    // The checkpoint error is the report's reason, rendered as its own long-standing `checkpoint
    // error:` line rather than a `reason:` line; each further attempt's error follows as its own
    // `attempt N error:` line, N being the attempt that produced it (busy-only or partially folding
    // attempts leave a gap, deliberately). That first line is the round's FIRST genuine failure and
    // keeps its shape: an attempt answered busy before it leaves no line to carry a number.
    let mut report = FailureReport::new(FailureKind::CheckpointFailure)
        .store(name)
        .environment(
            failures
                .iter()
                .any(|(_, e)| crate::db::is_actionable_signal(e)),
        );
    // Built only after the attempts loop ended with a genuine failure recorded, the repair having
    // run by then — so both are present by construction, not defensively.
    let (_, first) = failures
        .first()
        .expect("a failure report is built only after a failed attempt");
    let cause = format!("{first:#}");
    report = report.extra(format!("checkpoint error: {cause}"));
    for (attempt_no, e) in failures.iter().skip(1) {
        report = report.extra(format!("attempt {attempt_no} error: {e:#}"));
    }
    // The window's own cause and cumulative facts: this block is the only record of the earlier
    // failing rounds (they warn only), and what tells a reader whether the failure was transient or
    // persistent. The opening cause is carried only when it differs from this round's — usually the
    // same chain, a duplicate buying nothing. The retry policy's stated limit belongs with the
    // facts.
    if window.first_failure != cause {
        report = report.extra(format!(
            "window first failure error: {}",
            window.first_failure
        ));
    }
    report = report.extra(window.summary());
    report = report.extra(
        "retry policy: a transient engine refusal cannot be told from a persistent one except by \
         whether a later attempt succeeds — a persistent refusal exhausts this window and the \
         service still stops, by design",
    );
    let repair = repair.expect("the round runs the repair before it can report");
    report = report.extra(format!("repair outcome: {}", repair.summary()));
    report = report.extra(
        match AssertUnwindSafe(upkeep.quick_check_problems())
            .catch_unwind()
            .await
        {
            Ok(Ok(problems)) if problems.is_empty() => "quick_check: ok".to_string(),
            Ok(Ok(problems)) => format!("quick_check problems: {}", problems.join("; ")),
            Ok(Err(e)) => format!("quick_check error: {e:#}"),
            Err(_) => "quick_check: probe panicked".to_string(),
        },
    );
    with_store_file_state(report, upkeep.db_path())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::checkpoint_cause;
    use crate::db::test_support::{
        build_empty_main_file_store, build_zero_page_count_store, build_zero_page_count_wal_store,
        fixture_rows, foreign_client_is_refused, fts_corruption_ddl, insert_fts_ticket, page_count,
    };
    use crate::db::wal_guard::{ShapeDefect, StoreShape};

    #[tokio::test]
    async fn noop_when_no_stores() {
        checkpoint_all_databases().await;
        periodic_checkpoint_and_verify().await;
    }

    async fn temp_store(name: &'static str) -> (tempfile::TempDir, Connection) {
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = crate::db::open_with_schema(
            &crate::db::store_db_path(tmp.path(), name),
            "CREATE TABLE plain (id INTEGER PRIMARY KEY);",
        )
        .await
        .unwrap();
        (tmp, conn)
    }

    async fn a_store_with_a_corrupt_fts_index(root: &Path) -> Connection {
        let conn = crate::db::open_consolidated_store(root).await.unwrap();
        insert_fts_ticket(&conn, "t-1", "Important bug fix one").await;
        insert_fts_ticket(&conn, "t-2", "Another relevant thing").await;
        conn.execute_batch(&fts_corruption_ddl()).await.unwrap();
        conn
    }

    /// The error a blocked checkpoint reaches the round as: the engine's own busy sentence — taken
    /// from [`checkpoint_cause::BLOCKED_REASON`], the constant the classifier matches, so the two
    /// cannot drift — attached as [`checkpoint_cause::CauseSink::attach`] attaches it. The capture
    /// that produces the sentence is driven for real in `checkpoint_cause`'s own tests.
    fn blocked_checkpoint_error() -> anyhow::Error {
        anyhow::anyhow!("Unexpected result from PRAGMA wal_checkpoint").context(format!(
            "engine cause: {}",
            checkpoint_cause::BLOCKED_REASON
        ))
    }

    /// The retry pauses the round's tests use: none, so retries are instant and the production
    /// schedule ([`CHECKPOINT_RETRY_PAUSES`]) is never waited out.
    const TEST_PAUSES: [Duration; CHECKPOINT_ATTEMPTS - 1] =
        [Duration::ZERO; CHECKPOINT_ATTEMPTS - 1];

    fn window_open(conn: &Connection) -> bool {
        FAILURE_WINDOWS
            .lock()
            .unwrap_poison()
            .contains_key(&failure_window_key(conn))
    }

    fn window_rounds() -> usize {
        usize::try_from(CHECKPOINT_FAILURE_MIN_ROUNDS)
            .expect("the failure window's round floor fits a usize")
    }

    async fn failing_rounds(
        name: &'static str,
        conn: &Connection,
        root: &Path,
        rounds: usize,
        error: &str,
        retry_pauses: [Duration; CHECKPOINT_ATTEMPTS - 1],
        span: Duration,
    ) -> usize {
        let error = error.to_string();
        rounds_with_answers(name, conn, root, rounds, retry_pauses, span, move |_| {
            let error = error.clone();
            async move { Attempted::Ran(Err(anyhow::anyhow!(error))) }
        })
        .await
    }

    /// Run `rounds` periodic rounds, each attempt answered by `answer(attempt_no)` — how every test
    /// that varies the answer per attempt drives its rounds — and return the attempts made. The
    /// rounds use the writing connection as upkeep too, what a round does when the store cannot
    /// give a second one ([`checkpoint_stores`]), because what they drive is the decision table,
    /// not that connection.
    async fn rounds_with_answers<A, Fut>(
        name: &'static str,
        conn: &Connection,
        root: &Path,
        rounds: usize,
        retry_pauses: [Duration; CHECKPOINT_ATTEMPTS - 1],
        span: Duration,
        mut answer: A,
    ) -> usize
    where
        A: FnMut(usize) -> Fut,
        Fut: Future<Output = Attempted> + Send,
    {
        let mut attempts = 0usize;
        for _ in 0..rounds {
            let mut attempt_no = 0usize;
            periodic_checkpoint_inner(name, conn, conn, Some(root), retry_pauses, span, || {
                attempt_no += 1;
                attempts += 1;
                answer(attempt_no)
            })
            .await;
        }
        attempts
    }

    /// An exit-round checkpoint failure is recorded durably — the exit path can neither recover nor
    /// drain, so that block is its only surface — with the stat-only artifact state, and the
    /// environment note when the cause is an external condition.
    #[tokio::test]
    async fn exit_checkpoint_failure_is_recorded() {
        let (tmp, conn) = temp_store("core").await;
        record_store_failure(
            FailureKind::ExitCheckpointFailure,
            "exit checkpoint failure",
            "core",
            conn.db_path(),
            &anyhow::anyhow!("no space left on device"),
            Some(tmp.path()),
        );
        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        for needle in [
            "MahBot exit checkpoint failure",
            "store: core",
            failure_record::ENVIRONMENT_CAUSE,
            "reason: no space left on device",
            "artifact state: wal_size=",
        ] {
            assert!(
                body.contains(needle),
                "error.log must contain {needle:?}: {body}"
            );
        }
        assert!(
            body.contains(&format!("db path: {}", conn.db_path().display())),
            "the block must name the file the connection has open: {body}"
        );
    }

    #[tokio::test]
    async fn the_failure_record_carries_the_engines_own_reason() {
        use tracing_subscriber::layer::SubscriberExt;

        let _guard = tracing::subscriber::set_default(
            tracing_subscriber::registry().with(checkpoint_cause::CauseCaptureLayer),
        );
        let (tmp, conn) = temp_store("core").await;
        let sink = checkpoint_cause::CauseSink::new();
        sink.scoped(async {
            tracing::debug!(
                target: "turso_core::vdbe::execute",
                "PRAGMA wal_checkpoint failed: engine-side detail"
            );
        })
        .await;
        let e = sink.attach(anyhow::anyhow!(
            "Unexpected result from PRAGMA wal_checkpoint"
        ));
        record_store_failure(
            FailureKind::ExitCheckpointFailure,
            "exit checkpoint failure",
            "core",
            conn.db_path(),
            &e,
            Some(tmp.path()),
        );

        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.contains(
                "reason: engine cause: PRAGMA wal_checkpoint failed: engine-side detail: \
                 Unexpected result from PRAGMA wal_checkpoint"
            ),
            "the reason line must be the full chain — the engine's own reason and the \
             product's text as separate links: {body}"
        );
    }

    #[tokio::test]
    async fn integrity_failure_is_recorded_once_then_counted() {
        let name = "integrity_probe";
        let (tmp, conn) = temp_store(name).await;
        for _ in 0..3 {
            record_integrity_failure(
                name,
                conn.db_path(),
                &anyhow::anyhow!("the integrity check cannot run"),
                Some(tmp.path()),
            );
        }
        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            crate::db::wal_guard::integrity_scan_owed(conn.db_path()),
            "a recorded runtime integrity failure must mark the store as owing a scan"
        );
        assert_eq!(
            body.matches("MahBot runtime integrity failure").count(),
            1,
            "only the first failing round may file a block: {body}"
        );
        for needle in [
            "store: integrity_probe",
            "db path:",
            "reason: the integrity check cannot run",
        ] {
            assert!(
                body.contains(needle),
                "error.log must contain {needle:?}: {body}"
            );
        }
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn failed_checkpoint_with_broken_fts_repairs_and_retries() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = a_store_with_a_corrupt_fts_index(tmp.path()).await;
        assert!(
            !crate::db::is_fts_index(&conn, crate::db::TICKETS_FTS_INDEX_NAME).await,
            "index must be a btree before the recovery"
        );
        let before: i64 = conn
            .query_row("SELECT COUNT(*) FROM tickets", (), |r| r.get::<i64>(0))
            .await
            .unwrap();

        // The first attempt fails; the repair runs between it and the second, which is a real
        // checkpoint (TRUNCATE, single-writer test env).
        let mut attempt_no = 0;
        periodic_checkpoint_inner(
            "core",
            &conn,
            &conn,
            Some(tmp.path()),
            TEST_PAUSES,
            Duration::ZERO,
            || {
                attempt_no += 1;
                let n = attempt_no;
                let conn = conn.clone();
                async move {
                    Attempted::Ran(if n == 1 {
                        Err(anyhow::anyhow!("injected checkpoint failure"))
                    } else {
                        conn.checkpoint_ungated().await
                    })
                }
            },
        )
        .await;
        assert_eq!(
            attempt_no, 2,
            "the failed first attempt must be retried exactly once after the repair"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "a checkpoint completed by the retry must not begin the drain"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a checkpoint completed by the retry must not file a failure block"
        );

        assert!(
            crate::db::is_fts_index(&conn, crate::db::TICKETS_FTS_INDEX_NAME).await,
            "FTS index must be restored after the recovery"
        );
        let matched: String = conn
            .query_row(
                "SELECT id FROM tickets WHERE title MATCH ?1 LIMIT 1",
                crate::db::params![crate::db::sanitize_fts_query("Important bug fix one")],
                |r| r.get::<String>(0),
            )
            .await
            .unwrap();
        assert_eq!(
            matched, "t-1",
            "MATCH must find the known ticket after the rebuild"
        );
        let after: i64 = conn
            .query_row("SELECT COUNT(*) FROM tickets", (), |r| r.get::<i64>(0))
            .await
            .unwrap();
        assert_eq!(
            after, before,
            "ticket rows must be untouched by the FTS rebuild"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_rebuilt_index_does_not_exempt_a_persistently_failing_round() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = a_store_with_a_corrupt_fts_index(tmp.path()).await;
        let store = &conn;

        let rounds = window_rounds();
        let total_attempts = rounds_with_answers(
            "core",
            store,
            tmp.path(),
            rounds,
            TEST_PAUSES,
            Duration::ZERO,
            |attempt_no| async move {
                if attempt_no == 1 {
                    store.execute_batch(&fts_corruption_ddl()).await.unwrap();
                    return Attempted::Ran(Err(anyhow::anyhow!("injected checkpoint failure")));
                }
                Attempted::Ran(Err(anyhow::anyhow!("injected persistent failure")))
            },
        )
        .await;
        assert_eq!(
            total_attempts,
            CHECKPOINT_ATTEMPTS * rounds,
            "a persistent failure must run every attempt of every round before the window decides"
        );

        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.contains("injected checkpoint failure"),
            "the original checkpoint error must be in the report: {body}"
        );
        assert!(
            body.contains("injected persistent failure"),
            "the later attempts' errors must be in the report: {body}"
        );
        assert!(
            body.contains("repair outcome: rebuilt after detection"),
            "the report must name what the round's repair returned: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "a rebuilt index must not exempt a round in which no attempt completed a checkpoint"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_rebuilt_index_does_not_exempt_a_partial_retry() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = a_store_with_a_corrupt_fts_index(tmp.path()).await;

        let rounds = window_rounds();
        let total_attempts = rounds_with_answers(
            "core",
            &conn,
            tmp.path(),
            rounds,
            TEST_PAUSES,
            Duration::ZERO,
            |attempt_no| {
                let answer = if attempt_no == 1 {
                    Attempted::Ran(Err(anyhow::anyhow!("injected checkpoint failure")))
                } else {
                    // A partially folded journal: not a completion, not a failure.
                    Attempted::Ran(Ok(CheckpointOutcome {
                        busy: false,
                        log_frames: 5,
                        checkpointed_frames: 1,
                    }))
                };
                async move { answer }
            },
        )
        .await;

        assert_eq!(
            total_attempts,
            CHECKPOINT_ATTEMPTS * rounds,
            "a partially folded attempt must not cut a failing round's budget short"
        );
        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.contains("checkpoint error: injected checkpoint failure"),
            "the genuine failure must still be recorded with its real cause: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "a rebuilt index must not exempt a round in which a genuine failure had no completion"
        );
        crate::shutdown::drain_clear();
    }

    async fn a_round_cured_by_its_last_attempt(conn: &Connection, root: &Path) {
        let mut attempt_no = 0;
        periodic_checkpoint_inner(
            "core",
            conn,
            conn,
            Some(root),
            TEST_PAUSES,
            Duration::ZERO,
            || {
                attempt_no += 1;
                let n = attempt_no;
                async move {
                    Attempted::Ran(if n == CHECKPOINT_ATTEMPTS {
                        Ok(CheckpointOutcome {
                            busy: false,
                            log_frames: 0,
                            checkpointed_frames: 0,
                        })
                    } else {
                        Err(anyhow::anyhow!("injected checkpoint failure"))
                    })
                }
            },
        )
        .await;

        assert_eq!(
            attempt_no, CHECKPOINT_ATTEMPTS,
            "a completion on the last attempt leaves no attempt to follow it"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "a completed checkpoint after a failure must keep the service serving"
        );
        assert!(
            !root.join("error.log").exists(),
            "a round cured by its own retry must not file a failure block"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_completed_retry_keeps_serving_whatever_the_repair_returned() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        assert!(
            matches!(
                crate::db::repair_ticket_title_fts_runtime(&conn).await,
                TicketTitleFtsRuntimeRepair::NotApplicable
            ),
            "this store must classify as a store with nothing to rebuild"
        );

        a_round_cured_by_its_last_attempt(&conn, tmp.path()).await;
    }

    /// A repair that fails outright decides nothing either: this store's ticket-title index cannot
    /// be rebuilt — its `tickets` table has no title column, so the MATCH probe reads it as corrupt
    /// and the CREATE INDEX cannot succeed — and the round is cured by its own retry all the same.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_failed_repair_does_not_stop_a_round_its_retry_completes() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().unwrap();
        let conn = crate::db::open_with_schema(
            &crate::db::store_db_path(tmp.path(), "core"),
            "CREATE TABLE tickets (id INTEGER PRIMARY KEY);\
             CREATE INDEX idx_tickets_title_fts ON tickets (id);",
        )
        .await
        .unwrap();
        // The premise, asserted not assumed: this store makes the repair fail, so the round's
        // outcome is the `Failed` one (a rollback, so the state the round then sees is unchanged).
        assert!(
            matches!(
                crate::db::repair_ticket_title_fts_runtime(&conn).await,
                TicketTitleFtsRuntimeRepair::Failed(_)
            ),
            "this store must classify as a store whose repair fails"
        );

        a_round_cured_by_its_last_attempt(&conn, tmp.path()).await;
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn checkpoint_failure_without_fts_store_writes_error_log_and_drains() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let rounds = window_rounds();
        let attempts = failing_rounds(
            "core",
            &conn,
            tmp.path(),
            rounds,
            "no space left on device",
            TEST_PAUSES,
            Duration::ZERO,
        )
        .await;
        assert_eq!(
            attempts,
            CHECKPOINT_ATTEMPTS * rounds,
            "every store gets every attempt of every failing round, indexed or not"
        );

        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.contains("checkpoint error: no space left on device"),
            "the checkpoint error must be in the report: {body}"
        );
        assert!(
            body.contains(failure_record::ENVIRONMENT_CAUSE),
            "a resource-caused checkpoint failure must be marked environment-caused: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "persistent failure must begin the graceful drain"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_healthy_index_store_gets_every_attempt_and_stops() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let conn = crate::db::open_consolidated_store(tmp.path())
            .await
            .expect("open the consolidated store");
        insert_fts_ticket(&conn, "t-1", "Important bug fix one").await;

        let rounds = window_rounds();
        let attempts = failing_rounds(
            "core",
            &conn,
            tmp.path(),
            rounds,
            "injected checkpoint failure",
            TEST_PAUSES,
            Duration::ZERO,
        )
        .await;
        assert_eq!(
            attempts,
            CHECKPOINT_ATTEMPTS * rounds,
            "an indexed store gets every attempt of every failing round too",
        );

        let body = std::fs::read_to_string(tmp.path().join("error.log")).expect("error.log");
        assert!(
            body.contains("repair outcome: healthy"),
            "the report must name what the round's repair returned: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "a persistent failure on an indexed store must still stop the service",
        );
        crate::shutdown::drain_clear();
    }

    /// The round spaces its retries by the schedule it was handed, one entry per retry:
    /// [`CHECKPOINT_ATTEMPTS`] attempts with the whole production schedule
    /// ([`CHECKPOINT_RETRY_PAUSES`]) spent between them, scaled down to milliseconds so the wait is
    /// real but cheap — elapsed time is the only way to observe the spacing without a hook, and a
    /// round spending none finishes far short.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_failing_round_spaces_its_retries_by_the_production_schedule() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        let schedule = CHECKPOINT_RETRY_PAUSES.map(|pause| pause / 1000);
        let started = tokio::time::Instant::now();

        let attempts = failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            schedule,
            Duration::ZERO,
        )
        .await;

        assert_eq!(
            attempts, CHECKPOINT_ATTEMPTS,
            "a failing round runs every attempt the schedule has pauses for",
        );
        assert!(
            started.elapsed() >= schedule.into_iter().sum::<Duration>(),
            "the round must spend the schedule's own pause before each retry",
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_partially_folded_journal_is_normal_and_ends_the_round() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let mut attempts = 0usize;
        periodic_checkpoint_inner(
            "core",
            &conn,
            &conn,
            Some(tmp.path()),
            TEST_PAUSES,
            Duration::ZERO,
            || {
                attempts += 1;
                async {
                    Attempted::Ran(Ok(CheckpointOutcome {
                        busy: false,
                        log_frames: 5,
                        checkpointed_frames: 1,
                    }))
                }
            },
        )
        .await;

        assert_eq!(
            attempts, 1,
            "a partially folded journal must not be retried"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "a partially folded journal must not begin the drain"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a partially folded journal must not file a failure block"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_busy_store_is_retried_and_a_still_busy_round_keeps_serving() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let mut attempts = 0usize;
        periodic_checkpoint_inner(
            "core",
            &conn,
            &conn,
            Some(tmp.path()),
            TEST_PAUSES,
            Duration::ZERO,
            || {
                attempts += 1;
                async { Attempted::Ran(Err(blocked_checkpoint_error())) }
            },
        )
        .await;

        assert_eq!(
            attempts, CHECKPOINT_ATTEMPTS,
            "a blocked checkpoint must be retried up to the round's budget"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "a round that stayed busy must keep the service serving"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a round that stayed busy must not file a failure block"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_busy_attempt_before_a_failure_leaves_the_cause_line_unmarked() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        rounds_with_answers(
            "core",
            &conn,
            tmp.path(),
            window_rounds(),
            TEST_PAUSES,
            Duration::ZERO,
            |attempt_no| {
                let answer = if attempt_no == 1 {
                    Attempted::Ran(Err(blocked_checkpoint_error()))
                } else {
                    Attempted::Ran(Err(anyhow::anyhow!("injected checkpoint failure")))
                };
                async move { answer }
            },
        )
        .await;

        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.lines()
                .any(|line| line == "checkpoint error: injected checkpoint failure"),
            "a busy first attempt leaves no line, so the cause line stays unmarked: {body}"
        );
        assert!(
            body.contains("attempt 3 error: injected checkpoint failure"),
            "the later failure must keep its own labelled line: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "a genuine failure with no completion must stop the service"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_failure_followed_by_busy_attempts_still_stops() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let rounds = window_rounds();
        let attempts = rounds_with_answers(
            "core",
            &conn,
            tmp.path(),
            rounds,
            TEST_PAUSES,
            Duration::ZERO,
            |attempt_no| {
                let answer = if attempt_no == 1 {
                    Attempted::Ran(Err(anyhow::anyhow!("injected checkpoint failure")))
                } else {
                    Attempted::Ran(Err(blocked_checkpoint_error()))
                };
                async move { answer }
            },
        )
        .await;

        assert_eq!(
            attempts,
            CHECKPOINT_ATTEMPTS * rounds,
            "a busy attempt must not cut a genuine failure's budget short — every attempt of every \
             failing round must run"
        );
        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.contains("checkpoint error: injected checkpoint failure"),
            "the round's real failure must be the report's reason: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "a genuine failure must still stop the service despite later busy attempts"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn the_report_numbers_each_failure_after_the_first() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        rounds_with_answers(
            "core",
            &conn,
            tmp.path(),
            window_rounds(),
            TEST_PAUSES,
            Duration::ZERO,
            |attempt_no| {
                let answer = match attempt_no {
                    1 => Attempted::Ran(Err(anyhow::anyhow!("injected first failure"))),
                    2 => Attempted::Ran(Err(blocked_checkpoint_error())),
                    _ => Attempted::Ran(Err(anyhow::anyhow!("injected third failure"))),
                };
                async move { answer }
            },
        )
        .await;

        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.lines()
                .any(|line| line == "checkpoint error: injected first failure"),
            "attempt 1's cause line keeps its long-standing byte-for-byte shape: {body}"
        );
        assert!(
            body.contains("attempt 3 error: injected third failure"),
            "the later error must carry the attempt that produced it: {body}"
        );
        assert!(
            !body.contains("attempt 2 error:"),
            "the busy/partial attempt produced no error to record: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "the accumulated failure must still stop the service"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_panicking_attempt_is_a_failed_attempt_and_stops_after_the_window() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let rounds = window_rounds();
        let attempts = rounds_with_answers(
            "core",
            &conn,
            tmp.path(),
            rounds,
            TEST_PAUSES,
            Duration::ZERO,
            |_| async {
                Attempted::Ran(guarded_checkpoint(async { panic!("injected attempt panic") }).await)
            },
        )
        .await;
        assert_eq!(
            attempts,
            CHECKPOINT_ATTEMPTS * rounds,
            "a panic is a failed attempt, so every attempt of every round must run"
        );
        assert!(
            crate::shutdown::is_draining(),
            "a panic must not escape the round without beginning the drain"
        );
        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.contains("checkpoint attempt panicked"),
            "the panic must be filed as the failed attempt's reason: {body}"
        );
        assert!(
            body.contains("injected attempt panic"),
            "the panicking attempt's message must be in the report: {body}"
        );
        crate::shutdown::drain_clear();
    }

    /// A refused shrink is neither a failure nor an attempt: the round makes exactly one attempt (a
    /// refusal is not retried) and never reaches the failure/stop machinery. The store's bytes,
    /// verdict and lock are the end-to-end evidence, which drive this same round.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_refused_shrink_is_not_a_failure_and_not_an_attempt() {
        crate::shutdown::drain_clear();
        // The gate files its refusal block on the first refusal for a store file in this process
        // (the count is process-global but keyed by the file); this test's temp dir makes the file
        // unique.
        let name = "refused_shrink_probe";
        let tmp = tempfile::TempDir::new().unwrap();
        let db_path = crate::db::store_db_path(tmp.path(), name);
        build_zero_page_count_store(&db_path).await;
        let conn = Connection::open(&db_path)
            .await
            .expect("open the fixture store");
        let maintenance = conn
            .maintenance()
            .await
            .expect("open the store's maintenance connection");
        let path = tmp.path();

        let mut attempts = 0usize;
        periodic_checkpoint_inner(
            name,
            &conn,
            &maintenance,
            Some(path),
            TEST_PAUSES,
            Duration::ZERO,
            || {
                attempts += 1;
                checkpoint_attempt(name, &maintenance, true, Some(path))
            },
        )
        .await;

        assert_eq!(attempts, 1, "a refusal must not be retried");
        let body = std::fs::read_to_string(tmp.path().join("error.log"))
            .expect("the refusal must be filed in the round's root");
        assert!(
            body.contains("MahBot store shrink refused"),
            "the gate must refuse a shrink on a zero-page-count store and record it: {body}"
        );
        assert!(
            !body.contains("MahBot checkpoint failure"),
            "a refused shrink must not file a checkpoint failure: {body}"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "a refused shrink must not begin the drain"
        );
    }

    /// The exit/self-update round is gated exactly like the periodic one, and its refusal is
    /// recorded where the ordinary log may already be stopping: no reclaiming checkpoint is issued,
    /// and it is never filed as the exit round's checkpoint failure — a store the gate protected is
    /// not one it could not write.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn an_exit_round_refusal_is_recorded_and_is_not_an_exit_failure() {
        crate::shutdown::drain_clear();
        let name = "exit_refused_shrink_probe";
        let tmp = tempfile::TempDir::new().unwrap();
        let db_path = crate::db::store_db_path(tmp.path(), name);
        build_zero_page_count_store(&db_path).await;
        let conn = Connection::open(&db_path)
            .await
            .expect("open the fixture store");
        let before = std::fs::read(&db_path).unwrap();

        exit_checkpoint(name, &conn, true, Some(tmp.path())).await;

        let body = std::fs::read_to_string(tmp.path().join("error.log"))
            .expect("the refusal must be filed in the round's root");
        assert!(
            body.contains("MahBot store shrink refused"),
            "the exit round must record a refused shrink: {body}"
        );
        assert!(
            !body.contains("MahBot exit checkpoint failure"),
            "a refused shrink is not an exit-round checkpoint failure: {body}"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "the exit round never drains — the process is already exiting"
        );
        assert_eq!(
            std::fs::read(&db_path).unwrap(),
            before,
            "the refused reclaiming checkpoint must not shrink the store"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_refusal_on_a_retry_still_stops_on_the_rounds_real_failure() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let rounds = window_rounds();
        let attempts = rounds_with_answers(
            "core",
            &conn,
            tmp.path(),
            rounds,
            TEST_PAUSES,
            Duration::ZERO,
            |attempt_no| {
                let answer = if attempt_no == 1 {
                    Attempted::Ran(Err(anyhow::anyhow!("injected checkpoint failure")))
                } else {
                    Attempted::ShrinkRefused
                };
                async move { answer }
            },
        )
        .await;
        assert_eq!(
            attempts,
            2 * rounds,
            "every failing round must stop at the refusal instead of retrying forever — the total \
             is the failure and the refusal of each round"
        );
        let body = std::fs::read_to_string(tmp.path().join("error.log")).unwrap();
        assert!(
            body.contains("checkpoint error: injected checkpoint failure"),
            "the report's reason must be the round's real failure: {body}"
        );
        assert!(
            body.contains("MahBot checkpoint failure"),
            "the round's stop must be filed as a checkpoint failure — a refusal is \
             not one and is never written as one: {body}"
        );
        assert!(
            crate::shutdown::is_draining(),
            "the round's real failure must still stop the service"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_single_failing_round_warns_and_never_stops() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let attempts = failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            TEST_PAUSES,
            Duration::ZERO,
        )
        .await;

        assert_eq!(
            attempts, CHECKPOINT_ATTEMPTS,
            "one failing round must still make its whole attempt budget"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "one failing round must never stop the service"
        );
        assert!(
            window_open(&conn),
            "one failing round must open the store's failure window"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a window that is not exhausted must file no failure block"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn the_second_consecutive_failing_round_stops_with_the_windows_cumulative_facts() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;

        let rounds = window_rounds();
        let attempts = failing_rounds(
            "core",
            &conn,
            tmp.path(),
            rounds,
            "injected checkpoint failure",
            TEST_PAUSES,
            Duration::ZERO,
        )
        .await;

        assert_eq!(
            attempts,
            CHECKPOINT_ATTEMPTS * rounds,
            "a persistent failure must run every attempt of every round before the window decides"
        );
        assert!(
            crate::shutdown::is_draining(),
            "an exhausted window must stop the service"
        );

        let body = std::fs::read_to_string(tmp.path().join("error.log")).expect("error.log");
        for needle in [
            "MahBot checkpoint failure",
            "checkpoint error: injected checkpoint failure",
            "retry policy:",
        ] {
            assert!(
                body.contains(needle),
                "error.log must contain {needle:?}: {body}"
            );
        }
        assert!(
            !body.contains("window first failure error:"),
            "the opening cause is not repeated when it is the deciding round's own: {body}"
        );
        let summary = format!(
            "failure window: {} attempts (blocked and partial ones included) over {} consecutive \
             failing rounds",
            CHECKPOINT_ATTEMPTS * rounds,
            rounds,
        );
        assert!(
            body.contains(&summary),
            "the record must carry the window's cumulative attempts and rounds — {summary:?}: {body}"
        );
        assert!(
            !window_open(&conn),
            "the exhausted window is spent: it must not be left for a later round to re-file"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn the_window_records_the_cause_that_opened_it() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        let (retry_pauses, span) = (TEST_PAUSES, Duration::ZERO);

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected first failure",
            retry_pauses,
            span,
        )
        .await;
        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected second failure",
            retry_pauses,
            span,
        )
        .await;

        assert!(
            crate::shutdown::is_draining(),
            "the exhausted window must stop the service"
        );
        let body = std::fs::read_to_string(tmp.path().join("error.log")).expect("error.log");
        for needle in [
            "checkpoint error: injected second failure",
            "window first failure error: injected first failure",
        ] {
            assert!(
                body.contains(needle),
                "error.log must contain {needle:?}: {body}"
            );
        }
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_completed_checkpoint_closes_the_window_and_the_next_failure_starts_a_new_one() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        let (retry_pauses, span) = (TEST_PAUSES, Duration::ZERO);

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            retry_pauses,
            span,
        )
        .await;
        assert!(
            window_open(&conn),
            "the failing round must open the store's window"
        );

        periodic_checkpoint_inner(
            "core",
            &conn,
            &conn,
            Some(tmp.path()),
            retry_pauses,
            span,
            || {
                let conn = conn.clone();
                async move { Attempted::Ran(conn.checkpoint_ungated().await) }
            },
        )
        .await;
        assert!(
            !window_open(&conn),
            "a completed checkpoint must close the window"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "a completion must keep the service serving"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a completion must not file a failure block"
        );

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            retry_pauses,
            span,
        )
        .await;
        assert!(
            window_open(&conn),
            "the next failure must open a fresh window"
        );
        assert!(
            !crate::shutdown::is_draining(),
            "a fresh window is one failing round, so the service must keep serving"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a fresh, unexhausted window must file no failure block"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_round_that_did_not_fail_closes_the_window() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        let (retry_pauses, span) = (TEST_PAUSES, Duration::ZERO);

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            retry_pauses,
            span,
        )
        .await;
        assert!(
            window_open(&conn),
            "the failing round must open the store's window"
        );

        periodic_checkpoint_inner(
            "core",
            &conn,
            &conn,
            Some(tmp.path()),
            retry_pauses,
            span,
            || async { Attempted::Ran(Err(blocked_checkpoint_error())) },
        )
        .await;
        assert!(
            !window_open(&conn),
            "a round that ended without a genuine failure must close the window"
        );

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            retry_pauses,
            span,
        )
        .await;
        assert!(
            !crate::shutdown::is_draining(),
            "failing rounds separated by a round that did not fail are not consecutive, so the \
             fresh window must not stop the service"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "an unexhausted window must file no failure block"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn the_span_floor_alone_blocks_the_stop_the_round_floor_would_decide() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        let rounds = window_rounds() + 1;

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            rounds,
            "injected checkpoint failure",
            TEST_PAUSES,
            Duration::from_secs(3600),
        )
        .await;

        assert!(
            !crate::shutdown::is_draining(),
            "rounds past the round floor inside an unelapsed span must keep the service serving"
        );
        assert!(
            window_open(&conn),
            "the window must stay open until it has spanned both floors"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a window that has not spanned both floors must file no failure block"
        );
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_window_that_outlives_its_span_stops_on_the_next_failing_round() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        let (retry_pauses, span) = (TEST_PAUSES, Duration::from_millis(100));

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            retry_pauses,
            span,
        )
        .await;
        assert!(
            !crate::shutdown::is_draining(),
            "one failing round must never stop the service, whatever the span"
        );

        tokio::time::sleep(Duration::from_millis(150)).await;

        failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            retry_pauses,
            span,
        )
        .await;
        assert!(
            crate::shutdown::is_draining(),
            "the window spans both floors once the span has really elapsed"
        );
        crate::shutdown::drain_clear();
    }

    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn a_round_cut_short_by_a_drain_decides_nothing() {
        crate::shutdown::drain_clear();
        let (tmp, conn) = temp_store("core").await;
        let (mut retry_pauses, span) = (TEST_PAUSES, Duration::ZERO);
        retry_pauses[0] = Duration::from_millis(10);

        crate::shutdown::drain_begin();
        let attempts = failing_rounds(
            "core",
            &conn,
            tmp.path(),
            1,
            "injected checkpoint failure",
            retry_pauses,
            span,
        )
        .await;

        assert_eq!(
            attempts, 1,
            "the drain must cut the spaced retry short after the round's first attempt"
        );
        assert!(
            !window_open(&conn),
            "an interrupted round is not a failing one, so the window must stay untouched"
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a round that decided nothing must file no failure block"
        );
        crate::shutdown::drain_clear();
    }

    /// The durable record a refused reclaiming round must leave: the refusal block, never a
    /// checkpoint failure, and no drain — a refusal is neither a failure nor an attempt.
    fn assert_refusal_recorded(root: &Path) {
        let body = std::fs::read_to_string(root.join("error.log"))
            .expect("the refusal must be filed in the round's root");
        assert!(
            body.contains("MahBot store shrink refused"),
            "the gate must refuse the shrink and record it: {body}"
        );
        for forbidden in [
            "MahBot checkpoint failure",
            "MahBot exit checkpoint failure",
        ] {
            assert!(
                !body.contains(forbidden),
                "a refused shrink must not read as {forbidden:?}: {body}"
            );
        }
        assert!(
            !crate::shutdown::is_draining(),
            "a refused shrink must not begin the drain",
        );
    }

    /// After a refused round the engine must still hold the store and have changed nothing in it:
    /// both foreign `sqlite3` probes are refused, the verdict [`crate::db::wal_guard`] defines has
    /// not moved — the gate is a consistency check about one checkpoint's arithmetic, never a
    /// second definition of a damaged store — and both files are byte-identical to the bytes read
    /// before the store was opened. The probes come FIRST on purpose: reading the store's own bytes
    /// closes a descriptor, which drops this process's record locks, so the foreign observation
    /// must precede the comparison.
    fn assert_store_untouched_by_the_refusal(
        db_path: &Path,
        before_main: &[u8],
        before_wal: &[u8],
        verdict: StoreShape,
    ) {
        foreign_client_is_refused(db_path);
        assert_eq!(
            crate::db::wal_guard::classify_store_shape(db_path),
            verdict,
            "a refused shrink must not change what counts as a damaged store",
        );
        assert_eq!(
            std::fs::read(db_path).expect("read the fixture main file"),
            before_main,
            "a refused shrink must not change a byte of the store's main file",
        );
        assert_eq!(
            std::fs::read(crate::db::wal_path(db_path)).expect("read the fixture journal"),
            before_wal,
            "a refused shrink must not change a byte of the store's journal",
        );
    }

    /// The shared body of the destructive states whose main file is non-empty and whose rows stay
    /// readable — `state` names the page-1 image that declares no pages. Read the fixture's bytes,
    /// pin the file-level verdict, run the real reclaiming round, and prove it was refused with the
    /// rows served, nothing moved and the lock intact; then run the ungated reclaiming checkpoint
    /// the gate withheld, last because it destroys the fixture.
    async fn refused_state_lets_no_shrink_through(tmp: &Path, db_path: &Path, state: &str) {
        let before_main = std::fs::read(db_path).expect("read the fixture main file");
        let before_wal = std::fs::read(crate::db::wal_path(db_path)).expect("read the journal");
        assert!(
            !before_main.is_empty(),
            "the fixture must hold data in its main file",
        );
        // A file-level check sees a healthy store here, and must keep doing so: only the store's
        // own answer, compared with these files' sizes, refuses the shrink.
        let verdict = crate::db::wal_guard::classify_store_shape(db_path);
        assert_eq!(
            verdict,
            StoreShape::Present,
            "the gate must add no file-level defect to a store it refuses",
        );

        let conn = Connection::open(db_path)
            .await
            .expect("open the fixture store");
        assert_eq!(page_count(&conn).await, 0, "{state} must declare no pages");
        assert_eq!(
            fixture_rows(&conn).await,
            1,
            "the fixture's rows must stay readable",
        );

        let maintenance = conn
            .maintenance()
            .await
            .expect("open the store's maintenance connection");

        periodic_checkpoint("core", &conn, &maintenance, true, Some(tmp)).await;

        assert_refusal_recorded(tmp);
        assert_eq!(
            fixture_rows(&conn).await,
            1,
            "the refused round must leave the store serving",
        );

        assert_store_untouched_by_the_refusal(db_path, &before_main, &before_wal, verdict);

        conn.checkpoint_ungated()
            .await
            .expect("run the ungated reclaiming checkpoint");
        let main_len = std::fs::metadata(db_path)
            .expect("stat the fixture main file")
            .len();
        assert_eq!(
            main_len, 0,
            "an ungated reclaiming checkpoint must truncate the main file to nothing, \
             left {main_len} bytes",
        );
    }

    /// On a healthy store the reclaiming checkpoint is still issued, in its reclaiming mode, and
    /// still reclaims the journal — the gate withholds only an answer it cannot trust; it never
    /// downgrades the mode and never skips the checkpoint on a store that answers consistently.
    ///
    /// The store is the consolidated one, so this is the shape the periodic round reclaims: reader
    /// connections enabled, change capture on, the checkpoint on the maintenance connection as the
    /// round issues it (see the module header).
    #[tokio::test]
    async fn a_healthy_store_still_runs_its_reclaiming_checkpoint() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let conn = crate::db::open_consolidated_store(tmp.path())
            .await
            .expect("open the healthy store");
        let _ = conn
            .query("SELECT id FROM tickets", ())
            .await
            .expect("read through a reader connection");
        let wal = crate::db::wal_path(conn.db_path());
        let before = crate::db::wal_guard::stat_size(&wal).expect("stat the store's journal");
        assert!(
            before > crate::db::wal_guard::WAL_HEADER_BYTES,
            "the healthy store must have frames to reclaim, found {before} bytes",
        );

        let maintenance = conn
            .maintenance()
            .await
            .expect("open the store's maintenance connection");
        let Attempted::Ran(Ok(outcome)) =
            checkpoint_attempt("core", &maintenance, true, Some(tmp.path())).await
        else {
            panic!("a healthy store must still run its reclaiming checkpoint");
        };
        assert!(
            outcome.is_complete(),
            "the reclaiming checkpoint must complete on a healthy store",
        );
        let after = crate::db::wal_guard::stat_size(&wal).expect("stat the reclaimed journal");
        assert_eq!(
            after, 0,
            "the reclaiming mode must still reclaim the journal, left {after} bytes",
        );
    }

    /// The round issues its upkeep on the maintenance connection, outside the writing connection's
    /// mutex: with that connection held for the whole test, the round still completes, compaction
    /// and verification alike. Issued on the writing connection instead the round would queue
    /// behind the hold, so the timeout turns a routing regression into a failure rather than a hung
    /// suite.
    #[tokio::test]
    async fn the_round_for_a_store_runs_its_upkeep_off_the_writing_connection() {
        let (tmp, conn) = temp_store("core").await;

        let held = conn.begin_tx().await.expect("hold the writing connection");

        tokio::time::timeout(
            Duration::from_secs(30),
            periodic_store_round("core", &conn, false, Some(tmp.path())),
        )
        .await
        .expect("the round must not wait on the writing connection");

        assert!(
            !window_open(&conn),
            "a completed round must leave no failure window open",
        );
        held.rollback()
            .await
            .expect("release the writing connection");
    }

    /// A store that cannot give the round a maintenance connection is still upkept: the round runs
    /// on the writing connection, the shape every round had before that connection existed, and
    /// nothing is skipped or downgraded, the reclaiming checkpoint included.
    #[tokio::test]
    async fn a_store_without_a_maintenance_connection_still_runs_its_round() {
        let (tmp, conn) = temp_store("core").await;
        let wal = crate::db::wal_path(conn.db_path());
        let before = crate::db::wal_guard::stat_size(&wal).expect("stat the store's journal");
        assert!(
            before > crate::db::wal_guard::WAL_HEADER_BYTES,
            "the fixture must carry frames to reclaim, found {before} bytes",
        );

        periodic_round("core", &conn, &conn, true, Some(tmp.path())).await;

        let after = crate::db::wal_guard::stat_size(&wal).expect("stat the reclaimed journal");
        assert_eq!(
            after, 0,
            "the round must still reclaim the journal on the writing connection, left {after} bytes",
        );
        assert!(
            !window_open(&conn),
            "a completed round must leave no failure window open",
        );
        assert!(
            !tmp.path().join("error.log").exists(),
            "a healthy store's round must file no failure",
        );
    }

    /// The gate's destructive state A — an empty main file with a non-empty journal — never reaches
    /// a reclaiming round on this engine. A machine finding such a store refuses to start: the boot
    /// pre-flight classifies the shape before the store is opened (asserted here). Opening it
    /// anyway, which only a test can do, makes the engine discard the orphan journal as it resolves
    /// the empty main file (turso 0.8.0 leaves the main file at 0 bytes and empties the journal it
    /// cannot apply), so a round finds nothing to destroy and files nothing. The gate's rule for
    /// the state is pinned by its answer-table tests; the two states the engine *does* present run
    /// end to end below.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn empty_main_file_with_a_journal_is_refused_at_boot_and_never_reaches_a_round() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let db_path = crate::db::store_db_path(tmp.path(), "core");
        let wal = crate::db::wal_path(&db_path);
        build_empty_main_file_store(&db_path).await;
        let journal_bytes = std::fs::metadata(&wal)
            .expect("stat the fixture journal")
            .len();
        assert!(
            journal_bytes > crate::db::wal_guard::WAL_HEADER_BYTES,
            "the fixture must leave committed frames in its journal, found \
             {journal_bytes} bytes",
        );

        // The product's own door is closed on this store before the gate is asked: the boot
        // pre-flight refuses the shape.
        assert_eq!(
            crate::db::wal_guard::classify_store_shape(&db_path),
            StoreShape::Unusable(ShapeDefect::ZeroBytes),
            "an empty main file must stay a boot refusal",
        );

        let conn = Connection::open(&db_path)
            .await
            .expect("open the fixture store");
        assert_eq!(
            page_count(&conn).await,
            0,
            "the engine must answer no pages for the empty main file",
        );
        assert_eq!(
            std::fs::metadata(&wal).expect("stat the journal").len(),
            0,
            "the engine must discard the orphan journal as it opens the empty store",
        );

        let maintenance = conn
            .maintenance()
            .await
            .expect("open the store's maintenance connection");
        periodic_checkpoint("core", &conn, &maintenance, true, Some(tmp.path())).await;
        assert!(
            !tmp.path().join("error.log").exists(),
            "a round with nothing left to destroy files no refusal",
        );
    }

    /// The gate's destructive state B end to end through the real reclaiming round: a non-empty
    /// main file whose resolved page-1 header declares size zero. The attempt is refused with
    /// nothing issued and nothing counted, the rows stay readable, the store keeps the engine's
    /// lock and both files are byte-identical. The closing proof, last because it destroys the
    /// fixture, shows what the refusal withheld: an ungated reclaiming checkpoint truncates the
    /// main file to nothing.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn zero_page_count_store_is_refused_end_to_end() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let db_path = crate::db::store_db_path(tmp.path(), "core");
        build_zero_page_count_store(&db_path).await;

        let state = "the fixture's page-1 header";
        refused_state_lets_no_shrink_through(tmp.path(), &db_path, state).await;
    }

    /// The gate's destructive state C end to end through the real reclaiming round: a main file
    /// whose newest in-journal page-1 image declares size zero. The attempt is refused with nothing
    /// issued and nothing counted, the rows stay readable, the store keeps the engine's lock and
    /// both files are byte-identical. The closing proof, last because it destroys the fixture,
    /// shows what the refusal withheld: an ungated reclaiming checkpoint truncates the main file to
    /// nothing.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn zero_page_count_in_the_journal_is_refused_end_to_end() {
        crate::shutdown::drain_clear();
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let db_path = crate::db::store_db_path(tmp.path(), "core");
        build_zero_page_count_wal_store(&db_path).await;

        let state = "the journal's newest page-1 image";
        refused_state_lets_no_shrink_through(tmp.path(), &db_path, state).await;
    }
}