khive-db 0.9.0

SQLite storage backend: entities, edges, notes, events, FTS5, sqlite-vec vectors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
//! Single-writer task and bounded write queue (ADR-067 Component A).
//!
//! `WriterTask` (via `spawn` and the drain loop `run_writer_task`) owns a
//! dedicated standalone writer `rusqlite::Connection` and is the only code
//! path that issues `BEGIN IMMEDIATE` for write traffic routed through the
//! channel it drains. Callers reach it exclusively through a
//! [`WriterTaskHandle`], sending a typed closure and awaiting a typed
//! oneshot reply so each store method's natural return type (e.g.
//! `BatchWriteSummary`) survives the trip through the type-erased channel
//! unmodified — a flat `Result<u64, StorageError>` reply would conflate
//! `affected`/`failed` into one count and drop `first_error`.
//!
//! See `crates/khive-db/docs/api/writer-task.md` for migration-slice scope
//! (which write paths currently route through this vs. the legacy
//! pool-mutex path) and the ADR-067 component breakdown.
//!
//! ## ADR-136 D1 gate 5: writer classification
//!
//! Every connection that issues writes against a khive-db file falls into
//! exactly one of the rows below. Request-path store writes, runtime
//! merge/symmetric-edge transactions,
//! and `khive_storage::SqlAccess` (`SqlBridge::writer`/`atomic_unit`) are subject
//! to `PoolConfig::write_queue_enabled` / `write_routing_strict` routing.
//! Everything else here is an
//! explicit, intentional exemption — not an implicit gap left over from an
//! incomplete migration.
//!
//! | Writer | Connection | Request-path write | Routing |
//! | --- | --- | --- | --- |
//! | Request-path writes (`create`, `update`, batch upserts, …) | `WriterTaskHandle` (queue-first) or a standalone/pool-mutex connection on degrade | Yes | Queue-first (ADR-136 D1 gate 1); strict routing fails closed on degrade |
//! | Startup / schema migrations (`migrations::run_migrations`, `apply_schema_plan`) | The pool's own writer-mutex connection (`ConnectionPool::new`, before the `WriterTask` is ever spawned) | No | Exempt — runs once at boot, before any queue handle exists to route through |
//! | Checkpointing (`checkpoint::CheckpointConnection`) | Dedicated standalone connection, opened once at task startup (ADR-091 Amendment 5, #1652) | No | Exempt by design — the whole point of that fix was moving checkpoint I/O OFF the pool writer's admission path; routing it back through the write queue would reintroduce the contention it removed |
//! | Recovery (`walpin` beacon/sidecar bookkeeping) | None — file-level bookkeeping (PID beacons, heartbeats) alongside the database, not a SQL connection against it | No | N/A — never acquires a database writer connection |
//! | Top-level maintenance (`VACUUM` via `execute_script_top_level`/`WriterTaskHandle::send_top_level`) | `WriterTaskHandle`, skipping the per-request `BEGIN IMMEDIATE`/`COMMIT` wrap only | Yes | Routed through the SAME single writer owner as every other queued request — only the transaction wrap is skipped, never the queue |
//!
//! Store constructors may run outside Tokio and temporarily cache no handle;
//! every store request-path write refreshes through
//! `ConnectionPool::writer_task_for_write` at execution time. Strict routing
//! refuses a missing handle, while the explicit compatibility fallback emits
//! its store-specific violation at the actual direct-writer seam. Runtime
//! entity/note merges and symmetric edge updates use the same routing policy
//! through a closed operation adapter. The strict default itself remains gated
//! by ADR-135 F2 / ADR-136 D2 evidence.
//!
//! A `direct_route_violation` sink row (`timeout_sink::emit_direct_route_violation`,
//! ADR-136 D1 gate 6c) is emitted ONLY for the first row's degrade path — a
//! request-path write that bypassed an enabled queue. The other four
//! rows are exempt by design and never emit that row.

use rusqlite::Connection;
use std::collections::HashMap;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, oneshot};

use khive_storage::error::{StorageError, WriterTaskRequestState};

use crate::error::SqliteError;
use crate::pool::{ConnectionPool, WriterAcquisitionCounters};

/// Retry delays after a busy/locked `BEGIN IMMEDIATE` refusal. The operation
/// closure remains owned by the request until one BEGIN succeeds, so these
/// are the only retries this path may perform. Persistent contention is
/// bounded to three total BEGIN attempts and 15 ms of explicit backoff, and
/// the attempts together share one configured `busy_timeout` acquisition
/// budget rather than each waiting out a full window of their own.
const WRITER_BEGIN_RETRY_DELAYS: [Duration; 2] =
    [Duration::from_millis(5), Duration::from_millis(10)];

/// Closure signature for a write operation executed against the writer
/// task's dedicated connection.
///
/// `conn` is already inside a `BEGIN IMMEDIATE` transaction opened by
/// `run_writer_task` when this runs. The closure must issue DML (and, in
/// later slices, named `SAVEPOINT`s) only — never a bare `BEGIN` / `COMMIT`
/// / `ROLLBACK` — a nested bare `BEGIN IMMEDIATE` would violate SQLite's
/// nested-transaction rule and return `SQLITE_ERROR: cannot start a
/// transaction within a transaction` (ADR-067 lines 271-276).
type WriteOp<R> = Box<dyn FnOnce(&Connection) -> Result<R, StorageError> + Send>;

/// Latest completed writer-task span for one database, decomposed at the
/// boundaries an operator can act on (#1849). A zero value means that phase
/// did not run (top-level/early-failure request) or completed below the
/// microsecond clock resolution; `total_micros` retains the full span.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriterStageObservation {
    pub queue_wait_micros: u64,
    pub transaction_acquire_micros: u64,
    pub body_micros: u64,
    pub commit_micros: u64,
    pub total_micros: u64,
    pub queue_depth_at_entry: u64,
    pub observed_at_unix_ms: u64,
}

static WRITER_STAGE_OBSERVATIONS: OnceLock<
    Mutex<HashMap<Option<PathBuf>, WriterStageObservation>>,
> = OnceLock::new();

fn writer_stage_observations() -> &'static Mutex<HashMap<Option<PathBuf>, WriterStageObservation>> {
    WRITER_STAGE_OBSERVATIONS.get_or_init(|| Mutex::new(HashMap::new()))
}

fn writer_db_key_from_path(path: Option<&Path>) -> Option<PathBuf> {
    path.map(Path::to_path_buf)
}

fn writer_db_key(pool: &ConnectionPool) -> Option<PathBuf> {
    writer_db_key_from_path(pool.canonical_path())
}

fn duration_micros(duration: Duration) -> u64 {
    duration.as_micros().min(u128::from(u64::MAX)) as u64
}

fn observed_at_unix_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_millis() as u64)
        .unwrap_or(0)
}

/// Pure in-memory read of the most recently completed writer-task span for
/// this exact backend. It acquires no SQLite connection and performs no I/O.
pub fn last_writer_stage_observation(pool: &ConnectionPool) -> Option<WriterStageObservation> {
    writer_stage_observations()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(&writer_db_key(pool))
        .cloned()
}

struct WriteTelemetry {
    backend_key: Option<PathBuf>,
    db: String,
    submitted_at: Instant,
    queue_depth_at_entry: usize,
    slow_write_threshold: Option<Duration>,
}

impl WriteTelemetry {
    fn new(
        backend_key: Option<PathBuf>,
        db: String,
        queue_depth_at_entry: usize,
        slow_write_threshold: Option<Duration>,
    ) -> Self {
        Self {
            backend_key,
            db,
            submitted_at: Instant::now(),
            queue_depth_at_entry,
            slow_write_threshold,
        }
    }

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

    fn finish(
        self,
        queue_wait: Duration,
        transaction_acquire: Duration,
        body: Duration,
        commit: Duration,
    ) {
        let total = self.submitted_at.elapsed();
        let observation = WriterStageObservation {
            queue_wait_micros: duration_micros(queue_wait),
            transaction_acquire_micros: duration_micros(transaction_acquire),
            body_micros: duration_micros(body),
            commit_micros: duration_micros(commit),
            total_micros: duration_micros(total),
            queue_depth_at_entry: self.queue_depth_at_entry as u64,
            observed_at_unix_ms: observed_at_unix_ms(),
        };
        writer_stage_observations()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(self.backend_key, observation.clone());

        if self
            .slow_write_threshold
            .is_some_and(|threshold| total >= threshold)
        {
            crate::timeout_sink::emit_slow_write(&self.db, &observation);
        }
    }
}

/// One write request awaiting execution by the writer task.
///
/// Carries a typed closure and a typed oneshot reply so that the concrete
/// return type `R` (e.g. `BatchWriteSummary`) is preserved end to end,
/// while [`AnyWriteRequest`] lets the drain loop hold heterogeneous
/// requests in one homogeneous channel.
///
/// `top_level` (ADR-067 Component A): when `true`,
/// the drain loop runs this request's operation WITHOUT wrapping it in a
/// `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` — still serialized through the
/// single writer owner (only one request drains at a time regardless of
/// this flag), but with the transaction wrap skipped entirely. Exists for
/// statements SQLite forbids inside any open transaction (e.g. `VACUUM`);
/// see [`WriterTaskHandle::send_top_level`].
pub struct WriteRequest<R: Send + 'static> {
    op: WriteOp<R>,
    reply: oneshot::Sender<Result<R, StorageError>>,
    top_level: bool,
    telemetry: WriteTelemetry,
}

mod sealed {
    /// Restricts [`super::AnyWriteRequest`] to implementations defined in
    /// this module — only [`super::WriteRequest<R>`] implements it — and
    /// carries the drain loop's internal terminal-state reporting methods
    /// without changing the public execution-method signatures.
    pub trait Sealed {
        fn execute_and_reply_reporting_terminal(
            self: Box<Self>,
            conn: &rusqlite::Connection,
            tx_span: Option<khive_storage::tx_registry::TxHandle>,
            queue_wait: std::time::Duration,
            transaction_acquire: std::time::Duration,
        ) -> Option<khive_storage::error::WriterTaskRequestState>;

        fn execute_and_reply_top_level_reporting_terminal(
            self: Box<Self>,
            conn: &rusqlite::Connection,
            queue_wait: std::time::Duration,
        ) -> Option<khive_storage::error::WriterTaskRequestState>;

        fn reply_error_after_begin(
            self: Box<Self>,
            err: khive_storage::error::StorageError,
            queue_wait: std::time::Duration,
            transaction_acquire: std::time::Duration,
        );
    }
}

/// Type-erased write request the writer task's drain loop can hold in a
/// homogeneous channel (`mpsc::Sender<Box<dyn AnyWriteRequest + Send>>`),
/// while each concrete [`WriteRequest<R>`] still carries its own typed
/// reply. Sealed: only this module may implement it (ADR-067 lines
/// 210-212).
pub trait AnyWriteRequest: sealed::Sealed + Send {
    /// Runs this request's operation against `conn`, commits or rolls back
    /// the enclosing transaction based on the outcome, and sends the
    /// (possibly commit-failure-adjusted) result to the request's oneshot
    /// reply channel.
    ///
    /// `conn` must already be inside a successfully-opened `BEGIN IMMEDIATE`
    /// transaction opened by the caller (`run_writer_task`) — this method
    /// issues only `COMMIT` / `ROLLBACK`, never `BEGIN`, so `run_writer_task`
    /// remains the sole issuer of `BEGIN IMMEDIATE` (ADR-067 Component A).
    /// Callers must use [`Self::reply_error`] instead when the enclosing
    /// `BEGIN IMMEDIATE` itself failed — this method must not be invoked in
    /// that case.
    fn execute_and_reply(self: Box<Self>, conn: &Connection);

    /// Runs this request's operation directly against `conn` — no
    /// transaction wrap, no `COMMIT`/`ROLLBACK` — and sends the result to
    /// the request's oneshot reply channel.
    ///
    /// Used only for [`Self::is_top_level`] requests: the drain loop calls
    /// this INSTEAD of `execute_and_reply` for such requests, skipping
    /// `BEGIN IMMEDIATE` entirely so a statement that must run outside any
    /// transaction (e.g. `VACUUM`) can still be serialized through the
    /// single writer owner.
    fn execute_and_reply_top_level(self: Box<Self>, conn: &Connection);

    /// Replies with `err` without running this request's operation or
    /// touching `conn`.
    ///
    /// Used when the enclosing `BEGIN IMMEDIATE` failed (for example,
    /// `SQLITE_BUSY` from lock contention with an unmigrated writer path
    /// still holding the pool's writer mutex — reachable while only
    /// `entity.rs` is routed through this channel). Running the operation
    /// anyway would execute its DML against `conn` in autocommit mode,
    /// landing partial writes for a request the caller is told failed.
    /// Skipping the operation entirely keeps "the caller got an error" and
    /// "no rows landed" true together.
    fn reply_error(self: Box<Self>, err: StorageError);

    /// `true` if the drain loop must run this request via
    /// [`Self::execute_and_reply_top_level`] (no transaction wrap) instead
    /// of [`Self::execute_and_reply`] (wrapped in `BEGIN IMMEDIATE`).
    fn is_top_level(&self) -> bool;

    /// Time from the caller constructing this request (before bounded-channel
    /// admission) until the writer task dequeued it.
    fn queue_wait(&self) -> Duration;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RollbackDisposition {
    RolledBack,
    SideEffectsUnknown,
}

/// Roll back a failed wrapped request and verify that the connection really
/// returned to autocommit mode before it can serve another request.
fn rollback_after_failure(conn: &Connection, failure_context: &'static str) -> RollbackDisposition {
    match conn.execute_batch("ROLLBACK") {
        Ok(()) if conn.is_autocommit() => RollbackDisposition::RolledBack,
        Ok(()) => {
            tracing::error!(
                failure_context,
                "writer transaction: ROLLBACK returned success but the connection is still in a \
                 transaction; request side effects are unknown"
            );
            RollbackDisposition::SideEffectsUnknown
        }
        Err(rollback_error) => {
            tracing::error!(
                error = %rollback_error,
                failure_context,
                "writer transaction: rollback after request failure failed; request side effects are \
                 unknown"
            );
            RollbackDisposition::SideEffectsUnknown
        }
    }
}

/// Execute an operation inside an already-open transaction and apply the
/// shared commit, rollback, panic, and autocommit verification rules.
pub(crate) fn execute_wrapped_transaction<R, F>(
    conn: &Connection,
    commit_operation: &'static str,
    operation: F,
) -> (Result<R, StorageError>, Option<WriterTaskRequestState>)
where
    F: FnOnce(&Connection) -> Result<R, StorageError>,
{
    let profiled = execute_wrapped_transaction_profiled(conn, commit_operation, operation);
    (profiled.result, profiled.terminal_state)
}

struct ProfiledWrappedTransaction<R> {
    result: Result<R, StorageError>,
    terminal_state: Option<WriterTaskRequestState>,
    body: Duration,
    commit: Duration,
}

fn execute_wrapped_transaction_profiled<R, F>(
    conn: &Connection,
    commit_operation: &'static str,
    operation: F,
) -> ProfiledWrappedTransaction<R>
where
    F: FnOnce(&Connection) -> Result<R, StorageError>,
{
    let body_started = Instant::now();
    let operation_outcome = catch_unwind(AssertUnwindSafe(|| operation(conn)));
    let body = body_started.elapsed();

    match operation_outcome {
        Ok(Ok(value)) => {
            let commit_started = Instant::now();
            let commit_outcome = conn.execute_batch("COMMIT");
            let commit = commit_started.elapsed();
            match commit_outcome {
                Ok(()) if conn.is_autocommit() => ProfiledWrappedTransaction {
                    result: Ok(value),
                    terminal_state: None,
                    body,
                    commit,
                },
                Ok(()) => {
                    tracing::error!(
                    "writer transaction: COMMIT returned success but the connection is still in \
                     a transaction; request side effects are unknown"
                );
                    let request_state = WriterTaskRequestState::SideEffectsUnknown;
                    ProfiledWrappedTransaction {
                        result: Err(writer_task_terminated(request_state)),
                        terminal_state: Some(request_state),
                        body,
                        commit,
                    }
                }
                Err(commit_error) => match rollback_after_failure(conn, "commit failure") {
                    RollbackDisposition::RolledBack => ProfiledWrappedTransaction {
                        result: Err(StorageError::WriterTaskRequestFailed {
                            request_state: WriterTaskRequestState::TransactionRolledBack,
                            source: Box::new(StorageError::Pool {
                                operation: commit_operation.into(),
                                message: commit_error.to_string(),
                            }),
                        }),
                        terminal_state: None,
                        body,
                        commit,
                    },
                    RollbackDisposition::SideEffectsUnknown => {
                        let request_state = WriterTaskRequestState::SideEffectsUnknown;
                        ProfiledWrappedTransaction {
                            result: Err(writer_task_terminated(request_state)),
                            terminal_state: Some(request_state),
                            body,
                            commit,
                        }
                    }
                },
            }
        }
        Ok(Err(operation_error)) => {
            match rollback_after_failure(conn, "request operation failure") {
                RollbackDisposition::RolledBack => ProfiledWrappedTransaction {
                    result: Err(StorageError::WriterTaskRequestFailed {
                        request_state: WriterTaskRequestState::TransactionRolledBack,
                        source: Box::new(operation_error),
                    }),
                    terminal_state: None,
                    body,
                    commit: Duration::ZERO,
                },
                RollbackDisposition::SideEffectsUnknown => {
                    let request_state = WriterTaskRequestState::SideEffectsUnknown;
                    ProfiledWrappedTransaction {
                        result: Err(writer_task_terminated(request_state)),
                        terminal_state: Some(request_state),
                        body,
                        commit: Duration::ZERO,
                    }
                }
            }
        }
        Err(_panic_payload) => {
            let request_state = match rollback_after_failure(conn, "request panic") {
                RollbackDisposition::RolledBack => WriterTaskRequestState::TransactionRolledBack,
                RollbackDisposition::SideEffectsUnknown => {
                    WriterTaskRequestState::SideEffectsUnknown
                }
            };
            ProfiledWrappedTransaction {
                result: Err(writer_task_terminated(request_state)),
                terminal_state: Some(request_state),
                body,
                commit: Duration::ZERO,
            }
        }
    }
}

impl<R: Send + 'static> sealed::Sealed for WriteRequest<R> {
    fn execute_and_reply_reporting_terminal(
        self: Box<Self>,
        conn: &Connection,
        tx_span: Option<khive_storage::tx_registry::TxHandle>,
        queue_wait: Duration,
        transaction_acquire: Duration,
    ) -> Option<WriterTaskRequestState> {
        // Keep the typed reply sender outside the unwind boundary. Calling
        // `(self.op)(conn)` directly would drop `self.reply` while unwinding,
        // leaving the active caller with only an untyped RecvError.
        let WriteRequest {
            op,
            reply,
            telemetry,
            ..
        } = *self;
        let profiled = execute_wrapped_transaction_profiled(conn, "writer_task_commit", op);
        // The reply wake can make the caller immediately observe the
        // committed/error result. Deregister the transaction span first so
        // tx_registry continues to mean "currently open SQL transaction",
        // never "a transaction whose caller has already resumed" (#1790).
        drop(tx_span);
        telemetry.finish(
            queue_wait,
            transaction_acquire,
            profiled.body,
            profiled.commit,
        );
        // The receiver may already be gone (caller dropped its future) —
        // that is not this task's problem to report.
        let _ = reply.send(profiled.result);
        profiled.terminal_state
    }

    fn execute_and_reply_top_level_reporting_terminal(
        self: Box<Self>,
        conn: &Connection,
        queue_wait: Duration,
    ) -> Option<WriterTaskRequestState> {
        let WriteRequest {
            op,
            reply,
            telemetry,
            ..
        } = *self;
        let body_started = Instant::now();
        let outcome = catch_unwind(AssertUnwindSafe(|| op(conn)));
        let body = body_started.elapsed();
        telemetry.finish(queue_wait, Duration::ZERO, body, Duration::ZERO);
        match outcome {
            Ok(outcome) if conn.is_autocommit() => {
                // No COMMIT/ROLLBACK here: this request explicitly did not
                // open a transaction, so there is nothing to close.
                let _ = reply.send(outcome);
                None
            }
            Ok(_outcome) => {
                tracing::error!(
                    "writer task: top-level request returned with an open transaction; request \
                     side effects are unknown"
                );
                let request_state = WriterTaskRequestState::SideEffectsUnknown;
                let _ = reply.send(Err(writer_task_terminated(request_state)));
                Some(request_state)
            }
            Err(_panic_payload) => {
                // Statements completed before a top-level panic may already
                // have autocommitted. Report the ambiguity; never invent a
                // rollback for a request that opened no transaction.
                let request_state = WriterTaskRequestState::SideEffectsUnknown;
                let _ = reply.send(Err(writer_task_terminated(request_state)));
                Some(request_state)
            }
        }
    }

    fn reply_error_after_begin(
        self: Box<Self>,
        err: StorageError,
        queue_wait: Duration,
        transaction_acquire: Duration,
    ) {
        let WriteRequest {
            reply, telemetry, ..
        } = *self;
        telemetry.finish(
            queue_wait,
            transaction_acquire,
            Duration::ZERO,
            Duration::ZERO,
        );
        let _ = reply.send(Err(err));
    }
}

impl<R: Send + 'static> AnyWriteRequest for WriteRequest<R> {
    fn execute_and_reply(self: Box<Self>, conn: &Connection) {
        let queue_wait = self.queue_wait();
        let _ = sealed::Sealed::execute_and_reply_reporting_terminal(
            self,
            conn,
            None,
            queue_wait,
            Duration::ZERO,
        );
    }

    fn execute_and_reply_top_level(self: Box<Self>, conn: &Connection) {
        let queue_wait = self.queue_wait();
        let _ =
            sealed::Sealed::execute_and_reply_top_level_reporting_terminal(self, conn, queue_wait);
    }

    fn reply_error(self: Box<Self>, err: StorageError) {
        let queue_wait = self.queue_wait();
        sealed::Sealed::reply_error_after_begin(self, err, queue_wait, Duration::ZERO);
    }

    fn is_top_level(&self) -> bool {
        self.top_level
    }

    fn queue_wait(&self) -> Duration {
        self.telemetry.queue_wait()
    }
}

fn writer_task_terminated(request_state: WriterTaskRequestState) -> StorageError {
    StorageError::WriterTaskTerminated { request_state }
}

fn writer_task_begin_error(error: rusqlite::Error, busy_timeout: Duration) -> StorageError {
    if crate::timeout_sink::is_busy_or_locked(&error) {
        StorageError::WriterTaskBusy {
            timeout_ms: u64::try_from(busy_timeout.as_millis()).unwrap_or(u64::MAX),
        }
    } else {
        StorageError::Pool {
            operation: "writer_task_begin".into(),
            message: error.to_string(),
        }
    }
}

/// Sender half of the write queue. Cheaply cloneable (wraps an
/// `mpsc::Sender`) — every migrated store that shares one writer task holds
/// a clone of this handle.
#[derive(Clone, Debug)]
pub struct WriterTaskHandle {
    tx: mpsc::Sender<Box<dyn AnyWriteRequest + Send>>,
    /// Exact canonical backend identity used by the in-memory stage registry.
    /// Kept separate from `db`, whose lossy display form is logging-only.
    backend_key: Option<PathBuf>,
    /// This handle's pool's writer-timeout sink identity (`timeout_sink::db_label`),
    /// captured at spawn so `send_with_timeout`'s `WriteQueueFull` path can
    /// report a `queue_saturation` sink row (ADR-136 D1 gate 6a) without
    /// needing a `&ConnectionPool` reference.
    db: String,
    /// Slow-write latency bound (`timeout_sink::slow_write_threshold`),
    /// resolved once at spawn. `None` disables slow-write rows. Captured
    /// here rather than read per send so the caller path pays no env lookup
    /// and tests get a deterministic value by setting the override before
    /// spawning their own writer task.
    slow_write_threshold: Option<std::time::Duration>,
    /// Default enqueue-capacity deadline for [`Self::send_bounded`] /
    /// [`Self::send_top_level_bounded`], captured from
    /// `PoolConfig::write_admission_deadline_ms` at [`spawn`] (ADR-131
    /// Decision 2). Bounds ONLY the wait for channel capacity, the same
    /// boundary `send_with_timeout` already documents — never the reply wait
    /// after acceptance (#1382).
    ///
    /// This is a dedicated admission authority, distinct from
    /// `PoolConfig::checkout_timeout` (reader/pool checkout). The two used
    /// to be conflated here before ADR-131 Decision 2 (#1382, #1643).
    ///
    /// ADR-131 Decision 2's outer-request-budget clamp ("when the caller's outer
    /// request deadline leaves less time remaining than the configured
    /// admission deadline, the admission deadline applied to that operation
    /// is the remaining outer budget instead") is explicitly DEFERRED: no
    /// outer request deadline is plumbed to `send_bounded` /
    /// `send_top_level_bounded`'s call sites as of #1737, so there is no
    /// budget to clamp against. When an outer deadline reaches this call
    /// path, clamp here rather than faking a shorter deadline against a
    /// nonexistent budget.
    enqueue_timeout: std::time::Duration,
}

impl WriterTaskHandle {
    /// Enqueue a write operation and return the oneshot receiver its reply
    /// will arrive on, once the request has actually been accepted onto the
    /// channel.
    ///
    /// Shared by [`Self::send`] and [`Self::send_with_timeout`] so that a
    /// caller-supplied deadline (see `send_with_timeout`) can bound ONLY
    /// this enqueue step — never the reply-wait that follows it. Once this
    /// returns `Ok`, the request has been accepted by the writer task and
    /// will either run to completion or receive a typed terminal error if an
    /// earlier request kills the task before this operation begins. The
    /// returned receiver must be awaited without a timeout; abandoning it
    /// here would silently drop the request's eventual result, not cancel the
    /// request itself.
    async fn enqueue<R, F>(
        &self,
        op: F,
    ) -> Result<oneshot::Receiver<Result<R, StorageError>>, StorageError>
    where
        R: Send + 'static,
        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
    {
        self.enqueue_inner(op, false).await
    }

    /// Shared enqueue path for both transaction-wrapped ([`Self::enqueue`])
    /// and top-level ([`Self::send_top_level`]) requests — `top_level`
    /// controls which [`AnyWriteRequest`] method the drain loop invokes.
    async fn enqueue_inner<R, F>(
        &self,
        op: F,
        top_level: bool,
    ) -> Result<oneshot::Receiver<Result<R, StorageError>>, StorageError>
    where
        R: Send + 'static,
        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
    {
        let (reply_tx, reply_rx) = oneshot::channel();
        let telemetry = WriteTelemetry::new(
            self.backend_key.clone(),
            self.db.clone(),
            self.queue_depth(),
            self.slow_write_threshold,
        );
        let request = WriteRequest {
            op: Box::new(op),
            reply: reply_tx,
            top_level,
            telemetry,
        };

        self.tx
            .send(Box::new(request))
            .await
            .map_err(|_| writer_task_terminated(WriterTaskRequestState::NotStarted))?;

        Ok(reply_rx)
    }

    /// Send a write operation to the writer task and await its typed reply.
    ///
    /// Backpressure: this suspends on the channel's `send().await` when the
    /// bounded queue is full (ADR-067 "Channel capacity and queue-full
    /// policy") — there is no `try_send` escape hatch. Callers that need a
    /// deadline on that wait should use [`Self::send_with_timeout`] instead.
    pub async fn send<R, F>(&self, op: F) -> Result<R, StorageError>
    where
        R: Send + 'static,
        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
    {
        let reply_rx = self.enqueue(op).await?;
        reply_rx
            .await
            .map_err(|_| writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown))?
    }

    /// Like [`Self::send`], but bounds the wait for the bounded channel to
    /// free capacity with `timeout`.
    ///
    /// The timeout applies ONLY to enqueueing the request (the channel
    /// `send().await` that can suspend on a full queue) — never to waiting
    /// for the writer task's reply once the request has been accepted.
    /// `StorageError::WriteQueueFull` means exactly "the bounded channel was
    /// full and this request was never accepted"; it must never be returned
    /// for a request that was accepted and is still executing (or already
    /// committed) by the time `timeout` elapses — that would misreport a
    /// slow op or a lock wait as a queue-capacity failure, and could tell a
    /// caller a write failed when it actually landed. ADR-067's queue-full
    /// policy has no immediate-error `try_send` path — only this caller-side
    /// deadline on the enqueue step.
    pub async fn send_with_timeout<R, F>(
        &self,
        op: F,
        timeout: std::time::Duration,
    ) -> Result<R, StorageError>
    where
        R: Send + 'static,
        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
    {
        let reply_rx = match tokio::time::timeout(timeout, self.enqueue(op)).await {
            Ok(Ok(reply_rx)) => reply_rx,
            Ok(Err(e)) => return Err(e),
            Err(_elapsed) => {
                let timeout_ms = timeout.as_millis() as u64;
                crate::timeout_sink::emit_queue_saturation(&self.db, timeout_ms);
                return Err(StorageError::WriteQueueFull { timeout_ms });
            }
        };

        reply_rx
            .await
            .map_err(|_| writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown))?
    }

    /// Like [`Self::send`], but bounds the enqueue-capacity wait with this
    /// handle's configured `enqueue_timeout`
    /// (`PoolConfig::write_admission_deadline_ms` at spawn time, ADR-131
    /// Decision 2) instead of waiting indefinitely (#1382).
    ///
    /// Once the request is accepted onto the channel, the reply wait is
    /// unbounded by this method, identical to [`Self::send`] — this bounds
    /// only queue-capacity admission, never SQLite execution or reply
    /// latency. Callers that need a non-default deadline should use
    /// [`Self::send_with_timeout`] directly.
    pub async fn send_bounded<R, F>(&self, op: F) -> Result<R, StorageError>
    where
        R: Send + 'static,
        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
    {
        self.send_with_timeout(op, self.enqueue_timeout).await
    }

    /// Send a write operation that MUST run outside any open transaction
    /// (e.g. `VACUUM`, which SQLite forbids inside `BEGIN`/`COMMIT`) and
    /// await its typed reply.
    ///
    /// Still serialized through the same single writer owner as
    /// [`Self::send`] — the request goes through the identical bounded
    /// channel and drain loop, one request at a time — but the drain loop
    /// skips the per-request `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` wrap
    /// entirely for this request (ADR-067 Component A). The single-writer
    /// guarantee is preserved; only
    /// the transaction wrap is skipped.
    pub async fn send_top_level<R, F>(&self, op: F) -> Result<R, StorageError>
    where
        R: Send + 'static,
        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
    {
        let reply_rx = self.enqueue_inner(op, true).await?;
        reply_rx
            .await
            .map_err(|_| writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown))?
    }

    /// Like [`Self::send_top_level`], but bounds the enqueue-capacity wait
    /// with this handle's configured `enqueue_timeout`, mirroring
    /// [`Self::send_bounded`] for top-level (transaction-skipping) requests
    /// (#1382).
    pub async fn send_top_level_bounded<R, F>(&self, op: F) -> Result<R, StorageError>
    where
        R: Send + 'static,
        F: FnOnce(&Connection) -> Result<R, StorageError> + Send + 'static,
    {
        let reply_rx =
            match tokio::time::timeout(self.enqueue_timeout, self.enqueue_inner(op, true)).await {
                Ok(Ok(reply_rx)) => reply_rx,
                Ok(Err(e)) => return Err(e),
                Err(_elapsed) => {
                    let timeout_ms = self.enqueue_timeout.as_millis() as u64;
                    crate::timeout_sink::emit_queue_saturation(&self.db, timeout_ms);
                    return Err(StorageError::WriteQueueFull { timeout_ms });
                }
            };

        reply_rx
            .await
            .map_err(|_| writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown))?
    }

    /// Current write-queue backlog depth: requests enqueued but not yet
    /// accepted by the writer task's drain loop.
    ///
    /// Reads `mpsc::Sender::max_capacity() - capacity()`, so it is a
    /// point-in-time snapshot racy under concurrent senders/the drain loop
    /// draining concurrently — acceptable for a monitoring gauge (the
    /// load/perf harness metrics read-surface), never used for any correctness
    /// decision.
    pub fn queue_depth(&self) -> usize {
        self.tx.max_capacity() - self.tx.capacity()
    }

    /// The bounded channel's configured capacity
    /// (`PoolConfig::write_queue_capacity`).
    pub fn capacity(&self) -> usize {
        self.tx.max_capacity()
    }
}

/// Spawn the write-owner task (ADR-067 Component A) on the current Tokio
/// runtime.
///
/// Opens a dedicated standalone writer connection independent of the pool's
/// Mutex-guarded `writer()` connection used by unmigrated paths. That one-time
/// infrastructure open is uncounted; every dequeued top-level request or
/// successful `BEGIN IMMEDIATE` increments the writer-task acquisition class.
/// Returns the cloneable [`WriterTaskHandle`] sender half. The task normally
/// runs until every handle clone is dropped and the channel closes; a request
/// panic, failed rollback, or poisoned connection puts it into the permanent
/// terminal state documented below.
///
/// `capacity` bounds the channel (`PoolConfig::write_queue_capacity` /
/// `KHIVE_WRITE_QUEUE_CAPACITY`, ADR-067 recommends 256).
///
/// # Errors
/// Must be called from within a Tokio runtime context (calls
/// `tokio::spawn`). Returns an error if the pool cannot open a standalone
/// writer connection (e.g. an in-memory pool has no standalone-connection
/// support). See `crates/khive-db/docs/api/writer-task.md` for the
/// migration-slice scope this commits per `BEGIN IMMEDIATE`.
pub fn spawn(pool: &ConnectionPool, capacity: usize) -> Result<WriterTaskHandle, SqliteError> {
    // The lifetime connection is infrastructure, not one acquisition per
    // write. Each dequeued request is counted below at the task's actual
    // ownership boundary instead.
    let conn = pool.open_standalone_writer_untracked()?;
    let acquisition_counters = pool.writer_acquisition_counters();
    let busy_timeout = pool.config().busy_timeout;
    let origin = pool.origin();
    let backend_key = writer_db_key(pool);
    let db = crate::timeout_sink::db_label(pool);
    let (tx, rx) = mpsc::channel(capacity.max(1));
    let join = tokio::spawn(run_writer_task(
        conn,
        rx,
        origin,
        db.clone(),
        acquisition_counters,
        busy_timeout,
    ));
    // Stored on the pool (not returned) so the handle's clone-and-share
    // contract stays untouched; see ConnectionPool::take_writer_task_join
    // for who awaits it and why.
    pool.set_writer_task_join(join);
    Ok(WriterTaskHandle {
        tx,
        backend_key,
        db,
        slow_write_threshold: crate::timeout_sink::slow_write_threshold(),
        enqueue_timeout: std::time::Duration::from_millis(
            pool.config().write_admission_deadline_ms,
        ),
    })
}

/// Permanently close admission, then reply to every request that was already
/// accepted into the bounded channel without invoking its operation closure.
///
/// Closing before draining is load-bearing: draining an open receiver would
/// wait forever while [`WriterTaskHandle`] clones still exist, while dropping
/// the receiver immediately would discard buffered requests and their typed
/// reply senders.
async fn close_and_fail_queued_requests(rx: &mut mpsc::Receiver<Box<dyn AnyWriteRequest + Send>>) {
    rx.close();
    while let Some(request) = rx.recv().await {
        request.reply_error(writer_task_terminated(WriterTaskRequestState::NotStarted));
    }
}

/// Acquire the request transaction without multiplying its busy-timeout budget.
/// The setter is supplied so tests can fail SQLite's timeout update while still
/// executing real BEGIN statements; production uses `Connection::busy_timeout`.
fn begin_immediate_with_retry(
    conn: &Connection,
    acquisition_counters: &WriterAcquisitionCounters,
    busy_timeout: Duration,
    mut set_busy_timeout: impl FnMut(&Connection, Duration) -> rusqlite::Result<()>,
) -> (rusqlite::Result<()>, Duration, u32) {
    let transaction_acquire_started = Instant::now();
    let mut begin_attempt = 1_u32;
    let mut retry_delays = WRITER_BEGIN_RETRY_DELAYS.into_iter();
    let mut busy_timeout_lowered = false;
    let begin_outcome = loop {
        match conn.execute_batch("BEGIN IMMEDIATE") {
            Ok(()) => break Ok(()),
            Err(error) if crate::timeout_sink::is_busy_or_locked(&error) => {
                // Every busy/locked refusal is counted here,
                // whether or not it goes on to be retried: this
                // is the pre-PR meaning of the counter, and the
                // outer match below no longer counts the final
                // refusal a second time.
                acquisition_counters.record_writer_task_begin_busy();
                let Some(delay) = retry_delays.next() else {
                    break Err(error);
                };
                // The whole retry sequence shares one
                // `busy_timeout` budget: each SQLite attempt is
                // itself bounded by `busy_timeout`, so without a
                // shrinking budget three attempts could each
                // wait out a full window and multiply the
                // serialized writer's contention window instead
                // of bounding it.
                let remaining_budget =
                    busy_timeout.saturating_sub(transaction_acquire_started.elapsed());
                if remaining_budget.is_zero() {
                    break Err(error);
                }
                if let Err(set_err) = set_busy_timeout(conn, remaining_budget) {
                    tracing::warn!(
                        error = %set_err,
                        "writer task: failed to lower busy_timeout for BEGIN \
                         retry; surfacing the original busy refusal"
                    );
                    // A retry with the old timeout could exceed the shared budget.
                    break Err(error);
                }
                busy_timeout_lowered = true;
                // Count only refusals that will actually be retried. A failed
                // timeout reduction leaves this refusal visible to the caller.
                acquisition_counters.record_writer_task_begin_busy_absorbed();
                tracing::debug!(
                    attempt = begin_attempt,
                    backoff_ms = delay.as_millis() as u64,
                    budget_remaining_ms = remaining_budget.as_millis() as u64,
                    "writer task: BEGIN IMMEDIATE refused busy; retrying before \
                     request execution"
                );
                std::thread::sleep(delay);
                begin_attempt = begin_attempt.saturating_add(1);
            }
            Err(error) => break Err(error),
        }
    };
    let transaction_acquire = transaction_acquire_started.elapsed();
    // Restore the pool-configured busy_timeout only if a retry
    // actually lowered it, so the common uncontended request
    // never pays for an extra pragma write; the next request
    // dequeued on this same connection must still start from
    // the full configured budget.
    if busy_timeout_lowered {
        if let Err(restore_err) = set_busy_timeout(conn, busy_timeout) {
            tracing::warn!(
                error = %restore_err,
                "writer task: failed to restore busy_timeout after a BEGIN retry \
                 sequence"
            );
        }
    }
    (begin_outcome, transaction_acquire, begin_attempt)
}

/// Drain loop: the sole caller of `BEGIN IMMEDIATE` for write traffic routed
/// through the channel. Busy/locked `BEGIN IMMEDIATE` refusals receive the
/// bounded retry above before a final failure replies the request's error via
/// [`AnyWriteRequest::reply_error`] without invoking the request's closure.
///
/// A request-operation panic is contained inside the concrete
/// [`WriteRequest<R>`] so its typed reply survives. A panic, failed rollback,
/// or otherwise poisoned connection makes the task terminal. The task then
/// closes admission, explicitly fails every already-queued request as
/// [`WriterTaskRequestState::NotStarted`], and exits permanently. There is no
/// supervisor or connection restart; later sends observe the closed channel.
/// See
/// `crates/khive-db/docs/api/writer-task.md` for the full failure matrix.
async fn run_writer_task(
    mut conn: Connection,
    mut rx: mpsc::Receiver<Box<dyn AnyWriteRequest + Send>>,
    origin: khive_storage::tx_registry::TxOrigin,
    db: String,
    acquisition_counters: Arc<WriterAcquisitionCounters>,
    busy_timeout: Duration,
) {
    while let Some(request) = rx.recv().await {
        // The bounded-channel wait ends at this exact dequeue boundary.
        // Sampling inside the blocking closure would misattribute a saturated
        // Tokio blocking pool to writer-queue contention (#1849).
        let queue_wait = request.queue_wait();
        let origin = origin.clone();
        let blocking_counters = Arc::clone(&acquisition_counters);
        let outcome = tokio::task::spawn_blocking(move || {
            let acquisition_counters = blocking_counters;
            // A top-level request deliberately skips BEGIN, so it would
            // silently join any transaction leaked by an earlier request.
            // Refuse every request before dispatch if the connection is not
            // demonstrably clean, then retire the writer task.
            if !conn.is_autocommit() {
                tracing::error!(
                    "writer task: connection is not in autocommit mode before request dispatch; \
                     retiring the poisoned writer without running the request"
                );
                let request_state = WriterTaskRequestState::NotStarted;
                request.reply_error(writer_task_terminated(request_state));
                return (conn, Some(request_state));
            }

            let terminal_state = if request.is_top_level() {
                // ADR-067 Component A:
                // no BEGIN IMMEDIATE for this request — some statements
                // (e.g. VACUUM) are rejected by SQLite inside any open
                // transaction. Still runs on this task's dedicated
                // connection and still serialized one-request-at-a-time by
                // this same drain loop, so the single-writer guarantee
                // holds; only the transaction wrap is skipped.
                acquisition_counters.record_writer_task_acquisition();
                sealed::Sealed::execute_and_reply_top_level_reporting_terminal(
                    request, &conn, queue_wait,
                )
            } else {
                let tx_span = khive_storage::tx_registry::register_scoped(
                    Some("writer_task_tx".to_string()),
                    origin,
                );
                let (begin_outcome, transaction_acquire, begin_attempt) =
                    begin_immediate_with_retry(
                        &conn,
                        &acquisition_counters,
                        busy_timeout,
                        Connection::busy_timeout,
                    );
                match begin_outcome {
                    Ok(()) => {
                        acquisition_counters.record_writer_task_acquisition();
                        sealed::Sealed::execute_and_reply_reporting_terminal(
                            request,
                            &conn,
                            Some(tx_span),
                            queue_wait,
                            transaction_acquire,
                        )
                    }
                    Err(e) => {
                        // Do NOT run the request's operation: `conn` never
                        // entered a transaction, so executing the op's DML
                        // here would run in autocommit mode and land partial
                        // writes for a request the caller is about to be told
                        // failed.
                        tracing::warn!(
                            error = %e,
                            attempts = begin_attempt,
                            "writer task: BEGIN IMMEDIATE failed; replying an \
                             error without running the request's operation"
                        );
                        // Although BEGIN never opened a SQL transaction, the
                        // scoped attempt is observable in tx_registry. Drop
                        // it before waking the caller for the same reply-side
                        // lifecycle guarantee as successful requests (#1790).
                        drop(tx_span);
                        // A busy/locked refusal was already counted inside
                        // the retry loop above, including this final one —
                        // classifying and counting it again here would
                        // double it. Only a non-busy BEGIN failure (which
                        // never enters the retry loop's busy arm) still
                        // needs its counter recorded at this seam.
                        let begin_error = writer_task_begin_error(e, busy_timeout);
                        if !matches!(&begin_error, StorageError::WriterTaskBusy { .. }) {
                            acquisition_counters.record_writer_task_begin_error();
                        }
                        sealed::Sealed::reply_error_after_begin(
                            request,
                            begin_error,
                            queue_wait,
                            transaction_acquire,
                        );
                        None
                    }
                }
            };
            (conn, terminal_state)
        })
        .await;

        match outcome {
            Ok((returned_conn, None)) => conn = returned_conn,
            Ok((_returned_conn, Some(request_state))) => {
                acquisition_counters.record_writer_task_request_failure();
                if request_state == WriterTaskRequestState::SideEffectsUnknown {
                    acquisition_counters.record_writer_task_side_effects_unknown();
                }
                tracing::error!(
                    request_state = %request_state,
                    "writer task reached a terminal request or connection state; closing and \
                     failing the queue without restarting"
                );
                crate::timeout_sink::emit_writer_task_retirement(
                    &db,
                    &format!("terminal request state: {request_state}"),
                );
                close_and_fail_queued_requests(&mut rx).await;
                return;
            }
            Err(join_err) => {
                acquisition_counters.record_writer_task_request_failure();
                tracing::error!(
                    error = %join_err,
                    "writer task blocking closure failed outside the request \
                     panic boundary; closing and failing the queue without restarting"
                );
                crate::timeout_sink::emit_writer_task_retirement(
                    &db,
                    &format!("blocking closure join failure: {join_err}"),
                );
                close_and_fail_queued_requests(&mut rx).await;
                return;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pool::PoolConfig;
    use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
    use serial_test::serial;

    #[test]
    fn begin_error_classification_is_code_based_and_narrow() {
        for code in [rusqlite::ffi::SQLITE_BUSY, rusqlite::ffi::SQLITE_LOCKED] {
            let error = rusqlite::Error::SqliteFailure(
                rusqlite::ffi::Error::new(code),
                Some("rendered text is irrelevant".to_string()),
            );
            assert!(matches!(
                writer_task_begin_error(error, Duration::from_millis(175)),
                StorageError::WriterTaskBusy { timeout_ms: 175 }
            ));
        }

        let structural = rusqlite::Error::SqliteFailure(
            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CONSTRAINT),
            Some("database is locked".to_string()),
        );
        assert!(matches!(
            writer_task_begin_error(structural, Duration::from_millis(175)),
            StorageError::Pool { ref operation, .. } if operation == "writer_task_begin"
        ));
    }
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::mpsc as std_mpsc;
    use std::sync::{Arc, Mutex};
    use std::task::{Context, Poll, Wake, Waker};
    use std::time::Duration;

    fn file_pool(path: &std::path::Path) -> ConnectionPool {
        let cfg = PoolConfig {
            path: Some(path.to_path_buf()),
            ..PoolConfig::for_test()
        };
        ConnectionPool::new(cfg).expect("pool open")
    }

    fn deny_commit_and_rollback(ctx: AuthContext<'_>) -> Authorization {
        match ctx.action {
            // SQLite reports COMMIT as the non-exhaustive Unknown transaction
            // operation in rusqlite 0.40; ROLLBACK has its own variant.
            AuthAction::Transaction {
                operation: TransactionOperation::Unknown | TransactionOperation::Rollback,
            } => Authorization::Deny,
            _ => Authorization::Allow,
        }
    }

    fn deny_commit(ctx: AuthContext<'_>) -> Authorization {
        match ctx.action {
            AuthAction::Transaction {
                operation: TransactionOperation::Unknown,
            } => Authorization::Deny,
            _ => Authorization::Allow,
        }
    }

    fn deny_rollback(ctx: AuthContext<'_>) -> Authorization {
        match ctx.action {
            AuthAction::Transaction {
                operation: TransactionOperation::Rollback,
            } => Authorization::Deny,
            _ => Authorization::Allow,
        }
    }

    fn assert_writer_task_terminal_state<T: std::fmt::Debug>(
        result: Result<T, StorageError>,
        expected: WriterTaskRequestState,
    ) {
        match result {
            Err(StorageError::WriterTaskTerminated { request_state }) => {
                assert_eq!(request_state, expected)
            }
            other => panic!("expected WriterTaskTerminated({expected:?}), got {other:?}"),
        }
    }

    struct ParkedWake {
        entered: std_mpsc::SyncSender<()>,
        release: Mutex<std_mpsc::Receiver<()>>,
    }

    impl Wake for ParkedWake {
        fn wake(self: Arc<Self>) {
            self.entered
                .send(())
                .expect("reply sender must rendezvous with the test");
            self.release
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .recv()
                .expect("test must release the parked reply sender");
        }
    }

    fn arm_parked_wake<F: Future>(
        mut future: Pin<&mut F>,
    ) -> (std_mpsc::Receiver<()>, std_mpsc::Sender<()>) {
        let (entered_tx, entered_rx) = std_mpsc::sync_channel(0);
        let (release_tx, release_rx) = std_mpsc::channel();
        let waker = Waker::from(Arc::new(ParkedWake {
            entered: entered_tx,
            release: Mutex::new(release_rx),
        }));
        let mut context = Context::from_waker(&waker);
        assert!(
            matches!(future.as_mut().poll(&mut context), Poll::Pending),
            "writer send must remain pending until its operation replies"
        );
        (entered_rx, release_tx)
    }

    fn poll_ready<F: Future>(mut future: Pin<&mut F>) -> F::Output {
        let mut context = Context::from_waker(Waker::noop());
        match future.as_mut().poll(&mut context) {
            Poll::Ready(output) => output,
            Poll::Pending => panic!("reply wake must make the writer send ready"),
        }
    }

    fn database_tx_view(pool: &ConnectionPool) -> khive_storage::tx_registry::TxOriginFilter {
        match pool.origin() {
            khive_storage::tx_registry::TxOrigin::Database(identity) => {
                khive_storage::tx_registry::TxOriginFilter::Secondary(identity)
            }
            other => panic!("expected a file-backed database origin, got {other:?}"),
        }
    }

    async fn wait_for_writer_span_to_close(view: &khive_storage::tx_registry::TxOriginFilter) {
        tokio::time::timeout(Duration::from_secs(5), async {
            while khive_storage::tx_registry::any_open_labeled(view, "writer_task_tx") {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("writer task transaction span must eventually close");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[serial(tx_registry)]
    async fn successful_send_reply_waits_for_writer_tx_deregistration() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_success_reply_lifecycle.db");
        let pool = file_pool(&path);
        let view = database_tx_view(&pool);
        let handle = spawn(&pool, 8).expect("writer task spawn");
        let (op_started_tx, op_started_rx) = std_mpsc::sync_channel(0);
        let (op_release_tx, op_release_rx) = std_mpsc::channel();

        let send = handle.send(move |_conn| {
            op_started_tx
                .send(())
                .expect("operation must rendezvous with the test");
            op_release_rx
                .recv()
                .expect("test must release the operation");
            Ok::<_, StorageError>(())
        });
        tokio::pin!(send);
        let (reply_entered_rx, reply_release_tx) = arm_parked_wake(send.as_mut());

        op_started_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("writer operation must start");
        op_release_tx.send(()).expect("release writer operation");
        reply_entered_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("reply sender must wake the waiting caller");

        let reply = poll_ready(send.as_mut());
        let span_was_open_at_reply =
            khive_storage::tx_registry::any_open_labeled(&view, "writer_task_tx");

        reply_release_tx
            .send(())
            .expect("release parked reply sender");
        wait_for_writer_span_to_close(&view).await;

        reply.expect("committed operation reply");
        assert!(
            !span_was_open_at_reply,
            "a successful caller reply must not become observable while its committed writer_task_tx span remains registered"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[serial(tx_registry)]
    async fn begin_failure_reply_waits_for_writer_tx_deregistration() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_begin_reply_lifecycle.db");
        let cfg = PoolConfig {
            path: Some(path),
            busy_timeout: Duration::from_millis(150),
            ..PoolConfig::for_test()
        };
        let pool = ConnectionPool::new(cfg).unwrap();
        let view = database_tx_view(&pool);
        let handle = spawn(&pool, 8).expect("writer task spawn");
        let lock_holder = pool.try_writer().expect("pool writer");
        lock_holder
            .conn()
            .execute_batch("BEGIN IMMEDIATE")
            .expect("hold database write lock");
        let op_ran = Arc::new(AtomicBool::new(false));
        let op_ran_in_request = Arc::clone(&op_ran);

        let send = handle.send(move |_conn| {
            op_ran_in_request.store(true, Ordering::SeqCst);
            Ok::<_, StorageError>(())
        });
        tokio::pin!(send);
        let (reply_entered_rx, reply_release_tx) = arm_parked_wake(send.as_mut());
        reply_entered_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("BEGIN failure must wake the waiting caller");

        let reply = poll_ready(send.as_mut());
        let span_was_open_at_reply =
            khive_storage::tx_registry::any_open_labeled(&view, "writer_task_tx");

        reply_release_tx
            .send(())
            .expect("release parked reply sender");
        wait_for_writer_span_to_close(&view).await;
        lock_holder
            .conn()
            .execute_batch("ROLLBACK")
            .expect("release database write lock");

        assert!(
            matches!(
                &reply,
                Err(StorageError::WriterTaskBusy { timeout_ms }) if *timeout_ms == 150
            ),
            "expected typed retryable writer-task contention, got {reply:?}"
        );
        assert!(!op_ran.load(Ordering::SeqCst));
        assert!(
            !span_was_open_at_reply,
            "a BEGIN-failure caller reply must not become observable while its writer_task_tx span remains registered"
        );
    }

    // `#[serial(tx_registry)]`: `run_writer_task` registers a `writer_task_tx`
    // handle in the process-wide `tx_registry` singleton for the life of each
    // `BEGIN IMMEDIATE`. Tests that observe the registry (the checkpoint
    // `tx_age_sweep_*` group) read `tx_registry::oldest()`; an un-serialized
    // spawning test here would leak a longer-lived `writer_task_tx` into that
    // read and make the sweep name the wrong transaction. Share the key.
    #[tokio::test]
    #[serial(tx_registry)]
    async fn begin_immediate_failure_replies_error_without_running_op() {
        // Real lock contention, not a simulation: hold the database-level
        // write lock from the pool's own writer connection (the unmigrated
        // path this fix is guarding against) so the writer task's dedicated
        // connection genuinely fails `BEGIN IMMEDIATE` with `SQLITE_BUSY`
        // after a short `busy_timeout`.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_begin_failure.db");
        let cfg = PoolConfig {
            path: Some(path.clone()),
            busy_timeout: Duration::from_millis(150),
            ..PoolConfig::for_test()
        };
        let pool = ConnectionPool::new(cfg).unwrap();
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }

        let handle = spawn(&pool, 8).expect("writer task should spawn on a file-backed pool");

        let lock_holder = pool.try_writer().unwrap();
        lock_holder.conn().execute_batch("BEGIN IMMEDIATE").unwrap();

        let op_ran = Arc::new(AtomicBool::new(false));
        let op_ran_clone = Arc::clone(&op_ran);
        let result = handle
            .send(move |conn| {
                op_ran_clone.store(true, Ordering::SeqCst);
                conn.execute("INSERT INTO t (id, v) VALUES (99, 'should-not-land')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await;

        assert!(
            matches!(
                &result,
                Err(StorageError::WriterTaskBusy { timeout_ms }) if *timeout_ms == 150
            ),
            "expected a typed retryable error on contended BEGIN IMMEDIATE, got {result:?}"
        );
        assert!(
            !op_ran.load(Ordering::SeqCst),
            "the request's operation closure must never run when BEGIN \
             IMMEDIATE fails — running it would land a partial write in \
             autocommit mode for a request the caller is told failed"
        );

        // Release the contended lock, then verify no row landed from the
        // failed request.
        lock_holder.conn().execute_batch("ROLLBACK").unwrap();
        drop(lock_holder);

        handle
            .send(|conn| {
                conn.execute("INSERT INTO t (id, v) VALUES (100, 'next-request')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_insert_after_busy".into(),
                        message: e.to_string(),
                    })
            })
            .await
            .expect("transient contention must not retire the writer task");

        let reader = pool.reader().expect("reader");
        let count: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t WHERE id IN (99, 100)", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(
            count, 1,
            "the failed request must not land, while the next request commits on the same task"
        );
    }

    // `#[serial(tx_registry)]`: same rationale as
    // `begin_immediate_failure_replies_error_without_running_op`.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[serial(tx_registry)]
    async fn transient_begin_contention_clears_within_budget_and_op_runs_once() {
        // Hold a real SQLite write lock for a fixed, short delay — well
        // inside the configured busy_timeout — so SQLite's own internal
        // busy-handler wait absorbs the contention transparently within a
        // single `BEGIN IMMEDIATE` call. This is the common case the
        // shared retry budget (exercised by
        // `begin_retry_budget_makes_exactly_one_attempt_under_sustained_contention`
        // below) must not regress: recovery inside one busy_timeout window
        // should never touch the Rust-level retry loop or its counters.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_begin_transient_contention.db");
        let pool = ConnectionPool::new(PoolConfig {
            path: Some(path),
            busy_timeout: Duration::from_millis(500),
            ..PoolConfig::for_test()
        })
        .unwrap();
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
                .unwrap();
        }
        let handle = spawn(&pool, 8).expect("writer task spawn");
        let lock_holder = pool.try_writer().unwrap();
        lock_holder.conn().execute_batch("BEGIN IMMEDIATE").unwrap();

        let op_runs = Arc::new(AtomicUsize::new(0));
        let op_runs_in_request = Arc::clone(&op_runs);
        let send_future = handle.send(move |conn| {
            op_runs_in_request.fetch_add(1, Ordering::SeqCst);
            conn.execute("INSERT INTO t (id) VALUES (1)", [])
                .map_err(|error| StorageError::Pool {
                    operation: "test_insert_after_transient_contention".into(),
                    message: error.to_string(),
                })
        });
        let release_future = async {
            tokio::time::sleep(Duration::from_millis(50)).await;
            lock_holder.conn().execute_batch("ROLLBACK").unwrap();
        };
        let (result, ()) = tokio::join!(send_future, release_future);

        assert_eq!(
            result.expect("BEGIN IMMEDIATE succeeds once the transient lock clears"),
            1
        );
        assert_eq!(
            op_runs.load(Ordering::SeqCst),
            1,
            "the FnOnce request closure must execute exactly once"
        );

        let settled = pool.writer_acquisition_snapshot();
        assert_eq!(
            settled.writer_task_begin_busy, 0,
            "contention absorbed inside SQLite's own busy_timeout wait must never \
             surface as a Rust-level refusal"
        );
        assert_eq!(settled.writer_task_begin_busy_absorbed, 0);
        let reader = pool.reader().unwrap();
        let rows: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t", [], |row| row.get(0))
            .unwrap();
        assert_eq!(rows, 1, "exactly one closure execution commits one row");
    }

    // `#[serial(tx_registry)]`: same rationale as
    // `begin_immediate_failure_replies_error_without_running_op`.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[serial(tx_registry)]
    async fn transient_begin_refusal_retries_once_and_restores_timeout() {
        // Force the first contended BEGIN to return immediately, leaving
        // budget for the Rust retry. The holder is released only after that
        // refusal is counted, so an uncontended first attempt cannot pass.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_begin_transient_contention.db");
        let busy_timeout = Duration::from_secs(5);
        let configured_timeout_ms = i64::try_from(busy_timeout.as_millis()).unwrap();
        let pool = ConnectionPool::new(PoolConfig {
            path: Some(path),
            busy_timeout,
            ..PoolConfig::for_test()
        })
        .unwrap();
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
                .unwrap();
        }
        let handle = spawn(&pool, 8).expect("writer task spawn");
        let begin_attempts = Arc::new(AtomicUsize::new(0));
        let begin_attempts_in_setup = Arc::clone(&begin_attempts);
        handle
            .send_top_level(move |conn| {
                // A successful timeout reduction installs SQLite's normal busy
                // handler for attempt two; only the first refusal is immediate.
                conn.busy_handler(None)
                    .map_err(|error| StorageError::Internal(error.to_string()))?;
                count_begin_attempts(conn, begin_attempts_in_setup)
                    .map_err(|error| StorageError::Internal(error.to_string()))
            })
            .await
            .expect("install connection-local contention observers");
        let lock_holder = pool.try_writer().unwrap();
        lock_holder.conn().execute_batch("BEGIN IMMEDIATE").unwrap();

        let op_runs = Arc::new(AtomicUsize::new(0));
        let op_runs_in_request = Arc::clone(&op_runs);
        let send_future = handle.send(move |conn| {
            op_runs_in_request.fetch_add(1, Ordering::SeqCst);
            conn.execute("INSERT INTO t (id) VALUES (1)", [])
                .map_err(|error| StorageError::Pool {
                    operation: "test_insert_after_transient_contention".into(),
                    message: error.to_string(),
                })?;
            conn.query_row("PRAGMA busy_timeout", [], |row| row.get::<_, i64>(0))
                .map_err(|error| StorageError::Internal(error.to_string()))
        });
        let release_future = async {
            let observed = tokio::time::timeout(Duration::from_secs(2), async {
                while pool.writer_acquisition_snapshot().writer_task_begin_busy == 0 {
                    tokio::time::sleep(Duration::from_millis(1)).await;
                }
            })
            .await;
            // Release even when the handshake times out, so a failing test
            // cannot strand the writer behind its own fixture lock.
            lock_holder.conn().execute_batch("ROLLBACK").unwrap();
            observed.expect("first BEGIN refusal must be observed before releasing the lock");
        };
        let (result, ()) = tokio::join!(send_future, release_future);

        assert_eq!(
            result.expect("BEGIN IMMEDIATE succeeds once the transient lock clears"),
            configured_timeout_ms,
            "the configured timeout must be restored before the operation runs"
        );
        assert_eq!(
            begin_attempts.load(Ordering::SeqCst),
            2,
            "the request must actually retry BEGIN"
        );
        assert_eq!(
            op_runs.load(Ordering::SeqCst),
            1,
            "the FnOnce request closure must execute exactly once"
        );

        let settled = pool.writer_acquisition_snapshot();
        assert_eq!(
            settled.writer_task_begin_busy, 1,
            "the first real BEGIN refusal must be observed"
        );
        assert_eq!(settled.writer_task_begin_busy_absorbed, 1);
        let next_timeout = handle
            .send_top_level(|conn| {
                conn.query_row("PRAGMA busy_timeout", [], |row| row.get::<_, i64>(0))
                    .map_err(|error| StorageError::Internal(error.to_string()))
            })
            .await
            .unwrap();
        assert_eq!(
            next_timeout, configured_timeout_ms,
            "the next request must retain the configured timeout"
        );
        assert_eq!(
            begin_attempts.load(Ordering::SeqCst),
            2,
            "timeout probes and top-level setup must not count as BEGIN attempts"
        );
        let reader = pool.reader().unwrap();
        let rows: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t", [], |row| row.get(0))
            .unwrap();
        assert_eq!(rows, 1, "exactly one closure execution commits one row");
    }

    fn count_begin_attempts(conn: &Connection, attempts: Arc<AtomicUsize>) -> rusqlite::Result<()> {
        conn.authorizer(Some(move |context: AuthContext<'_>| {
            if matches!(
                context.action,
                AuthAction::Transaction {
                    operation: TransactionOperation::Begin
                }
            ) {
                attempts.fetch_add(1, Ordering::SeqCst);
            }
            Authorization::Allow
        }))
    }

    #[test]
    fn failed_busy_timeout_reduction_stops_before_a_second_begin() {
        let dir = tempfile::tempdir().unwrap();
        let pool = file_pool(&dir.path().join("writer_task_timeout_update_failure.db"));
        let conn = pool.open_standalone_writer_untracked().unwrap();
        let busy_timeout = Duration::from_secs(5);
        // Return BUSY before the budget expires, without manufacturing the
        // BEGIN result. Only the timeout setter below injects a failure.
        conn.busy_handler(None).unwrap();
        let original_timeout: i64 = conn
            .query_row("PRAGMA busy_timeout", [], |row| row.get(0))
            .unwrap();
        let attempts = Arc::new(AtomicUsize::new(0));
        count_begin_attempts(&conn, Arc::clone(&attempts)).unwrap();
        let lock_holder = pool.try_writer().unwrap();
        lock_holder.conn().execute_batch("BEGIN IMMEDIATE").unwrap();
        let counters = pool.writer_acquisition_counters();
        let mut timeout_updates = Vec::new();

        let (result, _, reported_attempts) =
            begin_immediate_with_retry(&conn, &counters, busy_timeout, |_, timeout| {
                timeout_updates.push(timeout);
                Err(rusqlite::Error::InvalidQuery)
            });

        let error = result.expect_err("failed timeout reduction must surface the busy refusal");
        assert_eq!(
            error.sqlite_error_code(),
            Some(rusqlite::ErrorCode::DatabaseBusy),
            "preserve the original BEGIN error, not the injected setter error"
        );
        assert_eq!(
            attempts.load(Ordering::SeqCst),
            1,
            "failed reduction must not issue a second BEGIN"
        );
        assert_eq!(reported_attempts as usize, attempts.load(Ordering::SeqCst));
        assert_eq!(timeout_updates.len(), 1, "a failed first update must not trigger retries or a spurious restoration call through the injected setter");
        assert!(timeout_updates[0] < busy_timeout);
        assert!(!timeout_updates[0].is_zero());
        let unchanged_timeout: i64 = conn
            .query_row("PRAGMA busy_timeout", [], |row| row.get(0))
            .unwrap();
        assert_eq!(
            unchanged_timeout, original_timeout,
            "the failed setter did not change the connection timeout"
        );
        assert!(
            conn.is_autocommit(),
            "the refused acquisition must not open a transaction"
        );
        let snapshot = pool.writer_acquisition_snapshot();
        assert_eq!(snapshot.writer_task_begin_busy, 1);
        assert_eq!(
            snapshot.writer_task_begin_busy_absorbed, 0,
            "an unretried refusal must not be counted as absorbed"
        );

        lock_holder.conn().execute_batch("ROLLBACK").unwrap();
        drop(lock_holder);
        conn.busy_timeout(busy_timeout).unwrap();
        let (positive, _, reported_attempts) =
            begin_immediate_with_retry(&conn, &counters, busy_timeout, Connection::busy_timeout);
        positive.expect(
            "the same connection and observer must see a valid BEGIN once contention clears",
        );
        assert_eq!(attempts.load(Ordering::SeqCst), 2);
        assert_eq!(
            reported_attempts, 1,
            "attempt count is local to this request"
        );
        conn.execute_batch("ROLLBACK").unwrap();
    }

    // `#[serial(tx_registry)]`: same rationale as
    // `begin_immediate_failure_replies_error_without_running_op`.
    #[tokio::test]
    #[serial(tx_registry)]
    async fn contended_begin_exhaustion_separates_absorbed_and_surfaced_refusals() {
        // Real contention: a refused write must be COUNTED, not merely
        // reported to its caller. Before this counter, `db_diagnostics`
        // showed a clean writer while requests were being refused after a
        // full busy timeout, so an operator could not distinguish this
        // daemon from one that had never refused a write.
        //
        // The lock is held continuously for the whole request, so SQLite's
        // own busy handler already spends the entire configured
        // `busy_timeout` internally before this call returns BUSY — the
        // shared retry budget introduced to bound total acquisition time to
        // one window (see `begin_retry_budget_makes_exactly_one_attempt_under_sustained_contention`)
        // is therefore already spent the instant this first refusal
        // surfaces, and no further attempt is retried. Real, sustained
        // contention against a single busy_timeout window can only ever
        // produce exactly one busy refusal and zero absorbed ones; a
        // multi-refusal absorbed sequence requires a refusal shape that
        // returns before the timeout elapses (for example SQLITE_LOCKED),
        // which this integration test cannot reproduce deterministically.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_begin_busy_counter.db");
        let cfg = PoolConfig {
            path: Some(path.clone()),
            busy_timeout: Duration::from_millis(150),
            ..PoolConfig::for_test()
        };
        let pool = ConnectionPool::new(cfg).unwrap();
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
                .unwrap();
        }

        let handle = spawn(&pool, 8).expect("writer task should spawn on a file-backed pool");

        let before = pool.writer_acquisition_snapshot();
        assert_eq!(
            before.writer_task_begin_busy, 0,
            "baseline: nothing has been refused yet"
        );
        assert_eq!(before.writer_task_begin_busy_absorbed, 0);

        let lock_holder = pool.try_writer().unwrap();
        lock_holder.conn().execute_batch("BEGIN IMMEDIATE").unwrap();

        let result = handle
            .send(|conn| {
                conn.execute("INSERT INTO t (id) VALUES (1)", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await;
        assert!(
            matches!(&result, Err(StorageError::WriterTaskBusy { .. })),
            "precondition: the request must actually be refused busy, got {result:?}"
        );

        let after = pool.writer_acquisition_snapshot();
        assert_eq!(
            after.writer_task_begin_busy, 1,
            "the single refusal the caller was told about must still be counted"
        );
        assert_eq!(
            after.writer_task_begin_busy_absorbed, 0,
            "a refusal that already spent the whole shared budget waiting out \
             SQLite's own busy handler must not be retried, so nothing is absorbed"
        );
        assert_eq!(
            after.writer_task_begin_errors, 0,
            "a busy refusal must not be counted as a non-busy BEGIN error"
        );
        assert_eq!(
            after.timeouts, before.timeouts,
            "a writer-task BEGIN refusal must not be mislabeled as a pool-mutex \
             checkout timeout — separate ADR-135 F6 stages, separate counters"
        );

        // Discriminating arm: a SUCCEEDING request must not move the failure
        // counter. Without this the assertion above would also pass against a
        // counter that simply counted every request.
        lock_holder.conn().execute_batch("ROLLBACK").unwrap();
        drop(lock_holder);
        handle
            .send(|conn| {
                conn.execute("INSERT INTO t (id) VALUES (2)", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_insert_after_busy".into(),
                        message: e.to_string(),
                    })
            })
            .await
            .expect("the writer task survives transient contention");

        let settled = pool.writer_acquisition_snapshot();
        assert_eq!(
            settled.writer_task_begin_busy, 1,
            "a successful request must leave the refusal counter untouched"
        );
        assert_eq!(
            settled.writer_task_begin_busy_absorbed, 0,
            "an uncontended request must not move the absorbed counter"
        );
        assert!(
            settled.writer_task_acquisitions > after.writer_task_acquisitions,
            "and it must still register as a success"
        );
    }

    // `#[serial(tx_registry)]`: same rationale as
    // `begin_immediate_failure_replies_error_without_running_op`.
    #[tokio::test]
    #[serial(tx_registry)]
    async fn begin_retry_budget_makes_exactly_one_attempt_under_sustained_contention() {
        // Before this fix, three BEGIN attempts each ran under their own
        // full `busy_timeout`, so persistent contention could hold the
        // serialized writer for roughly three windows plus the 15 ms of
        // explicit backoff. A held writer lock that is never released for
        // the life of this test reproduces that persistent contention:
        // total time from send to the final refusal must stay within one
        // busy_timeout window plus the sleeps, not three.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_begin_retry_budget.db");
        let busy_timeout = Duration::from_millis(150);
        let cfg = PoolConfig {
            path: Some(path),
            busy_timeout,
            ..PoolConfig::for_test()
        };
        let pool = ConnectionPool::new(cfg).unwrap();
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
                .unwrap();
        }

        let handle = spawn(&pool, 8).expect("writer task should spawn on a file-backed pool");
        let lock_holder = pool.try_writer().unwrap();
        lock_holder.conn().execute_batch("BEGIN IMMEDIATE").unwrap();

        let result = handle
            .send(|conn| {
                conn.execute("INSERT INTO t (id) VALUES (1)", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await;

        assert!(
            matches!(&result, Err(StorageError::WriterTaskBusy { .. })),
            "precondition: the request must actually be refused busy, got {result:?}"
        );
        // Against a lock that is never released, SQLite's busy handler spends
        // the whole configured window inside the first `BEGIN IMMEDIATE`, so
        // the shared budget is exhausted the moment that refusal surfaces:
        // exactly one attempt is made and nothing is absorbed. Three
        // unbounded attempts would have recorded two absorbed refusals and
        // waited roughly three windows. The attempt count is the bound's
        // deterministic signature; wall-clock time is not asserted because
        // scheduler delay on a loaded host dwarfs a 150 ms window.
        let counters = pool.writer_acquisition_snapshot();
        assert_eq!(
            counters.writer_task_begin_busy, 1,
            "one busy refusal must surface after the shared budget is spent"
        );
        assert_eq!(
            counters.writer_task_begin_busy_absorbed, 0,
            "a refusal that already consumed the whole budget must not be retried"
        );

        lock_holder.conn().execute_batch("ROLLBACK").unwrap();
    }

    // `#[serial(tx_registry)]`: shares the key with the checkpoint
    // `tx_age_sweep_*` tests — see the note on
    // `begin_immediate_failure_replies_error_without_running_op`.
    #[tokio::test]
    #[serial(tx_registry)]
    async fn writer_task_executes_op_and_commits() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_commit.db");
        let pool = file_pool(&path);
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }

        let handle = spawn(&pool, 8).expect("writer task should spawn on a file-backed pool");

        let affected = handle
            .send(|conn| {
                conn.execute("INSERT INTO t (id, v) VALUES (1, 'hello')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await
            .expect("op should succeed");
        assert_eq!(affected, 1);

        // Verify the write actually committed to the shared file — read it
        // back via a fresh pooled reader connection, not the writer task's
        // own connection.
        let reader = pool.reader().expect("reader");
        let v: String = reader
            .conn()
            .query_row("SELECT v FROM t WHERE id = 1", [], |row| row.get(0))
            .expect("row must be committed and visible to a reader");
        assert_eq!(v, "hello");

        let counters = pool.writer_acquisition_snapshot();
        assert_eq!(counters.acquisitions, 2);
        assert_eq!(counters.pooled_acquisitions, 1);
        assert_eq!(counters.standalone_acquisitions, 0);
        assert_eq!(counters.writer_task_acquisitions, 1);
        assert_eq!(counters.timeouts, 0);
    }

    #[tokio::test]
    async fn writer_task_connection_follows_checkpoint_ownership_claim() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_autocheckpoint.db");
        let pool = file_pool(&path);
        // The pool-registered handle (not a directly spawned side task):
        // `propagate_checkpoint_claim_to_writer_task` reaches exactly this
        // task's connection.
        let handle = pool
            .writer_task_handle()
            .expect("writer task should spawn")
            .expect("file-backed pool resolves the write queue on");

        let read_pages = |handle: &WriterTaskHandle| {
            let handle = handle.clone();
            async move {
                handle
                    .send_top_level(|conn| {
                        conn.pragma_query_value(None, "wal_autocheckpoint", |row| {
                            row.get::<_, u32>(0)
                        })
                        .map_err(|e| StorageError::Pool {
                            operation: "test_wal_autocheckpoint".into(),
                            message: e.to_string(),
                        })
                    })
                    .await
                    .expect("query writer-task connection pragma")
            }
        };

        // Spawned before any claim: the task's long-lived connection keeps
        // the bounded fallback.
        assert_eq!(
            read_pages(&handle).await,
            crate::pool::FALLBACK_WAL_AUTOCHECKPOINT_PAGES
        );

        // After the claim propagates, the same connection is flipped to the
        // dedicated-owner setting without reopening.
        pool.claim_checkpoint_ownership().expect("claim ownership");
        pool.propagate_checkpoint_claim_to_writer_task()
            .await
            .expect("propagate claim to the running writer task");
        assert_eq!(read_pages(&handle).await, 0);
    }

    #[test]
    fn spawn_fails_on_in_memory_pool() {
        // In-memory pools have no standalone-connection support
        // (the infrastructure-only standalone open) — `spawn` must surface
        // that as an error rather than panicking. Deliberately a plain
        // `#[test]` (no Tokio runtime): `spawn` fails before it ever reaches
        // `tokio::spawn`, so no runtime is required for this path.
        let cfg = PoolConfig {
            path: None,
            ..PoolConfig::default()
        };
        let pool = ConnectionPool::new(cfg).unwrap();
        let result = spawn(&pool, 8);
        assert!(
            result.is_err(),
            "in-memory pools must reject spawn, not panic"
        );
    }

    #[tokio::test]
    async fn full_channel_applies_backpressure_not_immediate_error() {
        // Build the channel directly (bypassing `spawn`/`run_writer_task`)
        // so nothing ever drains it — deterministic control over "the
        // channel is full" instead of racing a real writer task's
        // processing speed.
        let (tx, _rx) = mpsc::channel::<Box<dyn AnyWriteRequest + Send>>(1);
        let handle = WriterTaskHandle {
            tx,
            backend_key: None,
            db: "test".to_string(),
            slow_write_threshold: None,
            enqueue_timeout: Duration::from_secs(5),
        };

        // First send fills the sole channel slot. Its reply never arrives
        // since nothing drains `_rx`, so run it in the background.
        let first = tokio::spawn({
            let handle = handle.clone();
            async move {
                let _ = handle.send(|_conn| Ok::<(), StorageError>(())).await;
            }
        });

        // Give the first send a moment to occupy the channel slot.
        tokio::time::sleep(Duration::from_millis(20)).await;

        // Second send must block (backpressure), not fail immediately: a
        // short timeout should elapse rather than resolve.
        let second = tokio::time::timeout(
            Duration::from_millis(100),
            handle.send(|_conn| Ok::<(), StorageError>(())),
        )
        .await;

        assert!(
            second.is_err(),
            "a full channel must apply backpressure (send suspends) rather \
             than erroring immediately — no try_send escape hatch per ADR-067"
        );

        first.abort();
    }

    #[tokio::test]
    async fn send_with_timeout_maps_full_channel_to_write_queue_full() {
        let (tx, _rx) = mpsc::channel::<Box<dyn AnyWriteRequest + Send>>(1);
        let handle = WriterTaskHandle {
            tx,
            backend_key: None,
            db: "test".to_string(),
            slow_write_threshold: None,
            enqueue_timeout: Duration::from_secs(5),
        };

        let first = tokio::spawn({
            let handle = handle.clone();
            async move {
                let _ = handle.send(|_conn| Ok::<(), StorageError>(())).await;
            }
        });
        tokio::time::sleep(Duration::from_millis(20)).await;

        let result = handle
            .send_with_timeout(
                |_conn| Ok::<(), StorageError>(()),
                Duration::from_millis(50),
            )
            .await;

        match result {
            Err(StorageError::WriteQueueFull { timeout_ms }) => assert_eq!(timeout_ms, 50),
            other => panic!("expected WriteQueueFull, got {other:?}"),
        }

        first.abort();
    }

    #[tokio::test]
    async fn configured_enqueue_timeout_rejects_only_unaccepted_request() {
        // A real file-backed writer task: `send_bounded` reuses
        // `PoolConfig::write_admission_deadline_ms` (ADR-131 Decision 2) as
        // its enqueue deadline, captured at `spawn`, so this must exercise
        // the actual spawn path rather than a hand-built channel (#1382).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("configured_enqueue_timeout.db");
        let cfg = PoolConfig {
            path: Some(path.clone()),
            write_admission_deadline_ms: 100,
            ..PoolConfig::for_test()
        };
        let pool = ConnectionPool::new(cfg).unwrap();
        let handle = spawn(&pool, 1).expect("writer task should spawn on a file-backed pool");

        // Request A: dequeued and running (inside `spawn_blocking`), blocked
        // on a test-controlled channel so the writer task's single drain
        // slot stays occupied deterministically — no sleeps.
        let (started_tx, started_rx) = oneshot::channel::<()>();
        let (release_tx, release_rx) = std_mpsc::channel::<()>();
        let handle_a = handle.clone();
        let a_task = tokio::spawn(async move {
            handle_a
                .send(move |_conn| {
                    let _ = started_tx.send(());
                    release_rx.recv().expect("test must release request A");
                    Ok::<(), StorageError>(())
                })
                .await
        });
        tokio::time::timeout(Duration::from_secs(5), started_rx)
            .await
            .expect("request A did not start")
            .expect("request A dropped its start signal");

        // Request B: A has been dequeued (freeing the one channel slot), so
        // the private `enqueue` helper proves B is accepted and now occupies
        // that slot, without waiting for A to finish.
        let b_reply_rx = tokio::time::timeout(
            Duration::from_secs(5),
            handle.enqueue(|_conn| Ok::<(), StorageError>(())),
        )
        .await
        .expect("B must be accepted promptly")
        .expect("B must be accepted: the one channel slot is free while A drains");

        // Request C: the channel is now full (A draining, B queued behind
        // it) — `send_bounded` must reject C on the configured
        // `write_admission_deadline_ms` without ever running its closure.
        let c_ran = Arc::new(AtomicBool::new(false));
        let c_ran_in_op = Arc::clone(&c_ran);
        let c_result = handle
            .send_bounded(move |_conn| {
                c_ran_in_op.store(true, Ordering::SeqCst);
                Ok::<(), StorageError>(())
            })
            .await;
        match c_result {
            Err(StorageError::WriteQueueFull { .. }) => {}
            other => panic!("expected WriteQueueFull, got {other:?}"),
        }
        assert!(!c_ran.load(Ordering::SeqCst), "C must never run");

        // Release A; both A and B must then complete normally.
        release_tx.send(()).expect("release request A");
        tokio::time::timeout(Duration::from_secs(5), a_task)
            .await
            .expect("A did not complete")
            .expect("A task join")
            .expect("A must complete successfully");
        tokio::time::timeout(Duration::from_secs(5), b_reply_rx)
            .await
            .expect("B did not reply")
            .expect("B's reply channel must not be dropped")
            .expect("B must complete successfully");
    }

    // `#[serial(tx_registry)]`: this test deliberately keeps a request (and
    // thus its `writer_task_tx` registry handle) alive past a timeout, so it is
    // the worst polluter of the checkpoint `tx_age_sweep_*` reads if left
    // un-serialized. Shares the key — see the note on
    // `begin_immediate_failure_replies_error_without_running_op`.
    #[tokio::test]
    #[serial(tx_registry)]
    async fn send_with_timeout_returns_op_result_when_op_outlives_the_timeout() {
        // `send_with_timeout`'s timeout must bound ONLY the enqueue step —
        // never the reply-wait. An accepted request (channel not full) must
        // run to completion and report its REAL result even when that takes
        // longer than `timeout`; before this fix, wrapping the whole
        // send-plus-reply-wait in one timeout would misreport this as
        // `WriteQueueFull` despite the write actually landing.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_slow_op.db");
        let pool = file_pool(&path);
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }

        let handle = spawn(&pool, 8).expect("writer task should spawn on a file-backed pool");

        let result = handle
            .send_with_timeout(
                |conn| {
                    // Deliberately slower than the timeout below: proves the
                    // reply-wait itself is never bounded by `timeout`.
                    std::thread::sleep(Duration::from_millis(150));
                    conn.execute("INSERT INTO t (id, v) VALUES (1, 'slow')", [])
                        .map_err(|e| StorageError::Pool {
                            operation: "test_insert".into(),
                            message: e.to_string(),
                        })
                },
                Duration::from_millis(20),
            )
            .await;

        let affected = result.expect(
            "an accepted request must return its real result even when the \
             op takes longer than the enqueue timeout, not WriteQueueFull",
        );
        assert_eq!(affected, 1);

        // The slow op's write must have actually committed, not just been
        // reported as successful.
        let reader = pool.reader().expect("reader");
        let v: String = reader
            .conn()
            .query_row("SELECT v FROM t WHERE id = 1", [], |row| row.get(0))
            .expect("the slow op's write must have committed");
        assert_eq!(v, "slow");
    }

    #[tokio::test]
    #[serial(tx_registry)]
    async fn operation_failure_with_successful_rollback_reports_finality_once_and_continues() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_operation_rollback.db");
        let pool = file_pool(&path);
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }
        let handle = spawn(&pool, 8).expect("writer task spawn");

        let executions = Arc::new(AtomicUsize::new(0));
        let executions_in_op = Arc::clone(&executions);
        let original_error = handle
            .send(move |conn| -> Result<(), StorageError> {
                executions_in_op.fetch_add(1, Ordering::SeqCst);
                conn.execute("INSERT INTO t (id, v) VALUES (1, 'rolled-back')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_operation_error_insert".into(),
                        message: e.to_string(),
                    })?;
                Err(StorageError::Internal(
                    "intentional operation failure".into(),
                ))
            })
            .await;
        match &original_error {
            Err(StorageError::WriterTaskRequestFailed {
                request_state: WriterTaskRequestState::TransactionRolledBack,
                source,
            }) => assert!(
                matches!(source.as_ref(), StorageError::Internal(message)
                    if message == "intentional operation failure"),
                "the proven-rollback wrapper must retain the typed operation error: {source:?}"
            ),
            other => panic!(
                "a confirmed rollback must carry TransactionRolledBack and preserve the operation error, got {other:?}"
            ),
        }
        assert_eq!(
            executions.load(Ordering::SeqCst),
            1,
            "finality propagation must not replay the request closure"
        );

        let affected = handle
            .send(|conn| {
                conn.execute("INSERT INTO t (id, v) VALUES (2, 'committed')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_operation_error_followup_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await
            .expect("the writer must continue after a confirmed rollback");
        assert_eq!(affected, 1);
        assert_eq!(
            executions.load(Ordering::SeqCst),
            1,
            "serving a follow-up request must not replay the rolled-back closure"
        );

        let reader = pool.reader().expect("reader");
        let rolled_back: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t WHERE id = 1", [], |row| row.get(0))
            .unwrap();
        let committed: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t WHERE id = 2", [], |row| row.get(0))
            .unwrap();
        assert_eq!(rolled_back, 0);
        assert_eq!(committed, 1);
    }

    #[tokio::test]
    #[serial(tx_registry)]
    async fn commit_failure_with_successful_rollback_reports_finality_once_and_continues() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_commit_rollback.db");
        let pool = file_pool(&path);
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }
        let handle = spawn(&pool, 8).expect("writer task spawn");

        let executions = Arc::new(AtomicUsize::new(0));
        let executions_in_op = Arc::clone(&executions);
        let commit_error = handle
            .send(move |conn| -> Result<usize, StorageError> {
                executions_in_op.fetch_add(1, Ordering::SeqCst);
                let affected = conn
                    .execute("INSERT INTO t (id, v) VALUES (1, 'rolled-back')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_commit_error_insert".into(),
                        message: e.to_string(),
                    })?;
                conn.authorizer(Some(deny_commit))
                    .map_err(|e| StorageError::Pool {
                        operation: "test_install_authorizer".into(),
                        message: e.to_string(),
                    })?;
                Ok(affected)
            })
            .await;
        match &commit_error {
            Err(StorageError::WriterTaskRequestFailed {
                request_state: WriterTaskRequestState::TransactionRolledBack,
                source,
            }) => assert!(
                matches!(source.as_ref(), StorageError::Pool { operation, .. }
                    if operation == "writer_task_commit"),
                "the proven-rollback wrapper must retain the typed COMMIT error: {source:?}"
            ),
            other => panic!(
                "a confirmed rollback must carry TransactionRolledBack and preserve the COMMIT error, got {other:?}"
            ),
        }
        assert!(
            commit_error
                .as_ref()
                .expect_err("COMMIT must be denied")
                .is_retryable(),
            "the existing retryable commit-error contract must remain unchanged after a \
             confirmed rollback"
        );
        assert_eq!(
            executions.load(Ordering::SeqCst),
            1,
            "finality propagation must not replay the request closure"
        );

        let affected = handle
            .send(|conn| {
                conn.authorizer(None::<fn(AuthContext<'_>) -> Authorization>)
                    .map_err(|e| StorageError::Pool {
                        operation: "test_remove_authorizer".into(),
                        message: e.to_string(),
                    })?;
                conn.execute("INSERT INTO t (id, v) VALUES (2, 'committed')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_commit_error_followup_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await
            .expect("the writer must continue after the failed COMMIT is rolled back");
        assert_eq!(affected, 1);
        assert_eq!(
            executions.load(Ordering::SeqCst),
            1,
            "serving a follow-up request must not replay the rolled-back closure"
        );

        let reader = pool.reader().expect("reader");
        let rolled_back: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t WHERE id = 1", [], |row| row.get(0))
            .unwrap();
        let committed: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t WHERE id = 2", [], |row| row.get(0))
            .unwrap();
        assert_eq!(rolled_back, 0);
        assert_eq!(committed, 1);
    }

    #[test]
    fn top_level_request_returning_with_open_transaction_reports_side_effects_unknown() {
        let conn = Connection::open_in_memory().expect("in-memory connection");
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
            .unwrap();
        let (reply_tx, mut reply_rx) = oneshot::channel();
        let request = WriteRequest {
            op: Box::new(|conn| -> Result<usize, StorageError> {
                conn.execute_batch("BEGIN IMMEDIATE")
                    .map_err(|e| StorageError::Pool {
                        operation: "test_top_level_begin".into(),
                        message: e.to_string(),
                    })?;
                conn.execute("INSERT INTO t (id) VALUES (1)", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_top_level_insert".into(),
                        message: e.to_string(),
                    })
            }),
            reply: reply_tx,
            top_level: true,
            telemetry: WriteTelemetry::new(None, "test".to_string(), 0, None),
        };

        let terminal_state = sealed::Sealed::execute_and_reply_top_level_reporting_terminal(
            Box::new(request),
            &conn,
            Duration::ZERO,
        );
        assert_eq!(
            terminal_state,
            Some(WriterTaskRequestState::SideEffectsUnknown)
        );
        let reply = reply_rx
            .try_recv()
            .expect("active request must receive a typed terminal reply");
        assert_writer_task_terminal_state(reply, WriterTaskRequestState::SideEffectsUnknown);
        assert!(
            !conn.is_autocommit(),
            "the fixture must prove the post-request autocommit check observed an open transaction"
        );
    }

    #[test]
    fn commit_failure_with_failed_rollback_reports_side_effects_unknown() {
        let conn = Connection::open_in_memory().expect("in-memory connection");
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY); BEGIN IMMEDIATE")
            .unwrap();
        let executions = Arc::new(AtomicUsize::new(0));
        let executions_in_op = Arc::clone(&executions);
        let (reply_tx, mut reply_rx) = oneshot::channel();
        let request = WriteRequest {
            op: Box::new(move |conn| -> Result<usize, StorageError> {
                executions_in_op.fetch_add(1, Ordering::SeqCst);
                let affected = conn
                    .execute("INSERT INTO t (id) VALUES (1)", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_insert_before_commit_failure".into(),
                        message: e.to_string(),
                    })?;
                conn.authorizer(Some(deny_commit_and_rollback))
                    .map_err(|e| StorageError::Pool {
                        operation: "test_install_authorizer".into(),
                        message: e.to_string(),
                    })?;
                Ok(affected)
            }),
            reply: reply_tx,
            top_level: false,
            telemetry: WriteTelemetry::new(None, "test".to_string(), 0, None),
        };

        let terminal_state = sealed::Sealed::execute_and_reply_reporting_terminal(
            Box::new(request),
            &conn,
            None,
            Duration::ZERO,
            Duration::ZERO,
        );
        assert_eq!(
            terminal_state,
            Some(WriterTaskRequestState::SideEffectsUnknown)
        );
        let reply = reply_rx
            .try_recv()
            .expect("active request must receive a typed terminal reply");
        assert_writer_task_terminal_state(reply, WriterTaskRequestState::SideEffectsUnknown);
        assert_eq!(executions.load(Ordering::SeqCst), 1);
        assert!(
            !conn.is_autocommit(),
            "the denied COMMIT and ROLLBACK must leave the test connection poisoned"
        );
    }

    #[tokio::test]
    #[serial(tx_registry)]
    async fn poisoned_connection_retires_before_queued_top_level_request() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_rollback_poison.db");
        let pool = file_pool(&path);
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }
        let handle = spawn(&pool, 8).expect("writer task spawn");
        let (started_tx, started_rx) = oneshot::channel::<()>();
        let (release_tx, release_rx) = std_mpsc::channel::<()>();

        let active = tokio::spawn({
            let handle = handle.clone();
            async move {
                handle
                    .send(move |conn| -> Result<usize, StorageError> {
                        let affected = conn
                            .execute("INSERT INTO t (id, v) VALUES (1, 'active')", [])
                            .map_err(|e| StorageError::Pool {
                                operation: "test_active_insert".into(),
                                message: e.to_string(),
                            })?;
                        conn.authorizer(Some(deny_commit_and_rollback))
                            .map_err(|e| StorageError::Pool {
                                operation: "test_install_authorizer".into(),
                                message: e.to_string(),
                            })?;
                        let _ = started_tx.send(());
                        release_rx.recv().expect("test must release active op");
                        Ok(affected)
                    })
                    .await
            }
        });

        tokio::time::timeout(Duration::from_secs(5), started_rx)
            .await
            .expect("active request did not start")
            .expect("active request dropped its start signal");

        let queued_ran = Arc::new(AtomicBool::new(false));
        let queued_ran_in_op = Arc::clone(&queued_ran);
        let queued_top_level = handle
            .enqueue_inner(
                move |conn| {
                    queued_ran_in_op.store(true, Ordering::SeqCst);
                    conn.execute("INSERT INTO t (id, v) VALUES (2, 'queued')", [])
                        .map_err(|e| StorageError::Pool {
                            operation: "test_queued_top_level_insert".into(),
                            message: e.to_string(),
                        })
                },
                true,
            )
            .await
            .expect("top-level request must queue behind active request");
        release_tx.send(()).expect("release active op");

        let active_result = tokio::time::timeout(Duration::from_secs(5), active)
            .await
            .expect("active caller hung after rollback failure")
            .expect("active caller task join");
        assert_writer_task_terminal_state(
            active_result,
            WriterTaskRequestState::SideEffectsUnknown,
        );

        let queued_result = tokio::time::timeout(Duration::from_secs(5), queued_top_level)
            .await
            .expect("queued top-level caller hung after terminal failure")
            .expect("terminal drain must preserve queued typed reply");
        assert_writer_task_terminal_state(queued_result, WriterTaskRequestState::NotStarted);
        assert!(
            !queued_ran.load(Ordering::SeqCst),
            "a top-level request must never run on the poisoned connection"
        );

        let future_ran = Arc::new(AtomicBool::new(false));
        let future_ran_in_op = Arc::clone(&future_ran);
        let future_result = handle
            .send_top_level(move |_conn| {
                future_ran_in_op.store(true, Ordering::SeqCst);
                Ok::<(), StorageError>(())
            })
            .await;
        assert_writer_task_terminal_state(future_result, WriterTaskRequestState::NotStarted);
        assert!(!future_ran.load(Ordering::SeqCst));
    }

    #[test]
    fn operation_failure_with_failed_rollback_reports_side_effects_unknown() {
        let conn = Connection::open_in_memory().expect("in-memory connection");
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY); BEGIN IMMEDIATE")
            .unwrap();
        let executions = Arc::new(AtomicUsize::new(0));
        let executions_in_op = Arc::clone(&executions);
        let (reply_tx, mut reply_rx) = oneshot::channel();
        let request = WriteRequest {
            op: Box::new(move |conn| -> Result<(), StorageError> {
                executions_in_op.fetch_add(1, Ordering::SeqCst);
                conn.authorizer(Some(deny_rollback))
                    .map_err(|e| StorageError::Pool {
                        operation: "test_install_authorizer".into(),
                        message: e.to_string(),
                    })?;
                Err(StorageError::Internal(
                    "intentional operation failure before denied rollback".into(),
                ))
            }),
            reply: reply_tx,
            top_level: false,
            telemetry: WriteTelemetry::new(None, "test".to_string(), 0, None),
        };

        let terminal_state = sealed::Sealed::execute_and_reply_reporting_terminal(
            Box::new(request),
            &conn,
            None,
            Duration::ZERO,
            Duration::ZERO,
        );
        assert_eq!(
            terminal_state,
            Some(WriterTaskRequestState::SideEffectsUnknown)
        );
        let reply = reply_rx
            .try_recv()
            .expect("active request must receive a typed terminal reply");
        assert_writer_task_terminal_state(reply, WriterTaskRequestState::SideEffectsUnknown);
        assert_eq!(executions.load(Ordering::SeqCst), 1);
        assert!(
            !conn.is_autocommit(),
            "the denied ROLLBACK must leave the test connection poisoned"
        );
    }

    #[test]
    fn wrapped_panic_with_failed_rollback_reports_side_effects_unknown() {
        let conn = Connection::open_in_memory().expect("in-memory connection");
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY); BEGIN IMMEDIATE")
            .unwrap();
        let (reply_tx, mut reply_rx) = oneshot::channel();
        let request = WriteRequest {
            op: Box::new(|conn| -> Result<(), StorageError> {
                // Deliberately violate WriteOp's no-COMMIT contract to create
                // the otherwise rare but reachable rollback-failure state.
                // The row commits before the panic, so reporting a successful
                // rollback here would be dangerously false.
                conn.execute_batch("INSERT INTO t (id) VALUES (1); COMMIT")
                    .map_err(|e| StorageError::Pool {
                        operation: "test_force_rollback_failure".into(),
                        message: e.to_string(),
                    })?;
                panic!("intentional panic after illicit commit");
            }),
            reply: reply_tx,
            top_level: false,
            telemetry: WriteTelemetry::new(None, "test".to_string(), 0, None),
        };

        let terminal_state = sealed::Sealed::execute_and_reply_reporting_terminal(
            Box::new(request),
            &conn,
            None,
            Duration::ZERO,
            Duration::ZERO,
        );
        assert_eq!(
            terminal_state,
            Some(WriterTaskRequestState::SideEffectsUnknown)
        );
        let reply = reply_rx
            .try_recv()
            .expect("active request must receive a typed terminal reply");
        assert_writer_task_terminal_state(reply, WriterTaskRequestState::SideEffectsUnknown);

        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM t", [], |row| row.get(0))
            .unwrap();
        assert_eq!(
            count, 1,
            "the fixture's committed side effect proves why the state must be unknown"
        );
    }

    // `#[serial(tx_registry)]`: the active request holds a registered
    // `writer_task_tx` until its panic is caught and rolled back. Share the
    // process-wide registry key with the other writer-task transaction tests.
    #[tokio::test]
    #[serial(tx_registry)]
    async fn wrapped_panic_rolls_back_and_terminally_fails_queue() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_wrapped_panic.db");
        let cfg = PoolConfig {
            path: Some(path),
            write_queue_enabled: Some(true),
            write_queue_capacity: 8,
            ..PoolConfig::for_test()
        };
        let pool = ConnectionPool::new(cfg).unwrap();
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }

        // Use the pool-owned OnceLock path rather than `spawn` directly so
        // the test also proves a terminal task is never silently replaced.
        let handle = pool
            .writer_task_handle()
            .expect("writer task lookup")
            .expect("file-backed queued pool must spawn its writer task");
        assert_eq!(pool.writer_task_spawn_count(), 1);

        let (started_tx, started_rx) = oneshot::channel::<()>();
        let (release_tx, release_rx) = std_mpsc::channel::<()>();
        let active = tokio::spawn({
            let handle = handle.clone();
            async move {
                handle
                    .send(move |conn| -> Result<usize, StorageError> {
                        conn.execute("INSERT INTO t (id, v) VALUES (1, 'active')", [])
                            .map_err(|e| StorageError::Pool {
                                operation: "test_active_insert".into(),
                                message: e.to_string(),
                            })?;
                        let _ = started_tx.send(());
                        release_rx.recv().expect("test must release active op");
                        panic!("intentional wrapped writer request panic");
                    })
                    .await
            }
        });

        tokio::time::timeout(Duration::from_secs(5), started_rx)
            .await
            .expect("active request did not start")
            .expect("active request dropped its start signal");

        let queued_one_ran = Arc::new(AtomicBool::new(false));
        let queued_one_ran_in_op = Arc::clone(&queued_one_ran);
        let queued_one = handle
            .enqueue(move |conn| {
                queued_one_ran_in_op.store(true, Ordering::SeqCst);
                conn.execute("INSERT INTO t (id, v) VALUES (2, 'queued-one')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_queued_one_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await
            .expect("first queued request must be accepted");

        let queued_two_ran = Arc::new(AtomicBool::new(false));
        let queued_two_ran_in_op = Arc::clone(&queued_two_ran);
        let queued_two = handle
            .enqueue(move |_conn| {
                queued_two_ran_in_op.store(true, Ordering::SeqCst);
                Ok::<String, StorageError>("queued-two-ran".to_string())
            })
            .await
            .expect("second queued request must be accepted");

        assert_eq!(
            handle.queue_depth(),
            2,
            "both heterogeneous requests must be buffered behind the active op"
        );
        release_tx.send(()).expect("release active op");

        let active_result = tokio::time::timeout(Duration::from_secs(5), active)
            .await
            .expect("active caller hung after panic")
            .expect("active caller task join");
        assert_writer_task_terminal_state(
            active_result,
            WriterTaskRequestState::TransactionRolledBack,
        );

        let queued_one_result = tokio::time::timeout(Duration::from_secs(5), queued_one)
            .await
            .expect("first queued caller hung after terminal failure")
            .expect("terminal drain must preserve first typed reply");
        assert_writer_task_terminal_state(queued_one_result, WriterTaskRequestState::NotStarted);

        let queued_two_result = tokio::time::timeout(Duration::from_secs(5), queued_two)
            .await
            .expect("second queued caller hung after terminal failure")
            .expect("terminal drain must preserve second typed reply");
        assert_writer_task_terminal_state(queued_two_result, WriterTaskRequestState::NotStarted);
        assert!(!queued_one_ran.load(Ordering::SeqCst));
        assert!(!queued_two_ran.load(Ordering::SeqCst));

        let future_ran = Arc::new(AtomicBool::new(false));
        let future_ran_in_op = Arc::clone(&future_ran);
        let future_result = handle
            .send(move |_conn| {
                future_ran_in_op.store(true, Ordering::SeqCst);
                Ok::<(), StorageError>(())
            })
            .await;
        assert_writer_task_terminal_state(future_result, WriterTaskRequestState::NotStarted);
        assert!(!future_ran.load(Ordering::SeqCst));

        let cached_after_failure = pool
            .writer_task_handle()
            .expect("cached writer task lookup")
            .expect("pool retains its terminal handle");
        assert_eq!(
            pool.writer_task_spawn_count(),
            1,
            "a terminal writer task must not be restarted behind callers' backs"
        );
        let cached_result = cached_after_failure
            .send(|_conn| Ok::<(), StorageError>(()))
            .await;
        assert_writer_task_terminal_state(cached_result, WriterTaskRequestState::NotStarted);

        let reader = pool.reader().expect("reader");
        let count: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t", [], |row| row.get(0))
            .unwrap();
        assert_eq!(
            count, 0,
            "the active transaction must be rolled back and queued ops must never run"
        );
    }

    #[tokio::test]
    async fn top_level_panic_reports_unknown_and_fails_queue_without_running_it() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_task_top_level_panic.db");
        let pool = file_pool(&path);
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
                .unwrap();
        }
        let handle = spawn(&pool, 8).expect("writer task spawn");

        let (started_tx, started_rx) = oneshot::channel::<()>();
        let (release_tx, release_rx) = std_mpsc::channel::<()>();
        let active = tokio::spawn({
            let handle = handle.clone();
            async move {
                handle
                    .send_top_level(move |conn| -> Result<usize, StorageError> {
                        conn.execute("INSERT INTO t (id, v) VALUES (10, 'autocommitted')", [])
                            .map_err(|e| StorageError::Pool {
                                operation: "test_top_level_insert".into(),
                                message: e.to_string(),
                            })?;
                        let _ = started_tx.send(());
                        release_rx.recv().expect("test must release top-level op");
                        panic!("intentional top-level writer request panic");
                    })
                    .await
            }
        });

        tokio::time::timeout(Duration::from_secs(5), started_rx)
            .await
            .expect("top-level request did not start")
            .expect("top-level request dropped its start signal");

        let queued_ran = Arc::new(AtomicBool::new(false));
        let queued_ran_in_op = Arc::clone(&queued_ran);
        let queued = handle
            .enqueue(move |conn| {
                queued_ran_in_op.store(true, Ordering::SeqCst);
                conn.execute("INSERT INTO t (id, v) VALUES (11, 'queued')", [])
                    .map_err(|e| StorageError::Pool {
                        operation: "test_top_level_queued_insert".into(),
                        message: e.to_string(),
                    })
            })
            .await
            .expect("queued request must be accepted");
        assert_eq!(handle.queue_depth(), 1);
        release_tx.send(()).expect("release top-level op");

        let active_result = tokio::time::timeout(Duration::from_secs(5), active)
            .await
            .expect("top-level caller hung after panic")
            .expect("top-level caller task join");
        assert_writer_task_terminal_state(
            active_result,
            WriterTaskRequestState::SideEffectsUnknown,
        );

        let queued_result = tokio::time::timeout(Duration::from_secs(5), queued)
            .await
            .expect("queued caller hung after top-level panic")
            .expect("terminal drain must preserve queued typed reply");
        assert_writer_task_terminal_state(queued_result, WriterTaskRequestState::NotStarted);
        assert!(!queued_ran.load(Ordering::SeqCst));

        let reader = pool.reader().expect("reader");
        let active_count: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t WHERE id = 10", [], |row| row.get(0))
            .unwrap();
        let queued_count: i64 = reader
            .conn()
            .query_row("SELECT COUNT(*) FROM t WHERE id = 11", [], |row| row.get(0))
            .unwrap();
        assert_eq!(
            active_count, 1,
            "the completed top-level statement autocommits before the panic"
        );
        assert_eq!(queued_count, 0, "the queued request must never run");
    }

    #[tokio::test]
    async fn closed_receiver_rejects_all_send_surfaces_as_not_started() {
        // Simulates the writer task having terminated: its `rx` is gone, so
        // every send surface must fail deterministically without running the
        // supplied operation.
        let (tx, rx) = mpsc::channel::<Box<dyn AnyWriteRequest + Send>>(4);
        drop(rx);

        let handle = WriterTaskHandle {
            tx,
            backend_key: None,
            db: "test".to_string(),
            slow_write_threshold: None,
            enqueue_timeout: Duration::from_secs(5),
        };
        let send_result = handle.send(|_conn| Ok::<(), StorageError>(())).await;
        assert_writer_task_terminal_state(send_result, WriterTaskRequestState::NotStarted);

        let timed_result = handle
            .send_with_timeout(|_conn| Ok::<(), StorageError>(()), Duration::from_secs(1))
            .await;
        assert_writer_task_terminal_state(timed_result, WriterTaskRequestState::NotStarted);

        let top_level_result = handle
            .send_top_level(|_conn| Ok::<(), StorageError>(()))
            .await;
        assert_writer_task_terminal_state(top_level_result, WriterTaskRequestState::NotStarted);
    }

    #[tokio::test]
    async fn accepted_request_lost_reply_is_side_effects_unknown() {
        // A request can be accepted before an unexpected receiver/task loss.
        // The handle cannot prove whether its closure ran, so the oneshot
        // fallback must conservatively report SideEffectsUnknown.
        let (tx, mut rx) = mpsc::channel::<Box<dyn AnyWriteRequest + Send>>(1);
        let handle = WriterTaskHandle {
            tx,
            backend_key: None,
            db: "test".to_string(),
            slow_write_threshold: None,
            enqueue_timeout: Duration::from_secs(5),
        };
        let request_ran = Arc::new(AtomicBool::new(false));
        let request_ran_in_op = Arc::clone(&request_ran);

        let dropper = tokio::spawn(async move {
            let request = rx.recv().await.expect("request must be accepted");
            drop(request);
        });
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            handle.send(move |_conn| {
                request_ran_in_op.store(true, Ordering::SeqCst);
                Ok::<(), StorageError>(())
            }),
        )
        .await
        .expect("caller hung after accepted request was dropped");
        dropper.await.expect("dropper task join");

        assert_writer_task_terminal_state(result, WriterTaskRequestState::SideEffectsUnknown);
        assert!(!request_ran.load(Ordering::SeqCst));
    }

    /// #1849: writer telemetry uses the same canonical OS-path identity as
    /// the pool. A lossy display string would merge these distinct backends.
    #[cfg(unix)]
    #[test]
    fn writer_stage_backend_key_preserves_non_utf8_path_bytes() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let path_a =
            std::path::PathBuf::from(OsString::from_vec(b"/tmp/khive-writer-\x80.db".to_vec()));
        let path_b =
            std::path::PathBuf::from(OsString::from_vec(b"/tmp/khive-writer-\x81.db".to_vec()));
        assert_eq!(
            path_a.display().to_string(),
            path_b.display().to_string(),
            "fixture must reproduce the lossy display-label collision"
        );
        assert_ne!(
            writer_db_key_from_path(Some(&path_a)),
            writer_db_key_from_path(Some(&path_b)),
            "backend keys must retain the canonical path's exact OS bytes"
        );
    }

    /// #1849: a deliberately slow transaction body with no queue backlog or
    /// lock contention must be attributed to `body`, not flattened into one
    /// opaque send-to-reply duration.
    #[tokio::test]
    async fn writer_stage_sample_attributes_a_slow_body() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writer_stage_sample.db");
        let pool = file_pool(&path);
        {
            let writer = pool.try_writer().unwrap();
            writer
                .conn()
                .execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
                .unwrap();
        }
        let handle = spawn(&pool, 8).unwrap();

        // The delay must dwarf a COMMIT on a slow disk (an fsync of a few
        // hundred milliseconds has been observed on shared runners), or the
        // commit-stage comparison below reads the disk instead of the body.
        handle
            .send(|conn| {
                std::thread::sleep(Duration::from_millis(400));
                conn.execute("INSERT INTO t VALUES (1)", [])
                    .map_err(|error| StorageError::Pool {
                        operation: "writer_stage_sample".into(),
                        message: error.to_string(),
                    })
            })
            .await
            .unwrap();

        let sample = last_writer_stage_observation(&pool).expect("writer stage sample");
        assert!(
            sample.body_micros >= 350_000,
            "the synthetic delay must land in the body stage: {sample:?}"
        );
        assert!(
            sample.body_micros > sample.queue_wait_micros,
            "fast queueing must not receive the body's delay: {sample:?}"
        );
        assert!(
            sample.body_micros > sample.transaction_acquire_micros,
            "an uncontended BEGIN must not receive the body's delay: {sample:?}"
        );
        assert!(
            sample.body_micros > sample.commit_micros,
            "a fast COMMIT must not receive the body's delay: {sample:?}"
        );
        assert!(sample.observed_at_unix_ms > 0);
    }

    /// #1849: bounded-channel queue wait ends when the drain loop receives
    /// the request. Saturation in Tokio's blocking pool happens after that
    /// boundary and must remain in `total - named_stages`, never be relabeled
    /// as writer-queue contention.
    #[test]
    fn writer_queue_wait_excludes_blocking_pool_scheduling_delay() {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .max_blocking_threads(1)
            .enable_all()
            .build()
            .expect("test runtime");

        runtime.block_on(async {
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("writer_dequeue_boundary.db");
            let pool = file_pool(&path);
            let handle = spawn(&pool, 8).unwrap();

            let (blocker_started_tx, blocker_started_rx) = std_mpsc::sync_channel(0);
            let (release_blocker_tx, release_blocker_rx) = std_mpsc::channel();
            let blocker = tokio::task::spawn_blocking(move || {
                blocker_started_tx.send(()).unwrap();
                release_blocker_rx.recv().unwrap();
            });
            blocker_started_rx
                .recv_timeout(Duration::from_secs(1))
                .expect("sole blocking worker must be occupied");

            let reply = handle
                .enqueue(|_conn| Ok::<(), StorageError>(()))
                .await
                .expect("request must enter the bounded writer channel");
            let dequeue_deadline = Instant::now() + Duration::from_secs(1);
            while handle.queue_depth() != 0 {
                assert!(
                    Instant::now() < dequeue_deadline,
                    "writer drain never dequeued the accepted request"
                );
                tokio::task::yield_now().await;
            }

            let scheduling_delay = Duration::from_millis(150);
            tokio::time::sleep(scheduling_delay).await;
            release_blocker_tx.send(()).unwrap();
            blocker.await.unwrap();
            reply.await.unwrap().unwrap();

            let sample = last_writer_stage_observation(&pool).expect("writer stage sample");
            assert!(
                sample.total_micros.saturating_sub(sample.queue_wait_micros) >= 100_000,
                "the post-dequeue blocking-pool delay must not inflate queue_wait: {sample:?}"
            );
        });
    }

    // `#[serial(tx_registry)]`: the active request holds a registered
    // `writer_task_tx` before its terminal failure, sharing the process-wide
    // registry key with the other writer-task transaction tests.
    #[tokio::test]
    #[serial(tx_registry)]
    async fn writer_task_failure_counters_are_acquisition_site_exact() {
        // Case 1: a request that reaches the seam, panics, and rolls back
        // cleanly must move `writer_task_request_failures` by exactly one —
        // never `writer_task_side_effects_unknown` — and the requests that
        // never dequeued into the seam (failed only because the queue closed
        // behind them) must move neither counter.
        {
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("writer_task_failure_counters_rollback.db");
            let pool = file_pool(&path);
            let handle = spawn(&pool, 8).expect("writer task should spawn");

            let before = pool.writer_acquisition_snapshot();
            assert_eq!(before.writer_task_request_failures, 0);
            assert_eq!(before.writer_task_side_effects_unknown, 0);

            let (started_tx, started_rx) = oneshot::channel::<()>();
            let (release_tx, release_rx) = std_mpsc::channel::<()>();
            let active = tokio::spawn({
                let handle = handle.clone();
                async move {
                    handle
                        .send(move |_conn| -> Result<(), StorageError> {
                            let _ = started_tx.send(());
                            release_rx.recv().expect("test must release active op");
                            panic!("intentional rollback-clean panic for counter test");
                        })
                        .await
                }
            });
            tokio::time::timeout(Duration::from_secs(5), started_rx)
                .await
                .expect("active request did not start")
                .expect("active request dropped its start signal");

            let queued = handle
                .enqueue(|_conn| Ok::<(), StorageError>(()))
                .await
                .expect("second request must queue behind the active one");

            release_tx.send(()).expect("release active op");
            let active_result = tokio::time::timeout(Duration::from_secs(5), active)
                .await
                .expect("active caller hung after panic")
                .expect("active caller task join");
            assert_writer_task_terminal_state(
                active_result,
                WriterTaskRequestState::TransactionRolledBack,
            );

            let queued_result = queued.await.expect("terminal drain must reply");
            assert_writer_task_terminal_state(queued_result, WriterTaskRequestState::NotStarted);

            let after = pool.writer_acquisition_snapshot();
            assert_eq!(
                after.writer_task_request_failures, 1,
                "only the request that actually reached the seam counts, not the ones \
                 failed by the queue-close drain"
            );
            assert_eq!(
                after.writer_task_side_effects_unknown, 0,
                "a clean rollback must not be counted as an unknown-side-effects outcome"
            );
        }

        // Case 2: a request whose rollback is itself refused (denied by an
        // installed authorizer) terminates `SideEffectsUnknown` and must move
        // both counters by exactly one.
        {
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("writer_task_failure_counters_unknown.db");
            let pool = file_pool(&path);
            let handle = spawn(&pool, 8).expect("writer task should spawn");

            let before = pool.writer_acquisition_snapshot();

            let active_result = handle
                .send(|conn| -> Result<(), StorageError> {
                    conn.authorizer(Some(deny_rollback))
                        .map_err(|e| StorageError::Pool {
                            operation: "test_install_authorizer".into(),
                            message: e.to_string(),
                        })?;
                    Err(StorageError::Internal(
                        "intentional operation failure before denied rollback".into(),
                    ))
                })
                .await;
            assert_writer_task_terminal_state(
                active_result,
                WriterTaskRequestState::SideEffectsUnknown,
            );

            // The reply above races the counter increment: `send` observes
            // its reply before `run_writer_task` finishes its own await and
            // updates the pool counters. A trailing request against the same
            // (now-terminal) handle can only resolve once that update and the
            // subsequent queue-close drain have both happened, so awaiting it
            // orders the snapshot below strictly after the increment.
            let sentinel_result = handle.send(|_conn| Ok::<(), StorageError>(())).await;
            assert_writer_task_terminal_state(sentinel_result, WriterTaskRequestState::NotStarted);

            let after = pool.writer_acquisition_snapshot();
            assert_eq!(
                after.writer_task_request_failures - before.writer_task_request_failures,
                1
            );
            assert_eq!(
                after.writer_task_side_effects_unknown - before.writer_task_side_effects_unknown,
                1
            );
        }
    }
}