mssql-tds 0.1.0

Rust implementation of the TDS (Tabular Data Stream) protocol for SQL Server
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
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::connection::bulk_copy::{BulkCopyOptions, BulkLoadRow, ResolvedColumnMapping};
use crate::connection::bulk_copy_state::ATTENTION_TIMEOUT_SECONDS;
use crate::connection::client_context::{ClientContext, ExecutionColumnEncryptionSetting};
use crate::connection::session_recovery::RecoveryContext;
use crate::connection::transport::any_transport::AnyTransport;
use crate::datatypes::bulk_copy_metadata::BulkCopyColumnMetadata;
use crate::datatypes::encoder::GenericEncoder;
use crate::datatypes::row_writer::{DefaultRowWriter, DiscardRowWriter, RowWriter};
use crate::datatypes::sql_string::SqlString;
use crate::datatypes::sqldatatypes::TdsDataType;
use crate::datatypes::sqltypes::SqlType;
use crate::datatypes::tds_value_serializer::{PLP_NULL, PLP_TERMINATOR, PLP_UNKNOWN_LEN};
use crate::error::Error::UsageError;
use crate::error::{SqlErrorInfo, SqlInfoMessage};
use crate::io::packet_writer::{PacketWriter, SuspendedMessage, TdsPacketWriter};
use crate::message::bulk_load::{StreamingBulkLoadWriter, build_insert_bulk_command};
use crate::message::messages::{PacketType, ResetConnectionMode};
use crate::message::parameters::rpc_parameters::{
    RpcParameter, StatusFlags, build_parameter_list_string,
};
use crate::message::rpc::{RpcProcs, RpcType, SqlRpc};
use crate::message::transaction_management::{
    CreateTxnParams, TransactionIsolationLevel, TransactionManagementRequest,
    TransactionManagementType,
};
use crate::query::result::ReturnValue;
use crate::token::tokens::{SessionStateToken, SqlCollation};
use crate::{
    connection::execution_context::{ALREADY_EXECUTING_ERROR, ExecutionContext},
    datatypes::column_values::ColumnValues,
    handler::handler_factory::NegotiatedSettings,
    io::token_stream::{
        ColumnPolicy, ParserContext, PlpPauseState, RowHeader, RowPauseState, RowReadResult,
    },
    message::{batch::SqlBatch, messages::Request},
    token::tokens::{
        ColMetadataToken, CurrentCommand, DoneStatus, DoneToken, EnvChangeTokenSubType, Tokens,
    },
};
use std::collections::HashMap;
use std::future::Future;
use std::num::NonZeroU32;
use tracing::{debug, error, info, instrument, warn};

use crate::{
    core::{CancelHandle, NegotiatedEncryptionSetting, TdsResult},
    query::metadata::ColumnMetadata,
};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Prefix for the synthetic parameter names given to positional stored-procedure
/// parameters when building the `sp_describe_parameter_encryption` request.
/// Positional arguments have no caller-supplied name, so they are declared as
/// `@ce_pos_0`, `@ce_pos_1`, ... in the describe `EXEC`. These names exist only
/// in the describe request; the real RPC still sends the parameters unnamed.
const SYNTHETIC_POSITIONAL_PARAM_PREFIX: &str = "ce_pos_";

/// Server error severity/class at or above which the connection is fatally
/// broken and must not be reused. Mirrors msodbcsql's `MINFATALERR`: a token
/// with `severity >= 20` marks the transport dead so a pool checkout discards
/// it, even if the socket is still readable.
const FATAL_ERROR_SEVERITY: u8 = 20;

/// Budget for withdrawing a request, independent of the request's own timeout.
///
/// `remaining_request_timeout` is `None` whenever `SQL_ATTR_QUERY_TIMEOUT` is 0,
/// and inheriting that would block the caller forever on a server that never
/// acknowledges the withdrawal. Matches msodbcsql's `DEFAULT_CANCEL_TIMEOUT`.
const CANCEL_TIMEOUT_SECS: u32 = 120;

/// Derived rather than converted, so the budget cannot degrade to unbounded.
const CANCEL_TIMEOUT: Duration = Duration::from_secs(CANCEL_TIMEOUT_SECS as u64);

/// Budget for the ignore packet itself, strictly below [`CANCEL_TIMEOUT`].
///
/// `PacketWriter` checks this only after a write returns, so it can fire only
/// while the stream is still intact — which yields the graceful arm, closing the
/// transport normally. The outer deadline instead drops the write future and
/// forces retirement without a shutdown, so a merely slow peer should reach this
/// one first. Only the ordering matters; the exact value does not.
const CANCEL_WRITE_TIMEOUT_SECS: u32 = CANCEL_TIMEOUT_SECS / 2;

#[derive(Debug)]
enum Withdrawal {
    /// Ignore packet sent and the server's DONE consumed.
    Done,
    /// Nothing attempted: no stream left to resynchronize, so not an error.
    ConnectionAlreadyDead,
    /// Neither complete nor retracted; the transport must go.
    Failed(crate::error::Error),
    /// The ignore write was dropped mid-flight, so the transport must go
    /// *without* another write on the stream.
    WriteAbandoned(crate::error::Error),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::connection) enum CommandTimeoutBudget {
    None,
    Remaining(NonZeroU32),
    Exhausted,
}

/// A command timeout resolved after connection recovery, ready for request I/O.
///
/// Holds one `Option<NonZeroU32>` (niche-optimized to a bare `u32`) so the
/// seconds and the deadline it derives can never disagree; `None` is no
/// deadline (infinite).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::connection) struct ResolvedCommandTimeout {
    seconds: Option<NonZeroU32>,
}

impl ResolvedCommandTimeout {
    /// The timeout in whole seconds, or `None` for no deadline.
    pub(in crate::connection) fn seconds(self) -> Option<u32> {
        self.seconds.map(NonZeroU32::get)
    }

    /// The timeout as a [`Duration`] deadline, or `None` for no deadline.
    pub(in crate::connection) fn duration(self) -> Option<Duration> {
        self.seconds
            .map(|seconds| Duration::from_secs(u64::from(seconds.get())))
    }
}

impl CommandTimeoutBudget {
    /// Resolves the post-recovery budget into the timeout used by request I/O.
    ///
    /// `None`/`Remaining` become no-deadline / the remaining positive seconds;
    /// `Exhausted` is rejected here so a spent budget can never enter the
    /// `0 == infinite` path.
    ///
    /// # Errors
    /// Returns [`TimeoutError`](crate::error::Error::TimeoutError) when recovery
    /// consumed the whole command-timeout budget.
    pub(in crate::connection) fn into_timeout(self) -> TdsResult<ResolvedCommandTimeout> {
        match self {
            Self::None => Ok(ResolvedCommandTimeout { seconds: None }),
            Self::Remaining(seconds) => Ok(ResolvedCommandTimeout {
                seconds: Some(seconds),
            }),
            Self::Exhausted => Err(crate::error::Error::TimeoutError(
                crate::error::TimeoutErrorType::String("command timeout exhausted".to_string()),
            )),
        }
    }
}

/// State of the `ReturnStatus` token observed while draining the most recent
/// cursor RPC response. Distinguishes "no token was sent" from an actual raw
/// status value, so neither case is silently collapsed at interpretation time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::connection) enum ReturnStatus {
    /// No `ReturnStatus` token was sent for the most recent RPC.
    NotReceived,
    /// The server sent a `ReturnStatus` token carrying this raw value.
    Received(i32),
}

/// Memoized cell decryptor paired with the column metadata it was built for, so
/// it can be rebuilt when the result set changes.
type MemoizedCellDecryptor = (
    Arc<ColMetadataToken>,
    Option<Arc<dyn crate::security::cell_decryptor::CellDecryptor>>,
);

#[derive(Debug)]
enum ActiveRowReadState {
    /// No row is positioned: either nothing has been fetched yet or the result
    /// set is exhausted. `read_row_column` reports `RowEnded` here.
    Idle,
    /// A row is positioned and partially read; `next_column_index` columns have
    /// been consumed and more remain on the wire.
    RowPaused(Box<RowPauseState>),
    /// A row is positioned with an active PLP column stream mid-flight.
    PlpPaused(Box<PlpPauseState>),
}

/// One chunk of an active PLP (partially-length-prefixed) column stream,
/// returned by [`TdsClient::read_active_plp_chunk`].
///
/// Carries both facts a streaming consumer needs after each read: how many
/// bytes landed in the output buffer, and whether the stream is now finished.
/// Combining them avoids a second `&self` call and keeps the "reached end"
/// answer consistent with the read that produced it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PlpChunk {
    /// Number of bytes written into the caller's buffer by this read.
    pub read: usize,
    /// `true` once the PLP stream has been fully consumed; the caller should
    /// stop reading and resume the row cursor.
    pub reached_end: bool,
    /// Declared total length of the whole PLP value in wire bytes when the
    /// server sent a known-length PLP header; `None` for unknown-length
    /// (streamed) PLP whose total is not known in advance. Lets a consumer
    /// report the concrete bytes-remaining indicator instead of `SQL_NO_TOTAL`.
    pub known_total: Option<u64>,
    /// Cumulative wire bytes consumed from this PLP value across all chunks,
    /// including this read. With `known_total`, the bytes still available
    /// before this call are `known_total - (total_read - read)`.
    pub total_read: usize,
}

/// Outcome of [`TdsClient::read_row_column`], the ODBC pull-cursor column fetch.
#[derive(Debug, PartialEq)]
pub enum CursorColumn {
    /// A fully decoded, materialized column value (non-PLP).
    Value {
        /// The decoded value.
        value: ColumnValues,
        /// Base type declared by a `sql_variant` column, `None` otherwise. The
        /// decoded value cannot always recover it, since `varchar` and
        /// `nvarchar` both arrive as [`ColumnValues::String`].
        variant_base: Option<TdsDataType>,
    },
    /// `target` is a PLP column; its bytes are streamed via
    /// [`TdsClient::read_active_plp_chunk`] until
    /// [`PlpChunk::reached_end`] is `true`.
    PlpStreaming {
        /// Collation for the whole stream, fixed for its lifetime. `None` for
        /// binary PLP types, so callers do not need a separate lookup per chunk.
        collation: Option<SqlCollation>,
    },
    /// `target` was already read or skipped (forward-only violation). The
    /// cursor is left positioned on its next undecoded column.
    AlreadyConsumed,
    /// No row is positioned (cursor is idle / row already fully consumed).
    RowEnded,
}

/// Result of a non-blocking pull-cursor attempt on concrete [`TdsClient`].
///
/// This polling surface is not part of [`ResultSet`]; synchronous bindings use
/// it directly and continue with the matching async client method on `Pending`.
#[derive(Debug, PartialEq)]
pub enum CursorPoll<T> {
    /// The operation completed entirely from bytes already buffered by the
    /// transport.
    Ready(T),
    /// The existing async cursor method must continue the operation.
    ///
    /// No transport bytes or cursor state were consumed by the attempt.
    Pending,
}

impl<T> CursorPoll<T> {
    /// Returns a buffered result immediately or invokes `fallback` once when
    /// asynchronous continuation is required.
    pub fn resolve<E>(self, fallback: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
        match self {
            Self::Ready(value) => Ok(value),
            Self::Pending => fallback(),
        }
    }
}

/// Result of a concrete [`TdsClient`] attempt to decode the next row from
/// transport-buffered bytes.
///
/// `Pending` is non-destructive. `Partial` has written a prefix, so callers must
/// reuse the same writer with [`TdsClient::finish_row_into`].
#[derive(Debug, PartialEq)]
pub enum BufferedRowPoll {
    /// A complete row was written.
    Complete,
    /// A row prefix was written and the cursor holds the continuation state.
    Partial,
    /// No row bytes or cursor state were consumed.
    Pending,
    /// The current result set was already exhausted.
    Exhausted,
}

/// Where a connection stands in the RESETCONNECTION handshake (MS-TDS
/// 2.2.3.1.2). The bit is armed on the connection and consumed by the packet
/// writer, so confirming that the server honored it needs all three states
/// rather than a single "pending" flag: only [`AwaitingAck`](Self::AwaitingAck)
/// means an acknowledgement is genuinely owed and its absence is a failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResetAckState {
    /// No reset armed or outstanding.
    Idle,
    /// Armed on the writer; no request has carried the bit to the server yet.
    /// Carries the mode so a request boundary can re-arm it: `PacketWriter::new`
    /// consumes the arm before any bytes are written, so a message abandoned
    /// mid-serialization takes the arm with it.
    Armed(ResetConnectionMode),
    /// A request carried the bit; its response must contain the
    /// `ResetConnection` ENVCHANGE.
    AwaitingAck,
}

/// Result of beginning or continuing a streamed PLP parameter write.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamedParamStatus {
    /// The server still expects a streamed parameter value. Stream its chunks
    /// next via [`TdsClient::write_streamed_chunk`], then call
    /// [`TdsClient::end_streamed_param`].
    NeedData {
        /// Name of the streamed parameter now awaiting its value chunks.
        param_name: String,
    },
    /// All streamed parameters have been written, and the server response has
    /// been positioned exactly as after a normal execute call.
    Complete(StatementResult),
}

/// Result for one command in a prepared RPC batch.
#[derive(Debug, Clone)]
pub struct PreparedBatchRowResult {
    /// Caller-supplied row index, preserved across skipped application rows.
    pub row_index: usize,
    /// Aggregate update count reported for this RPC, or `None` when unavailable.
    pub rows_affected: Option<u64>,
    /// SQL Server errors associated with this RPC.
    pub errors: Vec<SqlErrorInfo>,
    /// Whether the RPC produced a row-returning result set.
    pub has_result_set: bool,
    /// Whether the RPC produced at least one informational message.
    pub has_info: bool,
}

/// Ordered results from one logical prepared RPC batch.
#[derive(Debug, Clone)]
pub struct PreparedBatchResult {
    /// One result for every RPC command serialized into the request.
    pub rows: Vec<PreparedBatchRowResult>,
    /// Whether the server returned a boundary for every serialized RPC.
    pub complete: bool,
}

impl PreparedBatchResult {
    /// Sum of reported update counts, or `None` when none were available.
    pub fn total_rows_affected(&self) -> Option<i64> {
        let mut counts = self.rows.iter().filter_map(|row| row.rows_affected);
        let first = counts.next()?;
        Some(
            counts.fold(i64::try_from(first).unwrap_or(i64::MAX), |total, count| {
                total.saturating_add(i64::try_from(count).unwrap_or(i64::MAX))
            }),
        )
    }
}

/// State machine for an in-progress incremental (streamed) PLP parameter write,
/// parked as owned state on the client between calls (mirrors the read side's
/// [`ActiveRowReadState`]). `Active` holds the suspended RPC message plus the
/// streamed parameters whose headers have not yet been emitted.
#[derive(Debug)]
enum StreamedWriteState {
    Idle,
    Active(Box<StreamedWriteContext>),
}

/// Owned context for a suspended, partially-written streamed RPC.
#[derive(Debug)]
struct StreamedWriteContext {
    /// The parked outgoing RPC message. The parameter currently open for data
    /// has had its header (status byte + `TYPE_INFO`) written; the PLP length
    /// field (the unknown-length opener, or `PLP_NULL`) and the value chunks are
    /// appended afterwards by the streaming driver.
    message: SuspendedMessage,
    /// Streamed parameters whose headers have not yet been written, in order.
    pending: std::collections::VecDeque<RpcParameter>,
    /// Collation used to write `TYPE_INFO` for subsequent streamed parameters.
    db_collation: SqlCollation,
    /// `true` once the unknown-length PLP opener (`PLP_UNKNOWN_LEN`) has been
    /// written for the currently-open parameter — i.e. at least one value chunk
    /// has been emitted. The opener is written lazily (on the first chunk) so a
    /// parameter can still resolve to NULL before any data is sent.
    value_opened: bool,
    /// `true` when the caller has signalled the currently-open parameter is NULL
    /// via [`TdsClient::write_streamed_null`]. Closing the parameter then writes
    /// `PLP_NULL` instead of an opener + terminator, and no chunks may follow.
    null_signaled: bool,
    /// Configured timeout reused for each resumed streaming operation.
    timeout_sec: Option<u32>,
}

/// Cached row-buffering eligibility paired with the exact metadata allocation it describes.
#[derive(Debug)]
struct BufferedRowSupport {
    /// Metadata allocation whose eligibility was evaluated.
    metadata: Arc<ColMetadataToken>,
    /// Whether all columns support buffered whole-row decoding.
    whole_row: bool,
    /// Number of inline columns before the first PLP, when a safe prefix exists.
    prefix_len: Option<usize>,
}

/// Active TDS connection to a SQL Server instance.
///
/// Created by [`TdsConnectionProvider::create_client()`](crate::connection_provider::tds_connection_provider::TdsConnectionProvider::create_client).
/// Provides methods for executing queries, managing transactions, and bulk copy.
#[derive(Debug)]
pub struct TdsClient {
    pub(crate) transport: AnyTransport,
    pub(crate) negotiated_settings: NegotiatedSettings,
    pub(crate) execution_context: ExecutionContext,
    pub(crate) recovery_context: Box<RecoveryContext>,
    /// Where this connection stands in the RESETCONNECTION handshake. Driven by
    /// [`prepare_reset_connection`](TdsClient::prepare_reset_connection),
    /// [`observe_response_token`](TdsClient::observe_response_token), and
    /// [`on_reset_connection_ack`](TdsClient::on_reset_connection_ack).
    reset_state: ResetAckState,

    // pub(crate) batch_result: Option<BatchResult<'static>>,
    pub(crate) current_metadata: Option<Arc<ColMetadataToken>>,
    /// Memoized cell decryptor for `current_metadata`'s CEK table, paired with
    /// the metadata it was built for so it is rebuilt when the result set
    /// changes. `None` until the first encrypted result set is seen.
    current_decryptor: Option<MemoizedCellDecryptor>,
    buffered_row_support: Option<Box<BufferedRowSupport>>,
    count_map: HashMap<CurrentCommand, u64>,
    /// Rows affected by the most recent statement; see [`last_rows_affected`](Self::last_rows_affected).
    last_rows_affected: i64,
    /// Per-statement affected-row counts captured (in order) from every counted
    /// DONE token seen since the last COLMETADATA or command start, excluding
    /// `SQLSELECT`-tagged counts (see
    /// [`last_rows_affected`](Self::last_rows_affected)). For a pure-DML batch
    /// (`UPDATE; DELETE; INSERT`) this holds one entry per statement so the ODBC
    /// layer can surface each as its own result set via
    /// [`take_dml_result_counts`](Self::take_dml_result_counts).
    dml_result_counts: Vec<i64>,

    pub(in crate::connection) return_values: Vec<ReturnValue>,
    info_messages: Vec<SqlInfoMessage>,
    /// Per-statement Always Encrypted parameter metadata, keyed by the same
    /// client-issued [`StatementId`] as `prepared_handles`. Captured by
    /// `execute_sp_prepare` / `sp_prepexec` from
    /// `sp_describe_parameter_encryption` and reused by `execute_sp_execute` to
    /// encrypt parameter values without describing again. Holds an `Arc` to the
    /// same describe result stored in `query_metadata_cache`, pinning it for the
    /// statement's lifetime even if the shared cache evicts it. Evicted when the
    /// statement is unprepared or superseded, and cleared on reconnect.
    prepared_param_encryption: HashMap<
        StatementId,
        std::sync::Arc<
            crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult,
        >,
    >,
    /// Connection-scoped cache of `sp_describe_parameter_encryption` results,
    /// keyed by (database, query text), so every parameterized execution of the
    /// same statement reuses the describe result instead of re-querying the
    /// server. Mirrors the SqlClient/JDBC query-metadata caches.
    query_metadata_cache: crate::security::query_metadata_cache::QueryMetadataCache,
    /// Number of `sp_describe_parameter_encryption` round-trips actually sent to
    /// the server (query-metadata cache misses). Exposed for observability and to
    /// let tests confirm the cache elides repeat describes.
    describe_round_trips: u64,
    /// Plaintext column encryption keys retained from the current command's
    /// `sp_describe_parameter_encryption` call, keyed by normalized parameter
    /// name (leading `@` stripped, ASCII-uppercased). An encrypted RETURNVALUE
    /// output parameter carries no CEK table and reuses the CEK that encrypted
    /// the matching input parameter, so these are consulted when decrypting
    /// output parameters. Cleared and repopulated by `encrypt_parameters` on
    /// every command.
    output_param_ceks: HashMap<String, Arc<zeroize::Zeroizing<Vec<u8>>>>,
    /// State of the most recent `ReturnStatus` token, captured while draining a
    /// cursor RPC response and interpreted as a [`CursorStatus`](crate::cursor::CursorStatus).
    pub(in crate::connection) last_return_status: ReturnStatus,
    pub(in crate::connection) current_result_set_has_been_read_till_end: bool,
    /// Whether the DONE that exhausted the current row set was `DONEINPROC`.
    /// Only that token makes MORE ambiguous between another application result
    /// and the RPC's protocol-only completion tail.
    current_result_ended_with_done_in_proc: bool,

    /// Column Encryption setting for the command currently executing. Set by
    /// each execute entry point; consulted by the parameter-encryption and
    /// result-decryption paths to honor per-command overrides.
    current_command_ce_setting: crate::connection::client_context::ExecutionColumnEncryptionSetting,

    /// The [`StatementId`] awaiting its `@handle` from an in-flight managed
    /// `sp_prepexec` (armed by [`execute_prepared`](Self::execute_prepared));
    /// `None` once captured, aborted, or on the raw protocol path (sp_* RPCs directly,
    /// where `@handle` is left in `return_values` like any other output parameter).
    pending_capture: Option<StatementId>,
    /// Always Encrypted metadata produced for the in-flight `sp_prepexec`,
    /// pinned under the statement's id when its handle is captured from the
    /// token stream.
    pending_prepared_param_encryption: Option<
        Arc<crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult>,
    >,

    /// Monotonic source of [`StatementId`]s for managed prepared statements.
    /// Never reset (including across reconnect) so an id is never reused within
    /// this client's lifetime.
    next_statement_id: u64,
    /// Live server handles of prepared statements, keyed by their client-issued
    /// [`StatementId`]. Owned by the sp_* RPCs: written by `execute_sp_prepare`
    /// and by `push_return_value` when the `sp_prepexec` `@handle` RETURNVALUE
    /// lands, removed by `execute_sp_unprepare`. Cleared on reconnect — the old
    /// session's handles are gone — so "stale" collapses to "absent from the
    /// map".
    prepared_handles: HashMap<StatementId, i32>,

    /// The remaining request timeout for operations. This is updated after each token read.
    pub(in crate::connection) remaining_request_timeout: Option<Duration>,

    /// The cancel handle for this client. Used to cancel operations.
    pub(in crate::connection) cancel_handle: Option<CancelHandle>,

    /// One-shot evidence that the latest interrupted read reached DONE_ATTN and
    /// applied its drained control tokens while the transport remained live.
    interrupted_read_settled: bool,

    /// Empty metadata vector for returning when no metadata is available
    empty_metadata: Vec<ColumnMetadata>,

    // Active PLP stream state when row decoding paused at a PLP target column.
    active_row_read_state: ActiveRowReadState,

    /// Set by [`peek_past_current_row`](Self::peek_past_current_row) when it
    /// finds another row: that row is fully positioned (its header has been
    /// read) but not yet exposed to a caller, so the *next*
    /// [`next_row_cursor`](Self::next_row_cursor) call must return it
    /// directly instead of draining it as an abandoned row and reading past
    /// it. Consumed (reset to `false`) the moment that next call runs, and
    /// invalidated by anything that discards `active_row_read_state` first
    /// (see `drain_active_row_if_needed`).
    row_already_positioned: bool,

    /// A token read by the RPC-terminator look-ahead
    /// (see [`settle_rpc_terminator`](Self::settle_rpc_terminator)) that turned
    /// out to start another result instead of ending the response. Replayed by
    /// [`next_response_token`](Self::next_response_token) before the wire is
    /// touched again. Boxed to keep the client — and every future that owns it
    /// by value — small.
    parked_token: Option<Box<Tokens>>,

    /// Test-only: when `Some`, [`check_and_reconnect`](Self::check_and_reconnect)
    /// reports this as the elapsed recovery time and skips the transport, so
    /// budget-exhaustion paths are exercised without live reconnect timing.
    #[cfg(test)]
    reconnect_elapsed_for_test: Option<Duration>,

    // Active incremental (streamed) PLP parameter-write state, if a streamed
    // RPC is mid-flight. Idle for the normal atomic send path.
    streamed_write_state: StreamedWriteState,
}

/// Runs `fut` bounded by `remaining`, converting an elapsed timeout into
/// `Error::TimeoutError`. Extracted out of `TdsClient::reconnect` so the
/// elapsed branch can be driven directly in a test (`tokio::time::pause` plus
/// a future that never resolves) instead of needing a live, slow connect
/// attempt to provoke it.
async fn attempt_within<T>(
    remaining: Duration,
    fut: impl Future<Output = TdsResult<T>>,
) -> TdsResult<T> {
    tokio::time::timeout(remaining, fut)
        .await
        .unwrap_or_else(|_elapsed| {
            Err(crate::error::Error::TimeoutError(
                crate::error::TimeoutErrorType::String(
                    "Reconnection attempt timed out".to_string(),
                ),
            ))
        })
}

impl TdsClient {
    pub(crate) fn new(
        transport: AnyTransport,
        negotiated_settings: NegotiatedSettings,
        execution_context: ExecutionContext,
        client_context: ClientContext,
        login_session_state_tokens: Vec<SessionStateToken>,
    ) -> Self {
        let mut recovery_context = RecoveryContext::new();
        recovery_context.initialize(
            client_context,
            &negotiated_settings,
            &login_session_state_tokens,
        );

        Self {
            transport,
            negotiated_settings,
            execution_context,
            recovery_context: Box::new(recovery_context),
            reset_state: ResetAckState::Idle,
            current_metadata: None,
            current_decryptor: None,
            buffered_row_support: None,
            count_map: HashMap::new(),
            last_rows_affected: -1,
            dml_result_counts: Vec::new(),
            return_values: Vec::new(),
            info_messages: Vec::new(),
            prepared_param_encryption: HashMap::new(),
            query_metadata_cache: crate::security::query_metadata_cache::QueryMetadataCache::new(),
            describe_round_trips: 0,
            output_param_ceks: HashMap::new(),
            last_return_status: ReturnStatus::NotReceived,
            current_result_set_has_been_read_till_end: false,
            current_result_ended_with_done_in_proc: false,
            current_command_ce_setting:
                crate::connection::client_context::ExecutionColumnEncryptionSetting::default(),
            pending_capture: None,
            pending_prepared_param_encryption: None,
            next_statement_id: 0,
            prepared_handles: HashMap::new(),
            remaining_request_timeout: None,
            cancel_handle: None,
            interrupted_read_settled: false,
            empty_metadata: Vec::new(),
            active_row_read_state: ActiveRowReadState::Idle,
            row_already_positioned: false,
            parked_token: None,
            #[cfg(test)]
            reconnect_elapsed_for_test: None,
            streamed_write_state: StreamedWriteState::Idle,
        }
    }

    /// Attempt to reconnect a dead connection by replaying session state.
    ///
    /// The overall reconnection is bounded by `timeout`. Each attempt (DNS
    /// resolution through login) is wrapped in whatever remains of that
    /// budget, and `connect_timeout` is capped to the same remaining budget
    /// so it can't ask for more than is left. Before each retry sleep, we
    /// verify enough time remains for the interval.
    #[instrument(skip(self), level = "info")]
    pub(crate) async fn reconnect(
        &mut self,
        timeout: Duration,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<()> {
        use crate::connection_provider::tds_connection_provider::TdsConnectionProvider;
        use crate::error::Error;

        // Gate: session must be recoverable
        if !self
            .recovery_context
            .is_recovery_possible(&self.execution_context)
        {
            return Err(Error::SessionNotRecoverable(
                "Session state does not allow recovery".to_string(),
            ));
        }

        let client_context = match self.recovery_context.client_context.as_ref() {
            Some(ctx) => ctx.clone(),
            None => {
                return Err(Error::SessionNotRecoverable(
                    "No client context available for reconnection".to_string(),
                ));
            }
        };

        // Snapshot session state for the reconnection LOGIN7
        let snapshot = self.recovery_context.session_state_table.snapshot(
            Some(&self.negotiated_settings.database),
            Some(&self.negotiated_settings.language),
            Some(self.negotiated_settings.database_collation),
        );

        // Close the dead transport (best-effort)
        let _ = self.transport.close_transport().await;

        let deadline = Instant::now() + timeout;
        let connect_retry_count = client_context.connect_retry_count;
        let connect_retry_interval =
            Duration::from_secs(client_context.connect_retry_interval as u64);
        let transport_context = client_context.transport_context.clone();

        let mut last_error: Option<Error> = None;

        for attempt in 0..=connect_retry_count {
            // Wait before retry (not before first attempt)
            if attempt > 0 {
                let remaining = deadline.saturating_duration_since(Instant::now());
                if remaining < connect_retry_interval {
                    info!(
                        attempt,
                        "Not enough time for retry interval, aborting reconnection"
                    );
                    break;
                }
                // Cancellable sleep — if the caller cancels, abort immediately
                // rather than blocking until the interval expires (matches ODBC's
                // recoveryCancelledEvent.Wait() interruptible sleep).
                CancelHandle::run_until_cancelled(cancel_handle, async {
                    tokio::time::sleep(connect_retry_interval).await;
                    Ok(())
                })
                .await?;
            }

            // Check deadline
            if Instant::now() >= deadline {
                info!("Reconnection deadline exceeded");
                break;
            }

            // Inject recovery data into the client context clone
            let mut reconnect_ctx = client_context.clone();

            // Cap the per-attempt connect timeout to the remaining reconnect budget.
            // `.max(1)`: `remaining` can be under a second this close to the deadline,
            // and `as_secs()` truncates that to 0 — which `create_base_stream_sequential`
            // has no "0 means default" fallback for, so it would time out the attempt
            // on its first poll instead of giving it a real chance. The outer
            // `attempt_within(remaining, ...)` below is the actual deadline backstop,
            // so rounding up here can't make an attempt outlive the reconnect budget.
            let remaining = deadline.saturating_duration_since(Instant::now());
            reconnect_ctx.connect_timeout = reconnect_ctx
                .connect_timeout
                .min(remaining.as_secs().max(1) as u32);

            info!(attempt, "Attempting reconnection");
            // `connect_timeout` above only bounds the TCP-connect step inside
            // `connect_with_transport_context`; DNS resolution ahead of it is
            // otherwise unbounded here. Wrap the whole attempt (DNS through
            // login) in `remaining` too, so a slow resolver can't make a
            // single reconnect attempt outlive the overall reconnect deadline.
            let connect_result = CancelHandle::run_until_cancelled(
                cancel_handle,
                attempt_within(
                    remaining,
                    TdsConnectionProvider::connect_with_transport_context(
                        &reconnect_ctx,
                        &transport_context,
                        Some(Box::new((*snapshot).clone())),
                    ),
                ),
            )
            .await;
            match connect_result {
                Ok((
                    new_transport,
                    new_settings,
                    new_exec_ctx,
                    info_messages,
                    session_state_tokens,
                )) => {
                    // Validate reconnection properties match original
                    if let Err(validation_err) =
                        self.recovery_context.validate_reconnection(&new_settings)
                    {
                        // Close the new transport — it's unusable
                        let mut transport = new_transport;
                        let _ = transport.close_transport().await;
                        info!(error = %validation_err, "Reconnection validation failed");
                        return Err(validation_err);
                    }

                    self.adopt_recovered_session(
                        new_transport,
                        new_settings,
                        new_exec_ctx,
                        info_messages,
                        &session_state_tokens,
                    )?;

                    self.recovery_context.recovery_count += 1;
                    info!(
                        recovery_count = self.recovery_context.recovery_count,
                        "Reconnection successful"
                    );
                    return Ok(());
                }
                Err(e) => {
                    info!(attempt, error = %e, "Reconnection attempt failed");
                    last_error = Some(e);
                }
            }
        }

        // All attempts exhausted
        let message = last_error
            .map(|e| e.to_string())
            .unwrap_or_else(|| "Deadline exceeded".to_string());
        Err(Error::SessionRecoveryFailed {
            attempts: connect_retry_count + 1,
            message,
        })
    }

    /// Adopts a freshly recovered session: swaps in the new transport, settings,
    /// and execution context, then drops everything bound to the dead one.
    ///
    /// Split out of [`reconnect`](Self::reconnect) so the invariants a recovered
    /// session must satisfy can be asserted without a live server.
    fn adopt_recovered_session(
        &mut self,
        transport: AnyTransport,
        settings: NegotiatedSettings,
        execution_context: ExecutionContext,
        info_messages: Vec<SqlInfoMessage>,
        session_state_tokens: &[crate::token::tokens::SessionStateToken],
    ) -> TdsResult<()> {
        self.transport = transport;
        self.negotiated_settings = settings;
        self.execution_context = execution_context;

        // Reset per-request state
        self.current_metadata = None;
        self.count_map.clear();
        self.return_values.clear();
        self.info_messages.clear();
        self.info_messages.extend(info_messages);
        // Prepared-statement handles belong to the dead session and do not
        // survive a reconnect, so drop them and their cached Always Encrypted
        // metadata.
        self.clear_session_bound_caches();
        self.current_result_set_has_been_read_till_end = false;
        self.current_result_ended_with_done_in_proc = false;
        self.active_row_read_state = ActiveRowReadState::Idle;
        self.row_already_positioned = false;
        self.parked_token = None;
        self.remaining_request_timeout = None;
        self.cancel_handle = None;

        // Mirror msodbcsql's recovery-login handling (ReadUpdatedSessionState,
        // seq 0): the FEATUREEXTACK payload REPLACES the current (delta) table
        // (reset-then-reload), then any reconnect SESSIONSTATE tokens apply on
        // top. The initial baseline is untouched; both blocks serialize on the
        // next reconnect. Read from `negotiated_settings` *after* the swap above
        // so it is the recovered session's acknowledgement, not the dead one's.
        if let Some(ack) = self
            .negotiated_settings
            .session_recovery_initial_state()
            .map(|s| s.to_vec())
        {
            self.recovery_context
                .session_state_table
                .apply_feature_ack_to_delta(&ack);
        }
        for token in session_state_tokens {
            self.recovery_context.process_session_state(token)?;
        }

        // A pending reset is satisfied — more completely than RESETCONNECTION
        // would — by the fresh login: the new session is already at its login
        // defaults, and the armed header bit died with the old transport, so no
        // acknowledgement is coming. Leaving the state set would make the next
        // response report the reset as unacknowledged and discard a healthy,
        // brand-new connection.
        self.reset_state = ResetAckState::Idle;
        Ok(())
    }

    /// Clears the caches bound to a specific server session: managed
    /// prepared-statement handles, their cached Always Encrypted describe
    /// metadata, and any in-flight `sp_prepexec` capture state. Shared by the
    /// reconnect path (the old session's handles are gone) and the
    /// connection-reset path (`sp_reset_connection` drops server-side prepared
    /// handles), so a later `execute_prepared` re-prepares against the live
    /// session instead of aliasing a stale or unrelated handle.
    fn clear_session_bound_caches(&mut self) {
        self.prepared_handles.clear();
        self.prepared_param_encryption.clear();
        self.pending_capture = None;
        self.pending_prepared_param_encryption = None;
    }

    /// Confirms a reset and reconciles client state with the reset server session.
    ///
    /// `prepare_reset_connection` performs the same invalidation at arm time so
    /// the carrying request cannot use stale state. Repeating it here is
    /// intentional: this is the protocol-level transition shared by every token
    /// processing path, including resets not coordinated by the ODBC checkout
    /// flow.
    fn on_reset_connection_ack(&mut self) {
        self.reset_state = ResetAckState::Idle;
        self.recovery_context.session_state_table.reset();
        self.clear_session_bound_caches();
        self.negotiated_settings.restore_login_defaults();
    }

    /// Advances reset-acknowledgement tracking for one token just read from a
    /// response, and fails the connection when the acknowledgement is provably
    /// missing.
    ///
    /// The packet writer — not this client — consumes the armed mode, so the
    /// only way to learn that the bit truly reached the wire is to ask the
    /// writer. That is done solely while this client still believes a reset is
    /// armed, so a dispatch record left behind by a response that was never
    /// read cannot be charged to an unrelated later request.
    ///
    /// SQL Server resets the session *before* it parses the carrying request,
    /// so the `ResetConnection` ENVCHANGE precedes everything that request
    /// produces. The first token that is evidence the request actually ran is
    /// therefore the last moment the acknowledgement could still have arrived,
    /// and its absence means the session was never reset. ERROR is exempt so a
    /// server diagnostic reaches the caller instead of being masked by this
    /// one; a reset still unacknowledged after it is caught on the next token.
    fn observe_response_token(&mut self, token: &Tokens) -> TdsResult<()> {
        if matches!(self.reset_state, ResetAckState::Armed(_))
            && self.transport.as_writer().take_reset_dispatched()
        {
            self.reset_state = ResetAckState::AwaitingAck;
        }

        if self.reset_state != ResetAckState::AwaitingAck || !Self::proves_request_ran(token) {
            return Ok(());
        }

        warn!(
            token = Self::token_variant_name(token),
            "Request carrying the RESETCONNECTION bit produced output without a ResetConnection \
             ENVCHANGE; marking connection dead"
        );
        // Clearing first keeps the failure to a single report: the caller's
        // error drain reads more tokens on the same dead connection.
        self.reset_state = ResetAckState::Idle;
        self.transport.mark_known_dead();
        Err(crate::error::Error::ConnectionResetNotAcknowledged)
    }

    /// The token's variant name, for diagnostics. Deliberately *not* `?token`:
    /// the tokens that reach the failure log are typically ROW or RETURNVALUE,
    /// whose Debug output is customer row and output-parameter data. The kind is
    /// the whole diagnostic value here; the payload is not ours to log.
    ///
    /// Kept as an explicit match rather than `?token.token_type()` because that
    /// collapses `Done` / `DoneInProc` / `DoneProc` into a single
    /// `TokenType::Done`, and which of the three ended the carrying request is
    /// exactly the detail worth having when diagnosing an unacknowledged reset.
    /// The match is exhaustive, so a new variant is a build break, not a silent
    /// gap.
    fn token_variant_name(token: &Tokens) -> &'static str {
        match token {
            Tokens::Done(_) => "Done",
            Tokens::DoneInProc(_) => "DoneInProc",
            Tokens::DoneProc(_) => "DoneProc",
            Tokens::EnvChange(_) => "EnvChange",
            Tokens::Error(_) => "Error",
            Tokens::Info(_) => "Info",
            Tokens::LoginAck(_) => "LoginAck",
            Tokens::FeatureExtAck(_) => "FeatureExtAck",
            Tokens::FedAuthInfo(_) => "FedAuthInfo",
            Tokens::SessionState(_) => "SessionState",
            Tokens::Sspi(_) => "Sspi",
            Tokens::Row(_) => "Row",
            Tokens::ColMetadata(_) => "ColMetadata",
            Tokens::Order(_) => "Order",
            Tokens::ReturnStatus(_) => "ReturnStatus",
            Tokens::ReturnValue(_) => "ReturnValue",
            Tokens::TabName => "TabName",
            Tokens::ColInfo => "ColInfo",
        }
    }

    /// Whether a token proves the server started executing the request, and so
    /// is past the point where a `ResetConnection` ENVCHANGE could still
    /// arrive. ENVCHANGE, INFO, and SESSIONSTATE can legitimately precede or
    /// accompany the acknowledgement; ERROR is treated as inconclusive so the
    /// server's own diagnostic wins. DONE_ATTN acknowledges the cancellation,
    /// not execution of the request that carried RESETCONNECTION.
    fn proves_request_ran(token: &Tokens) -> bool {
        match token {
            Tokens::EnvChange(_) | Tokens::Info(_) | Tokens::SessionState(_) | Tokens::Error(_) => {
                false
            }
            Tokens::Done(done) | Tokens::DoneInProc(done) | Tokens::DoneProc(done)
                if done.status.contains(DoneStatus::ATTN) =>
            {
                false
            }
            _ => true,
        }
    }

    /// Settles reset tracking left over from an earlier request whose response
    /// was abandoned before any verdict could be reached.
    ///
    /// Cancellation and timeout are the reachable cases. Their ATTENTION drain
    /// replays a retained `ResetConnection` ENVCHANGE when one arrived. If the
    /// drain reaches DONE_ATTN without any token proving the carrying request
    /// ran, acknowledgement tracking remains outstanding for this boundary to
    /// settle.
    ///
    /// This runs at the request boundary, before the current request has sent
    /// anything, so a dispatch record or outstanding acknowledgement seen here
    /// necessarily belongs to an earlier request. Carrying that suspicion
    /// forward would mark a healthy connection dead on the first token of a
    /// request that never had anything to do with the reset — the failure mode
    /// this verification exists to avoid causing.
    ///
    /// Called from both [`begin_command`](Self::begin_command) and
    /// [`check_and_reconnect`](Self::check_and_reconnect) because neither alone
    /// is universal: the cursor RPCs in `cursor_ops` never call `begin_command`,
    /// and the transaction ops deliberately skip recovery. Together they cover
    /// every request path. It is idempotent — once settled, the state is `Idle`
    /// and the dispatch record consumed — so reaching it twice is harmless.
    ///
    /// Settling as reset rather than as a failure is what the protocol
    /// supports: the server resets the session *before* it processes the
    /// carrying request, the bit demonstrably reached the wire, and
    /// `prepare_reset_connection` already reconciled every client-side cache at
    /// arm time. No pool guarantee is weakened either — an abandoned carrier
    /// fails its own request, so the checkout that issued it reports failure and
    /// discards the connection.
    ///
    /// This is also where a *lost* arm is recovered. `PacketWriter::new`
    /// consumes the armed mode before any bytes are written, so a message
    /// abandoned during serialization (e.g. a parameter-encoding or Always
    /// Encrypted failure, which propagates without condemning the transport)
    /// takes the arm with it while leaving no dispatch record. Left alone the
    /// connection would sit in `Armed` forever: no request would carry the bit,
    /// so nothing could ever reach `AwaitingAck`, and the session would never be
    /// reset with nothing to notice. Re-arming the carried mode restores the
    /// invariant that `Armed` means "the next eligible request carries it".
    fn settle_abandoned_reset_verification(&mut self) {
        let carried = self.transport.as_writer().take_reset_dispatched();
        let abandoned = match self.reset_state {
            ResetAckState::Idle => false,
            // Still `Armed` with the bit already sent: an earlier request
            // carried it and its response was abandoned before the first token.
            ResetAckState::Armed(mode) => {
                if !carried {
                    // The arm may have been consumed by a message that never
                    // reached the wire. Re-arming is safe either way: if the
                    // writer still holds it, this overwrites it with the same
                    // mode; if it was lost, this puts it back.
                    self.transport.as_writer().set_reset_mode(mode);
                    return;
                }
                true
            }
            // The response ended without ever reaching a verdict token.
            ResetAckState::AwaitingAck => true,
        };
        if !abandoned {
            return;
        }
        warn!(
            "A request carrying the RESETCONNECTION bit was abandoned before its acknowledgement \
             could be observed; treating the session as reset rather than charging the next request"
        );
        self.reset_state = ResetAckState::Idle;
    }

    /// True when a RESETCONNECTION bit has been armed but the server has not yet
    /// acknowledged it with a `ResetConnection` ENVCHANGE.
    ///
    /// The client verifies this itself: the response to the request that carried
    /// the bit must contain the ENVCHANGE, or the connection is marked dead and
    /// the request fails with
    /// [`Error::ConnectionResetNotAcknowledged`](crate::error::Error::ConnectionResetNotAcknowledged).
    /// This is exposed for observability and for a pool that wants to assert the
    /// reset has been settled; correctness does not depend on anyone calling it.
    pub fn reset_pending(&self) -> bool {
        self.reset_state != ResetAckState::Idle
    }

    /// Converts a server `ERROR` token into [`SqlErrorInfo`], marking the
    /// transport known-dead when the error is fatal (severity/class ≥
    /// [`FATAL_ERROR_SEVERITY`]). A fatal error breaks the session even when the
    /// socket is still readable, so flagging it here lets a later pool checkout
    /// discard the connection instead of handing back an unusable one.
    fn record_error_token(
        &mut self,
        error_token: &crate::token::tokens::ErrorToken,
    ) -> SqlErrorInfo {
        if error_token.severity >= FATAL_ERROR_SEVERITY {
            warn!(
                severity = error_token.severity,
                number = error_token.number,
                "Fatal server error token received; marking connection dead"
            );
            self.transport.mark_known_dead();
        }
        SqlErrorInfo::from(error_token)
    }

    /// Returns the current database collation.
    ///
    /// If the collation changed after login (via an ENVCHANGE token), the
    /// updated value is returned; otherwise the collation negotiated at login.
    pub fn get_collation(&self) -> SqlCollation {
        self.negotiated_settings.database_collation
    }

    /// Returns the name of the database the connection is currently using.
    ///
    /// Reflects any change made after login (e.g. a `USE` statement, surfaced
    /// via an ENVCHANGE token); otherwise the database negotiated at login.
    ///
    /// Intended for connection-pool consumers that need to match a pooled
    /// connection to a request or decide whether a reset is required.
    pub fn database(&self) -> &str {
        &self.negotiated_settings.database
    }

    /// Returns the language the connection is currently using.
    ///
    /// Reflects any change made after login (e.g. `SET LANGUAGE`, surfaced via
    /// an ENVCHANGE token); otherwise the language negotiated at login.
    ///
    /// Intended for connection-pool consumers that need to match a pooled
    /// connection to a request or decide whether a reset is required.
    pub fn language(&self) -> &str {
        &self.negotiated_settings.language
    }

    /// Returns the negotiated TDS packet size, in bytes.
    ///
    /// The packet size is fixed for the lifetime of the connection (the server
    /// rejects mid-session packet-size changes), so this always reflects the
    /// value negotiated at login.
    pub fn packet_size(&self) -> u32 {
        self.negotiated_settings.session_settings.packet_size
    }

    /// Returns whether application traffic remains encrypted after login.
    pub fn is_encrypted(&self) -> bool {
        matches!(
            self.transport.as_writer_ref().get_encryption_setting(),
            NegotiatedEncryptionSetting::Mandatory | NegotiatedEncryptionSetting::Strict
        )
    }

    /// Returns the SQL Server version reported in the `LOGINACK` token, if the
    /// server sent one during login.
    pub fn server_version(&self) -> Option<crate::core::Version> {
        self.negotiated_settings.login_ack_server_version
    }

    /// Returns the instance name the server reported for itself during login
    /// (`@@SERVERNAME`), which is not necessarily the host the client dialled.
    pub fn server_reported_name(&self) -> Option<&str> {
        self.negotiated_settings.server_reported_name.as_deref()
    }

    /// Returns `true` if the connection is known to be dead.
    ///
    /// This surfaces the connection's last-known liveness status, updated
    /// whenever the connection is explicitly closed or an I/O operation observes
    /// it broken. It is a cached read: it never touches the socket, so it is
    /// always safe to call regardless of connection state and never consumes
    /// in-flight protocol data.
    ///
    /// A `true` result means the connection is definitively dead. A `false`
    /// result means it has not been observed dead — it may still have failed
    /// silently while idle. That case is handled transparently by idle
    /// connection resiliency, which detects and recovers a dead connection on
    /// the next operation. This makes the method suitable for connection pools
    /// that want a cheap, always-safe liveness check before handing out a
    /// connection.
    pub fn is_connection_dead(&self) -> bool {
        self.transport.connection_known_dead()
    }

    /// Marks the connection known-dead so [`is_connection_dead`] reports it
    /// without touching the socket. A caller that observes the session in an
    /// unrecoverable state — e.g. a connection-pool reset that failed partway —
    /// uses this so a later liveness check discards the connection instead of
    /// handing back a session left in an unknown state.
    ///
    /// [`is_connection_dead`]: Self::is_connection_dead
    pub fn mark_connection_dead(&mut self) {
        self.transport.mark_known_dead();
    }

    pub(crate) fn get_current_metadata(&self) -> Option<&ColMetadataToken> {
        self.current_metadata.as_deref()
    }

    /// Rows affected by the most recently executed statement.
    ///
    /// Returns the row count from the last DONE token that carried the
    /// `DONE_COUNT` flag **and** was not tagged with the `SQLSELECT` command,
    /// or `-1` when no such count is available (DDL, `SET NOCOUNT ON`, a
    /// forward-only SELECT whose trailing DONE has not been read, or before any
    /// statement has executed). This maps directly to the value ODBC
    /// `SQLRowCount` reports.
    ///
    /// The `SQLSELECT` exclusion exists because SQL Server sets `DONE_COUNT` on
    /// variable assignment (`DECLARE @x int = 1`, `SET @x = 1`,
    /// `SELECT @x = col FROM t`) while tagging it `SQLSELECT`; that count is not
    /// an update count and neither msodbcsql nor .NET SqlClient reports it. See
    /// the comment in `advance_to_result_boundary`.
    pub fn last_rows_affected(&self) -> i64 {
        self.last_rows_affected
    }

    /// Drains the per-statement affected-row counts captured since the last
    /// COLMETADATA (or command start), in statement order. Used by the ODBC
    /// layer to surface each DML statement in a pure-DML batch as its own
    /// result set. `SQLSELECT`-tagged counts are excluded, as for
    /// [`last_rows_affected`](Self::last_rows_affected). Returns an empty vec
    /// when the batch produced no qualifying counted DONE (e.g. DDL,
    /// `SET NOCOUNT ON`, or only variable assignments).
    pub fn take_dml_result_counts(&mut self) -> Vec<i64> {
        std::mem::take(&mut self.dml_result_counts)
    }

    /// Updates the remaining timeout by subtracting the elapsed time.
    fn update_remaining_timeout(&mut self, start: Instant) {
        self.remaining_request_timeout = self.remaining_request_timeout.map(|t| {
            let elapsed = start.elapsed();
            if elapsed > t {
                Duration::ZERO
            } else {
                t.saturating_sub(elapsed)
            }
        });
    }

    #[inline]
    /// Starts timeout accounting only when the request has a finite budget.
    fn request_timeout_start(&self) -> Option<Instant> {
        self.remaining_request_timeout.map(|_| Instant::now())
    }

    /// Pre-execution check: detect a dead connection and attempt session recovery.
    ///
    /// Call this at the top of any operation that sends a TDS request (SQL
    /// batch, RPC, bulk load, `BEGIN TRANSACTION`). Recovery is attempted only
    /// when all of the following hold; otherwise this is a cheap no-op that
    /// returns `Duration::ZERO`:
    /// - session recovery was negotiated at login, and the server offered a
    ///   retry count (`connect_retry_count > 0`); and
    /// - the underlying socket is actually dead (a non-blocking poll).
    ///
    /// `timeout_sec` is the overall budget for recovery **and** the subsequent
    /// execution, matching ODBC's `CheckOrRecoverConnection` (which deducts
    /// recovery time from the remaining command timeout). Charge the returned
    /// duration back with [`deduct_timeout`](Self::deduct_timeout) so a
    /// 30-second command timeout still means at most 30 seconds total whether
    /// or not a reconnect occurred. When `timeout_sec` is `None` or `Some(0)`,
    /// recovery is instead bounded by the login `connect_timeout`, so it can
    /// never block indefinitely.
    ///
    /// Operations inside an active transaction (`COMMIT`, `ROLLBACK`, `SAVE`)
    /// intentionally skip recovery — `is_recovery_possible()` returns `false`
    /// while a transaction is open, matching SqlClient's
    /// `RestoreBrokenConnection` behavior.
    ///
    /// A caller managing prepared statements uses this as its single recovery
    /// point: a successful reconnect clears the client's prepared-handle map, so
    /// the next [`execute_prepared`](Self::execute_prepared) re-prepares against
    /// the new session instead of addressing a plan that died with the old one.
    ///
    /// # Parameters
    /// - `timeout_sec`: recovery budget in seconds; `None` (or `Some(0)`) falls
    ///   back to the connection's `connect_timeout`.
    /// - `cancel_handle`: optional token used to abort an in-progress reconnect.
    ///
    /// # Returns
    /// The wall-clock time spent reconnecting, or `Duration::ZERO` when no
    /// reconnect was needed.
    ///
    /// # Errors
    /// Returns [`Error::ConnectionClosed`](crate::error::Error::ConnectionClosed)
    /// when the socket is dead but the session state forbids recovery (e.g. an
    /// open transaction), and propagates any error raised by the underlying
    /// `reconnect()` attempt (including a timed-out or cancelled reconnect).
    pub(crate) async fn check_and_reconnect(
        &mut self,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<Duration> {
        // Request boundary. `begin_command` misses the cursor RPCs (they never
        // call it) and this misses the transaction ops (they deliberately skip
        // recovery), so the settle lives in both; it is idempotent, so a path
        // that reaches it twice costs nothing.
        self.settle_abandoned_reset_verification();

        #[cfg(test)]
        if let Some(elapsed) = self.reconnect_elapsed_for_test.take() {
            return Ok(elapsed);
        }

        let connect_retry_count = self
            .recovery_context
            .client_context
            .as_ref()
            .map_or(0, |ctx| ctx.connect_retry_count);

        // A cached dead verdict is authoritative. Without this gate, callers
        // with recovery disabled (including intentionally closed clients and
        // clients retired after protocol desynchronization) would fall through
        // and write another request to the unusable transport.
        let known_dead = self.transport.connection_known_dead();
        if known_dead
            && (!self.recovery_context.session_recovery_negotiated || connect_retry_count == 0)
        {
            return Err(crate::error::Error::ConnectionClosed(
                "Connection is dead and session recovery is unavailable".to_string(),
            ));
        }

        // Only attempt recovery when session recovery was negotiated and
        // the server supports retry (connect_retry_count > 0).
        if !self.recovery_context.session_recovery_negotiated {
            return Ok(Duration::ZERO);
        }
        if connect_retry_count == 0 {
            return Ok(Duration::ZERO);
        }

        // Non-blocking poll — returns immediately. Skipped once the verdict is
        // already in: a session retired by a fatal ERROR token or a failed drain
        // stays unusable however healthy its socket still looks.
        if !known_dead && !self.transport.is_connection_dead() {
            return Ok(Duration::ZERO);
        }

        // Connection is dead. Check if recovery is possible.
        if !self
            .recovery_context
            .is_recovery_possible(&self.execution_context)
        {
            return Err(crate::error::Error::ConnectionClosed(
                "Connection is dead and session state does not allow recovery".to_string(),
            ));
        }

        // Use the command timeout as the reconnection budget. If no command
        // timeout is set, fall back to connect_timeout so reconnection is
        // still bounded.
        let reconnect_timeout = match timeout_sec {
            Some(t) if t > 0 => Duration::from_secs(t as u64),
            _ => {
                let connect_timeout = self
                    .recovery_context
                    .client_context
                    .as_ref()
                    .map_or(15, |ctx| ctx.connect_timeout);
                Duration::from_secs(connect_timeout as u64)
            }
        };

        let start = Instant::now();
        self.reconnect(reconnect_timeout, cancel_handle).await?;
        Ok(start.elapsed())
    }

    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub async fn check_and_reconnect_for_test(
        &mut self,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<Duration> {
        self.check_and_reconnect(timeout_sec, cancel_handle).await
    }

    /// Charges elapsed recovery time against a command-timeout budget.
    ///
    /// # Parameters
    /// - `timeout_sec`: remaining command budget in seconds; `None` means "no
    ///   timeout".
    /// - `elapsed`: time already consumed.
    ///
    /// `None` and caller-supplied `Some(0)` both represent an infinite budget.
    /// A positive timeout becomes [`CommandTimeoutBudget::Exhausted`] when
    /// recovery consumes it, which must be rejected by `into_timeout` before a
    /// request is serialized.
    pub(in crate::connection) fn deduct_timeout(
        timeout_sec: Option<u32>,
        elapsed: Duration,
    ) -> CommandTimeoutBudget {
        let Some(timeout_sec) = timeout_sec.and_then(NonZeroU32::new) else {
            return CommandTimeoutBudget::None;
        };
        let elapsed_secs = u32::try_from(
            elapsed
                .as_secs()
                .saturating_add(u64::from(elapsed.subsec_nanos() > 0)),
        )
        .unwrap_or(u32::MAX);

        match NonZeroU32::new(timeout_sec.get().saturating_sub(elapsed_secs)) {
            Some(remaining) => CommandTimeoutBudget::Remaining(remaining),
            None => CommandTimeoutBudget::Exhausted,
        }
    }

    /// Requests that the connection be reset before the next request is
    /// processed by the server, to support connection pooling.
    ///
    /// This sets the RESETCONNECTION (or RESETCONNECTIONSKIPTRAN) status bit on
    /// the first packet of the next SQL Batch, RPC, or Transaction Manager
    /// request sent on this connection (MS-TDS section 2.2.3.1.2). The server
    /// resets the session state back to its login defaults — equivalent to
    /// `sp_reset_connection` — before processing that request. The request is
    /// one-shot: it is cleared once the next such request has been sent.
    ///
    /// # Parameters
    /// - `preserve_transaction` — when `true`, use
    ///   RESETCONNECTIONSKIPTRAN so a local or enlisted/distributed transaction
    ///   survives. The ODBC pool always passes `false`; low-level TDS consumers
    ///   should pass `true` only when a transaction must outlive the reset.
    ///
    /// # Client-side state is dropped immediately
    /// The session-bound caches (prepared handles, their Always Encrypted
    /// describe metadata, in-flight capture state), the accumulated
    /// session-recovery state, and the negotiated DATABASE / LANGUAGE /
    /// COLLATION are reset here, at arm time, rather than when the
    /// acknowledgement arrives. The server *will* reset the session before it
    /// processes the next request, so continuing to serve a borrower from those
    /// caches in the meantime is never correct: a cached prepared handle would
    /// be sent on a request whose own header bit is about to drop it
    /// server-side, which is how msodbcsql produces "Could not find prepared
    /// statement with handle N" (native 8179) across a pool reset.
    ///
    /// Dropping them eagerly is conservative — the worst case is re-preparing a
    /// statement that a deferred reset had not yet invalidated — and it removes
    /// the window without costing a round trip. msodbcsql does the same for its
    /// cached database/language/collation (`sqlcmisc.cpp:2373-2461`); it simply
    /// does not extend it to prepared handles.
    ///
    /// The acknowledgement is verified by the client itself: the response to the
    /// request that carries the bit must contain the server's `ResetConnection`
    /// ENVCHANGE. If it does not, that request fails with
    /// [`Error::ConnectionResetNotAcknowledged`](crate::error::Error::ConnectionResetNotAcknowledged)
    /// and the connection is marked dead, so a pool cannot hand out a session
    /// that was never reset. Verification therefore does not depend on the
    /// consumer issuing any particular request after arming.
    pub fn prepare_reset_connection(&mut self, preserve_transaction: bool) {
        let mode = match preserve_transaction {
            true => ResetConnectionMode::ResetSkipTran,
            false => ResetConnectionMode::Reset,
        };
        self.transport.as_writer().set_reset_mode(mode);
        self.reset_state = ResetAckState::Armed(mode);
        // A full reset discards the server-side transaction, so mirror that here.
        // Leaving a stale descriptor would make `has_active_transaction()` report
        // a transaction the carrying request is itself about to destroy, and the
        // next caller would send a TM rollback for it — which the server answers
        // with 3903 ("no corresponding BEGIN TRANSACTION"), failing the checkout.
        // RESETCONNECTIONSKIPTRAN deliberately preserves the transaction, so the
        // descriptor must survive in that mode.
        if !preserve_transaction {
            self.execution_context.set_transaction_descriptor(0);
        }
        // Mirror the reset the server will apply before the next request, so no
        // borrower is served from state the reset is about to invalidate.
        self.recovery_context.session_state_table.reset();
        self.clear_session_bound_caches();
        self.negotiated_settings.restore_login_defaults();
    }

    /// Executes a SQL batch and positions on its **first navigable result**,
    /// returning that result's [`StatementResult`].
    ///
    /// Navigation is statement-wise (lossless): a no-row statement that carries
    /// a row count or produced a message is surfaced as its own
    /// [`StatementResult::NoRows`]; a pure no-op statement (e.g. a bare
    /// `CREATE TABLE`) is collapsed. Advance through the rest of the batch with
    /// [`advance()`](Self::advance), or skip straight to row-returning result
    /// sets with [`advance_to_rows()`](Self::advance_to_rows).
    ///
    /// # Parameters
    /// - `sql_command` — raw T-SQL text to execute.
    /// - `options` — per-command [`ExecuteOptions`] (timeout, cancellation,
    ///   Always Encrypted override). Pass `()` for defaults.
    ///
    /// # Errors
    /// Returns [`UsageError`](crate::error::Error::UsageError) if a previous
    /// batch is still open.
    #[instrument(skip(self, options), level = "info")]
    pub async fn execute<'a>(
        &mut self,
        sql_command: String,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementResult> {
        self.send_query_batch(sql_command, options.into()).await?;
        let boundary = self.advance_to_result_boundary().await?;
        Ok(self.apply_result_boundary(boundary))
    }

    /// Runs the batch-execution prologue and sends a SQL batch to the wire:
    /// sets the per-command Always Encrypted setting, rejects a re-entrant call,
    /// reconnects if needed, stores the timeout / cancel handle, and serializes
    /// the batch. The caller then consumes the response via
    /// [`advance_to_result_boundary`](Self::advance_to_result_boundary).
    async fn send_query_batch(
        &mut self,
        sql_command: String,
        options: ExecuteOptions<'_>,
    ) -> TdsResult<()> {
        let ExecuteOptions {
            timeout,
            cancel,
            column_encryption,
        } = options;
        self.current_command_ce_setting = column_encryption;

        if self.command_is_busy() {
            return Err(crate::error::Error::UsageError(
                ALREADY_EXECUTING_ERROR.to_string(),
            ));
        };

        self.begin_command();
        let reconnect_elapsed = self.check_and_reconnect(timeout, cancel).await?;
        let budget = Self::deduct_timeout(timeout, reconnect_elapsed);
        let resolved = budget.into_timeout()?;
        let timeout = resolved.seconds();
        let request_timeout = resolved.duration();

        // Store timeout and cancel handle for this operation
        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel.map(|handle| handle.child_handle());

        self.transport.reset_reader();
        let batch = SqlBatch::new(sql_command, &self.execution_context);
        let mut packet_writer =
            batch.create_packet_writer(self.transport.as_writer(), timeout, cancel);
        let serialize_result = batch.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        self.finish_send(serialize_result, message).await?;
        Ok(())
    }

    /// Executes a parameterized query via `sp_executesql`, positioning on its
    /// first navigable result.
    ///
    /// The SQL text and parameter declarations are sent as positional RPC
    /// arguments. Caller-supplied `named_params` are appended as named
    /// parameters — each [`RpcParameter`] must have a `name` matching the
    /// declaration in the query (e.g. `@id`).
    ///
    /// This is the primary path for parameterized queries; prefer it over
    /// string interpolation to avoid SQL injection and benefit from plan
    /// caching on the server.
    ///
    /// # Parameters
    /// - `sql` — parameterized T-SQL statement.
    /// - `named_params` — parameter values. Build with [`RpcParameter::new`].
    /// - `options` — per-command [`ExecuteOptions`]; set
    ///   [`column_encryption`](ExecuteOptions::column_encryption) to override
    ///   Always Encrypted for this call. Pass `()` for defaults.
    #[instrument(skip(self, named_params, options), level = "info")]
    pub async fn execute_sp_executesql<'a>(
        &mut self,
        sql: String,
        mut named_params: Vec<RpcParameter>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementResult> {
        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            column_encryption,
        } = options.into();
        self.current_command_ce_setting = column_encryption;

        if self.command_is_busy() {
            return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
        };
        RpcParameter::reject_data_at_exec(named_params.iter())?;

        let declaration_params = named_params.clone();
        let mut params_list_as_string = String::new();
        build_parameter_list_string(&declaration_params, &mut params_list_as_string)?;

        // Always Encrypted: when the connection enabled column encryption and the
        // server acknowledged the feature, ask the server which parameters need
        // encryption and encrypt them in place before sending the real RPC.
        self.ensure_force_column_encryption_supported(named_params.iter())?;
        let (timeout_sec, request_timeout, database_collation) =
            self.prepare_rpc_command(timeout_sec, cancel_handle).await?;

        if self.should_encrypt_parameters() && !named_params.is_empty() {
            self.encrypt_parameters(
                &sql,
                &params_list_as_string,
                &mut named_params,
                timeout_sec,
                cancel_handle,
            )
            .await?;
            // The describe round-trip closes its own batch, which clears the
            // per-operation timeout/cancel state; restore it for the real RPC.
            self.remaining_request_timeout = request_timeout;
            self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());
        }

        let rpc = self.build_sp_executesql_rpc(
            sql,
            named_params,
            params_list_as_string,
            &database_collation,
        );

        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = rpc.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        drop(rpc);
        self.finish_send(serialize_result, message).await?;

        self.position_on_first_result().await
    }

    async fn execute_sp_execute_batch<'a, I>(
        &mut self,
        statement_id: StatementId,
        rows: I,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<PreparedBatchResult>
    where
        I: IntoIterator<Item = TdsResult<(usize, Vec<RpcParameter>)>>,
    {
        let Some(handle) = self.prepared_handles.get(&statement_id).copied() else {
            return Err(UsageError(
                "Cannot execute. Given prepared statement is not materialized on this connection"
                    .to_string(),
            ));
        };

        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            column_encryption,
        } = options.into();
        self.current_command_ce_setting = column_encryption;
        self.remaining_request_timeout = timeout_sec
            .filter(|seconds| *seconds > 0)
            .map(|seconds| Duration::from_secs(u64::from(seconds)));
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());
        self.transport.reset_reader();

        let database_collation = self.negotiated_settings.database_collation;
        let send_started = self.request_timeout_start();
        let rows = rows.into_iter();
        let mut packet_writer = PacketType::RpcRequest.create_packet_writer(
            self.transport.as_writer(),
            timeout_sec,
            cancel_handle,
        );
        let (row_count, _) = rows.size_hint();
        let mut row_indices = Vec::with_capacity(row_count);
        let mut first = true;
        let serialization_result = async {
            for row in rows {
                // A row's parameters are all converted before any of its bytes
                // reach the writer, so a build failure leaves no partial
                // command behind: skipping it keeps the batch well-formed and
                // the connection synchronised. msodbcsql reaches the same end
                // state by retracting the started command with
                // RPCBATCH_IGNORELAST (tdsrpc.cpp:258-268); it needs the byte
                // because it streams conversion straight into the RPC buffer.
                let Ok((row_index, mut positional_params)) = row else {
                    continue;
                };
                RpcParameter::reject_data_at_exec(positional_params.iter())?;
                if positional_params
                    .iter()
                    .any(RpcParameter::force_column_encryption)
                {
                    return Err(UsageError(
                        "Batched prepared execution does not support ForceColumnEncryption."
                            .to_string(),
                    ));
                }
                let handle_parameter =
                    RpcParameter::new(None, StatusFlags::NONE, SqlType::Int(Some(handle)));
                positional_params.insert(0, handle_parameter);
                let rpc = SqlRpc::new_batch_command(
                    RpcType::ProcId(RpcProcs::Execute),
                    Some(positional_params),
                    None,
                    &database_collation,
                    &self.execution_context,
                    first,
                );
                rpc.serialize_batch_command(&mut packet_writer, first)
                    .await?;
                first = false;
                row_indices.push(row_index);
            }
            if first {
                return Err(UsageError(
                    "Prepared RPC batch contains no executable rows".to_string(),
                ));
            }
            packet_writer.finalize().await
        }
        .await;
        let message = packet_writer.suspend();
        self.finish_send(serialization_result, message).await?;
        if let Some(start) = send_started {
            self.update_remaining_timeout(start);
        }

        let result = self.drain_prepared_batch(row_indices).await;
        if result.is_err() {
            self.execution_context.set_has_open_batch(false);
            self.current_result_set_has_been_read_till_end = true;
            self.current_metadata = None;
        }
        result
    }

    async fn drain_prepared_batch(
        &mut self,
        row_indices: Vec<usize>,
    ) -> TdsResult<PreparedBatchResult> {
        let expected_rows = row_indices.len();
        let parser_context = ParserContext::ColumnEncryption(
            self.negotiated_settings.is_column_encryption_supported(),
        );
        let mut results = Vec::with_capacity(row_indices.len());
        let mut row_indices = row_indices.into_iter();
        let mut current_index = row_indices.next().ok_or_else(|| {
            UsageError("Prepared RPC batch contains no executable rows".to_string())
        })?;
        let mut errors = Vec::new();
        let mut rows_affected = None;
        let mut has_result_set = false;
        let mut info_count = self.info_messages.len();

        loop {
            let token = self.next_response_token(&parser_context).await?;
            match token {
                Tokens::ColMetadata(metadata) => {
                    has_result_set = true;
                    if self
                        .drain_result_set_rows(Arc::new(metadata), &mut errors)
                        .await?
                    {
                        results.push(PreparedBatchRowResult {
                            row_index: current_index,
                            rows_affected,
                            errors,
                            has_result_set,
                            has_info: self.info_messages.len() != info_count,
                        });
                        // The DONE that ended this result set carried no MORE.
                        // If sets are still outstanding it ended the stream
                        // early, so there are unread tokens and the connection
                        // cannot be reused.
                        //
                        // This arm keys off MORE while the DONE arm below keys
                        // off RPC_IN_BATCH, on the assumption that the server
                        // moves the two together for a batched RPC. A DONE
                        // carrying RPC_IN_BATCH with MORE clear would fail here
                        // rather than continue - loudly, but on a healthy
                        // connection. No server has been observed doing it.
                        if row_indices.next().is_some() {
                            self.transport.mark_known_dead();
                            return Err(crate::error::Error::ProtocolError(
                                "Batched RPC result set ended before every set reported"
                                    .to_string(),
                            ));
                        }
                        break;
                    }
                }
                Tokens::DoneInProc(done) => {
                    if done.status.contains(DoneStatus::COUNT)
                        && done.cur_cmd != CurrentCommand::Select
                    {
                        rows_affected =
                            Some(rows_affected.unwrap_or(0u64).saturating_add(done.row_count));
                    }
                }
                Tokens::DoneProc(done) | Tokens::Done(done) => {
                    if done.status.contains(DoneStatus::COUNT)
                        && done.cur_cmd != CurrentCommand::Select
                    {
                        rows_affected =
                            Some(rows_affected.unwrap_or(0u64).saturating_add(done.row_count));
                    }
                    if done.has_error() && errors.is_empty() {
                        // Tokens for the rest of the batch are still unread, so
                        // this connection cannot be handed back to the pool.
                        self.transport.mark_known_dead();
                        return Err(crate::error::Error::ProtocolError(
                            "Server reported an error for a batched RPC without an ERROR token"
                                .to_string(),
                        ));
                    }

                    // msodbcsql treats any non-DONEINPROC DONE as the parameter
                    // set boundary (sqlctokn.cpp:2329) and uses DONE_RPCINBATCH
                    // only to say another command follows (:2413). So every DONE
                    // reaching here reports its set; the flag decides whether to
                    // expect another, never whether this one counts.
                    results.push(PreparedBatchRowResult {
                        row_index: current_index,
                        rows_affected,
                        errors,
                        has_result_set,
                        has_info: self.info_messages.len() != info_count,
                    });

                    if !done.status.contains(DoneStatus::RPC_IN_BATCH) {
                        if done.has_more() {
                            // No further RPC, yet the server says more tokens
                            // follow: the batch never reached a final DONE, so
                            // this connection cannot go back to the pool.
                            self.transport.mark_known_dead();
                            return Err(crate::error::Error::ProtocolError(
                                "Batched RPC results ended without a final DONE".to_string(),
                            ));
                        }
                        break;
                    }
                    match row_indices.next() {
                        Some(next_index) => current_index = next_index,
                        None => {
                            self.transport.mark_known_dead();
                            return Err(crate::error::Error::ProtocolError(
                                "Server returned more batched RPC results than were sent"
                                    .to_string(),
                            ));
                        }
                    }
                    errors = Vec::new();
                    rows_affected = None;
                    has_result_set = false;
                    info_count = self.info_messages.len();
                }
                Tokens::Error(error_token) => {
                    errors.push(self.record_error_token(&error_token));
                }
                other => self.apply_drain_side_effect(other, &mut errors)?,
            }
        }

        // A short batch means the stream ended at a final DONE before every
        // command reported - an accounting mismatch, not a desynchronised
        // socket, so the connection stays usable and `complete` carries it.
        let complete = results.len() == expected_rows;

        self.execution_context.set_has_open_batch(false);
        self.current_result_set_has_been_read_till_end = true;
        self.current_metadata = None;

        let result = PreparedBatchResult {
            rows: results,
            complete,
        };
        self.last_rows_affected = result.total_rows_affected().unwrap_or(-1);
        Ok(result)
    }

    /// Starts a parameterized `sp_executesql` whose MAX parameter values are
    /// supplied later, in chunks (data-at-execution).
    ///
    /// This is the additive streaming counterpart to
    /// [`TdsClient::execute_sp_executesql`]. Existing materialized-parameter
    /// callers should continue using that method; this method is for
    /// [`RpcParameter::data_at_exec`] parameters.
    ///
    /// Supported streamed types are listed by [`StreamedSqlType`]. Chunks are
    /// raw wire bytes and are written verbatim, so the caller owns the encoding:
    /// `nvarchar(max)` chunks must be UTF-16LE, and `varchar(max)`/
    /// `varbinary(max)` chunks their corresponding single-byte/binary
    /// representation. A zero-length stream is a present empty value; use
    /// [`TdsClient::write_streamed_null`] for SQL `NULL`.
    ///
    /// The method returns [`StreamedParamStatus::NeedData`] after the RPC
    /// prefix is parked. Supply zero or more chunks and call
    /// [`TdsClient::end_streamed_param`]. When all parameters are complete,
    /// the final server result is returned as
    /// [`StreamedParamStatus::Complete`].
    ///
    /// Streamed parameters must be named and must use one of the
    /// [`StreamedSqlType`] variants. Streaming is not supported when Always
    /// Encrypted is active.
    ///
    /// # Errors
    /// Returns a usage error for invalid streamed parameters or an active
    /// command, and returns transport/serialization errors from the request.
    pub async fn begin_sp_executesql<'a>(
        &mut self,
        sql: String,
        named_params: Vec<RpcParameter>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StreamedParamStatus> {
        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            column_encryption,
        } = options.into();

        if self.command_is_busy() {
            return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
        }

        self.current_command_ce_setting = column_encryption;
        self.ensure_force_column_encryption_supported(named_params.iter())?;

        let (streamed_params, materialized_params) =
            Self::split_and_validate_streamed_params(named_params)?;

        if streamed_params.is_empty() {
            let result = self
                .execute_sp_executesql(
                    sql,
                    materialized_params,
                    ExecuteOptions {
                        timeout: timeout_sec,
                        cancel: cancel_handle,
                        column_encryption,
                    },
                )
                .await?;
            return Ok(StreamedParamStatus::Complete(result));
        }

        if self.should_encrypt_parameters() {
            return Err(UsageError(
                "Streamed PLP parameter writes are not supported with Always Encrypted."
                    .to_string(),
            ));
        }

        let mut declaration_params = materialized_params.clone();
        declaration_params.extend(streamed_params.iter().cloned());
        let mut params_list_as_string = String::new();
        build_parameter_list_string(&declaration_params, &mut params_list_as_string)?;

        let (timeout_sec, _request_timeout, database_collation) =
            self.prepare_rpc_command(timeout_sec, cancel_handle).await?;
        let rpc = self.build_sp_executesql_rpc(
            sql,
            materialized_params,
            params_list_as_string,
            &database_collation,
        );

        self.start_streamed_rpc(
            rpc,
            streamed_params,
            timeout_sec,
            cancel_handle,
            database_collation,
        )
        .await
    }

    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub async fn execute_sp_execute_batch_for_test<I>(
        &mut self,
        statement_id: StatementId,
        rows: I,
    ) -> TdsResult<PreparedBatchResult>
    where
        I: IntoIterator<Item = TdsResult<(usize, Vec<RpcParameter>)>>,
    {
        self.begin_command();
        self.execute_sp_execute_batch(statement_id, rows, ExecuteOptions::default())
            .await
    }

    /// Opens the command boundary, recovers a dead connection, and resolves the
    /// per-command timeout/cancel state for an RPC the caller is about to build.
    /// Shared by the `sp_executesql`, `sp_prepexec` and `sp_execute` streamed and
    /// materialized entry points.
    async fn prepare_rpc_command(
        &mut self,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<(Option<u32>, Option<Duration>, SqlCollation)> {
        self.begin_command();
        let reconnect_elapsed = self.check_and_reconnect(timeout_sec, cancel_handle).await?;
        let budget = Self::deduct_timeout(timeout_sec, reconnect_elapsed);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        let request_timeout = resolved.duration();

        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());
        self.transport.reset_reader();

        Ok((
            timeout_sec,
            request_timeout,
            self.negotiated_settings.database_collation,
        ))
    }

    fn build_sp_executesql_rpc<'a>(
        &self,
        sql: String,
        named_params: Vec<RpcParameter>,
        params_list_as_string: String,
        database_collation: &'a SqlCollation,
    ) -> SqlRpc<'a> {
        let statement_parameter = RpcParameter::new(
            None,
            StatusFlags::NONE,
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(sql))),
        );

        let params_parameter = RpcParameter::new(
            None,
            StatusFlags::NONE,
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(params_list_as_string))),
        );

        let positional_parameters = Some(vec![statement_parameter, params_parameter]);

        SqlRpc::new(
            RpcType::ProcId(RpcProcs::ExecuteSql),
            positional_parameters,
            Some(named_params),
            database_collation,
            &self.execution_context,
        )
    }

    fn split_and_validate_streamed_params(
        named_params: Vec<RpcParameter>,
    ) -> TdsResult<(Vec<RpcParameter>, Vec<RpcParameter>)> {
        let (streamed_params, materialized_params): (Vec<_>, Vec<_>) = named_params
            .into_iter()
            .partition(RpcParameter::is_data_at_exec);

        for param in &streamed_params {
            if param.name.is_none() {
                return Err(UsageError("Streamed parameters must be named.".to_string()));
            }
        }

        Ok((streamed_params, materialized_params))
    }

    /// Sends the RPC prefix plus the first streamed parameter's header, then
    /// parks the half-written message so the caller can supply chunks.
    async fn start_streamed_rpc(
        &mut self,
        rpc: SqlRpc<'_>,
        streamed_params: Vec<RpcParameter>,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
        database_collation: SqlCollation,
    ) -> TdsResult<StreamedParamStatus> {
        let mut pending: std::collections::VecDeque<RpcParameter> =
            streamed_params.into_iter().collect();
        let first = pending
            .pop_front()
            .expect("streamed_params checked non-empty above");
        let first_name = first
            .name
            .clone()
            .expect("streamed parameter names validated above");

        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        // Write the RPC prefix (headers, proc, positional + materialized named
        // params) then the first streamed parameter's header. The data-at-exec
        // branch of `serialize` writes name + status + TYPE_INFO and stops before
        // the value. The PLP opener is written lazily with the first chunk so the
        // parameter can still resolve to NULL.
        let serialization_result = async {
            rpc.serialize_prefix(&mut packet_writer).await?;
            first
                .serialize(
                    &mut packet_writer,
                    &database_collation,
                    false,
                    &GenericEncoder::new(),
                )
                .await
        }
        .await;
        let message = packet_writer.suspend();
        if let Err(error) = serialization_result {
            drop(rpc);
            // The prefix runs every materialized parameter through the same
            // checks as the non-streamed sites, so this is retractable rather
            // than a reason to discard the connection.
            self.retract_partial_request(message).await;
            return Err(error);
        }

        self.streamed_write_state = StreamedWriteState::Active(Box::new(StreamedWriteContext {
            message,
            pending,
            db_collation: database_collation,
            value_opened: false,
            null_signaled: false,
            timeout_sec,
        }));

        Ok(StreamedParamStatus::NeedData {
            param_name: first_name,
        })
    }

    /// Appends one value chunk to the streamed parameter currently open for
    /// data. Call zero or more times between
    /// a [`StreamedParamStatus::NeedData`] from
    /// [`begin_sp_executesql`](Self::begin_sp_executesql) (or
    /// [`end_streamed_param`](Self::end_streamed_param)) and the matching
    /// [`end_streamed_param`](Self::end_streamed_param).
    ///
    /// Empty chunks are ignored: a zero-length PLP chunk header is the value
    /// terminator, so it must never be emitted mid-value.
    ///
    /// # Errors
    /// Returns a usage error if no streamed parameter is currently open, if the
    /// parameter was already marked NULL via
    /// [`write_streamed_null`](Self::write_streamed_null), or if `chunk` is longer
    /// than [`u32::MAX`] bytes (the PLP chunk-length field is 32-bit).
    pub async fn write_streamed_chunk(&mut self, chunk: &[u8]) -> TdsResult<()> {
        if matches!(self.streamed_write_state, StreamedWriteState::Idle) {
            return Err(UsageError(
                "write_streamed_chunk called with no active streamed parameter.".to_string(),
            ));
        }
        if chunk.len() > u32::MAX as usize {
            return Err(UsageError(format!(
                "Streamed PLP chunk length {} exceeds the maximum chunk size of {} bytes.",
                chunk.len(),
                u32::MAX
            )));
        }

        let ctx = match std::mem::replace(&mut self.streamed_write_state, StreamedWriteState::Idle)
        {
            StreamedWriteState::Active(ctx) => ctx,
            StreamedWriteState::Idle => {
                return Err(UsageError(
                    "write_streamed_chunk called with no active streamed parameter.".to_string(),
                ));
            }
        };
        let StreamedWriteContext {
            message,
            pending,
            db_collation,
            value_opened,
            null_signaled,
            timeout_sec,
        } = *ctx;
        self.remaining_request_timeout = timeout_sec.map(|s| Duration::from_secs(u64::from(s)));

        // A parameter already signalled NULL cannot carry data. Re-park the
        // (still-clean) message and reject; this is a caller sequencing error,
        // not a wire failure, so the stream stays usable. Checked before the
        // empty-chunk short-circuit below so `write_streamed_chunk(&[])` after
        // `write_streamed_null()` still errors instead of silently succeeding.
        if null_signaled {
            self.streamed_write_state =
                StreamedWriteState::Active(Box::new(StreamedWriteContext {
                    message,
                    pending,
                    db_collation,
                    value_opened,
                    null_signaled,
                    timeout_sec,
                }));
            return Err(UsageError(
                "write_streamed_chunk called after the parameter was marked NULL.".to_string(),
            ));
        }

        // Empty chunks are ignored: a zero-length PLP chunk header is the value
        // terminator, so it must never be emitted mid-value. Re-park the
        // (unchanged) message so a later chunk or the terminator continues
        // from the same point.
        if chunk.is_empty() {
            self.streamed_write_state =
                StreamedWriteState::Active(Box::new(StreamedWriteContext {
                    message,
                    pending,
                    db_collation,
                    value_opened,
                    null_signaled,
                    timeout_sec,
                }));
            return Ok(());
        }

        let mut packet_writer = PacketWriter::resume(message, self.transport.as_writer());
        let result = async {
            // Lazily write the unknown-length opener on the first chunk. Deferring
            // it (rather than emitting it at header time) is what lets a streamed
            // parameter still resolve to NULL before any data is sent.
            if !value_opened {
                packet_writer.write_u64_async(PLP_UNKNOWN_LEN).await?;
            }
            packet_writer.write_u32_async(chunk.len() as u32).await?;
            packet_writer.write_async(chunk).await
        }
        .await;
        let message = packet_writer.suspend();

        match result {
            Ok(()) => {
                // Chunk framed cleanly: re-park the message so the next chunk or
                // the terminator continues exactly where this one left off. The
                // opener is now on the wire, so the value is committed as present.
                self.streamed_write_state =
                    StreamedWriteState::Active(Box::new(StreamedWriteContext {
                        message,
                        pending,
                        db_collation,
                        value_opened: true,
                        null_signaled: false,
                        timeout_sec,
                    }));
                Ok(())
            }
            Err(e) => {
                // A partial value chunk is now on the wire, so this message can no
                // longer be continued safely. Drop it and abort the streamed
                // write rather than re-parking it as resumable.
                drop(message);
                self.abort_streamed_write().await;
                Err(e)
            }
        }
    }

    /// Aborts an in-progress streamed PLP write after a mid-stream failure.
    ///
    /// The half-written RPC message is dropped rather than re-parked, so a
    /// subsequent [`write_streamed_chunk`](Self::write_streamed_chunk) or
    /// [`end_streamed_param`](Self::end_streamed_param) fails cleanly (no active
    /// stream) instead of appending to a corrupt message. The transport is closed
    /// because RESETCONNECTION applies only to a subsequent request and cannot
    /// terminate this incomplete RPC.
    ///
    /// The request is lost, but the session need not be: the open-batch flag is
    /// cleared here, so a caller that keeps the client alive will pass
    /// `is_recovery_possible` and reconnect on its next
    /// [`check_and_reconnect`](Self::check_and_reconnect).
    async fn abort_streamed_write(&mut self) {
        self.streamed_write_state = StreamedWriteState::Idle;
        self.execution_context.set_has_open_batch(false);
        // A streamed `sp_prepexec` armed a capture for the `@handle` RETURNVALUE
        // that will now never arrive; leaving it armed would divert an unrelated
        // RPC's first return value into the handle map.
        self.abort_pending_prepare_capture();
        self.transport.mark_known_dead();
        if let Err(error) = self.transport.close_transport().await {
            warn!(%error, "Failed to close transport after streamed write abort");
        }
    }

    /// Cancels an in-progress streamed PLP write while the client is parked in
    /// [`StreamedParamStatus::NeedData`](StreamedParamStatus::NeedData),
    /// discarding the half-written RPC.
    ///
    /// This is the supported way for a caller to bail out of a streamed
    /// parameter sequence once [`begin_sp_executesql`](Self::begin_sp_executesql)
    /// has parked a message (for example, to service `SQLCancel` while an ODBC
    /// driver is between `SQLPutData` calls, or to unwind after the driver
    /// rejects a chunk). After this returns, no streamed write is active, so a
    /// subsequent [`write_streamed_chunk`](Self::write_streamed_chunk),
    /// [`write_streamed_null`](Self::write_streamed_null), or
    /// [`end_streamed_param`](Self::end_streamed_param) fails with a usage
    /// error. Calling this with no streamed write active is a no-op.
    ///
    /// The connection normally survives, which is what lets an application keep
    /// using a statement after a cancelled or rejected data-at-execution
    /// sequence. How that is achieved depends on how much of the request has
    /// escaped, mirroring msodbcsql's state-aware cancel:
    ///
    /// - nothing sent yet: the parked message is dropped locally and no bytes
    ///   go to the server at all;
    /// - partially sent: the message is closed with an EOM | IGNORE packet so
    ///   the server discards it, and the DONE it answers with is consumed.
    ///
    /// Only if that handshake fails does the transport close, since the request
    /// is then neither complete nor retractable.
    pub async fn cancel_streamed_write(&mut self) {
        let StreamedWriteState::Active(context) =
            std::mem::replace(&mut self.streamed_write_state, StreamedWriteState::Idle)
        else {
            return;
        };
        // Same reasoning as `abort_streamed_write`: a cancelled `sp_prepexec`
        // never yields its `@handle`, so the capture must not stay armed.
        self.abort_pending_prepare_capture();

        if context.message.nothing_sent() {
            // Not a plain drop: the message consumed the connection's pending
            // RESETCONNECTION bit when it was opened, and it never reached the
            // network to carry it. `abandon` puts it back so the next request
            // does, keeping the pool's one-shot reset honest.
            context.message.abandon(self.transport.as_writer());
            self.execution_context.set_has_open_batch(false);
            return;
        }

        match self.withdraw_sent_message(context.message).await {
            Withdrawal::Done | Withdrawal::ConnectionAlreadyDead => {
                self.execution_context.set_has_open_batch(false);
            }
            Withdrawal::Failed(error) => {
                warn!(%error, "Failed to withdraw a cancelled streamed write");
                self.abort_streamed_write().await;
            }
            Withdrawal::WriteAbandoned(error) => {
                warn!(%error, "Abandoned a cancelled streamed write mid-write");
                self.retire_without_writing();
            }
        }
    }

    /// Gives up a request whose serialization failed, so the failure costs the
    /// request rather than the connection.
    ///
    /// How depends on how much of the message reached the server: nothing is
    /// discarded locally, part is withdrawn with `EOM | IGNORE`, and all of it is
    /// cancelled with an attention. Without this the server holds a truncated
    /// message and answers 4002 on the *next* command.
    async fn retract_partial_request(&mut self, message: SuspendedMessage) {
        // Before anything that drains: a RETURNVALUE read with the capture still
        // armed would record a handle for a request that never ran.
        // `cancel_streamed_write` disarms up front for the same reason.
        self.abort_pending_prepare_capture();

        if message.nothing_sent() {
            // Not a plain drop: re-arm the RESETCONNECTION bit this message took.
            message.abandon(self.transport.as_writer());
            self.execution_context.set_has_open_batch(false);
            return;
        }

        if message.message_complete() {
            // The server has the whole request and will answer it, so there is
            // nothing to withdraw - an `EOM | IGNORE` would open a second message
            // and leave its DONE for the next command. Cancel with an attention
            // instead, which is msodbcsql's `STATE_BATCH_CMDSENT` arm. The
            // transport marks itself dead if the attention goes unacknowledged.
            //
            // Bounded by `ATTENTION_TIMEOUT_SECONDS`, not `CANCEL_TIMEOUT`:
            // msodbcsql passes its 120s cancel budget here too, but an ACK that
            // has not arrived in 5s is not coming, and the bulk-load abort takes
            // the same bound for the same reason.
            //
            // Dropped rather than abandoned: this message carried its reset bit
            // all the way out and `note_reset_dispatched` recorded it, so the
            // acknowledgement is already being tracked. Re-arming would send it
            // twice.
            drop(message);
            // `send_attention_and_wait` logs its own timeouts, but the write
            // failure path returns without logging - and that is the one that
            // costs a connection.
            if let Err(error) = self
                .send_attention_with_timeout(Duration::from_secs(ATTENTION_TIMEOUT_SECONDS))
                .await
            {
                warn!(%error, "Failed to cancel a fully sent request");
            }
            return;
        }

        match self.withdraw_sent_message(message).await {
            Withdrawal::Done | Withdrawal::ConnectionAlreadyDead => {
                self.execution_context.set_has_open_batch(false);
            }
            Withdrawal::Failed(error) => {
                warn!(%error, "Failed to withdraw a partially sent request");
                self.abort_partial_request().await;
            }
            Withdrawal::WriteAbandoned(error) => {
                warn!(%error, "Abandoned a partially sent request mid-write");
                self.retire_without_writing();
            }
        }
    }

    /// Closes an already-sent message with `EOM | IGNORE`, allowing 60 seconds
    /// for the write and then 120 seconds to consume its DONE. A stalled write
    /// hits the 120-second outer deadline and skips the drain. msodbcsql instead
    /// allows 120 seconds for each sequential leg.
    async fn withdraw_sent_message(&mut self, message: SuspendedMessage) -> Withdrawal {
        // Cached read, not `is_connection_dead`: that one `try_read`s a byte,
        // which here could swallow the server's answer to the half-written
        // request. msodbcsql's `FIsConnectionDead` is likewise a cached flag.
        if self.transport.connection_known_dead() {
            // Dead or not, opening this message took the connection's one-shot
            // reset arm; hand it back rather than swallowing it in a plain drop.
            message.abandon(self.transport.as_writer());
            return Withdrawal::ConnectionAlreadyDead;
        }

        // Read before `resume` takes it: the server discards an ignored message
        // whole, so a reset bit already on the wire has to ride a later request.
        let carried_reset = message.reset_mode();

        let mut packet_writer = PacketWriter::resume(
            message
                .with_write_timeout(Some(CANCEL_WRITE_TIMEOUT_SECS))
                .without_cancellation(),
            self.transport.as_writer(),
        );
        // `PacketWriter` only checks its budget once a write returns, so the
        // ignore packet needs an outer deadline too. Reaching that one means the
        // write never came back, so the future is dropped mid-record and the
        // transport is retired without being written to again.
        let ignored =
            tokio::time::timeout(CANCEL_TIMEOUT, packet_writer.cancel_current_message()).await;
        drop(packet_writer);
        match ignored {
            Ok(Ok(())) => {}
            Ok(Err(error)) => return Withdrawal::Failed(error),
            Err(_) => {
                return Withdrawal::WriteAbandoned(crate::error::Error::TimeoutError(
                    crate::error::TimeoutErrorType::String(
                        "Timed out sending the ignore packet".to_string(),
                    ),
                ));
            }
        }

        self.rearm_withdrawn_reset(carried_reset);

        // The server acknowledges an ignored message with a DONE. Leaving it
        // unread would desynchronize the next command.
        let saved_timeout = self.remaining_request_timeout.replace(CANCEL_TIMEOUT);
        let saved_cancel = self.cancel_handle.take();
        let drained = self.drain_stream().await;
        self.cancel_handle = saved_cancel;
        self.remaining_request_timeout = saved_timeout;
        match drained {
            Ok(_) => Withdrawal::Done,
            Err(error) => Withdrawal::Failed(error),
        }
    }

    /// Hands back the RESETCONNECTION bit a withdrawn message carried away.
    ///
    /// Packet #1 recorded the dispatch, but the server discards the whole
    /// ignored message, reset included. Leaving that record set would make the
    /// withdrawal's own DONE look like a request that ran without resetting, and
    /// `observe_response_token` would condemn a connection that is still fine.
    ///
    /// Deliberately diverges from msodbcsql, which clears `m_fResetConnection`
    /// as the bit goes out (`SendPacket`, `tds/TdsSend.cpp`) and re-arms only on
    /// pooled reuse (`odbc/sqlcmisc.cpp`). It has the same hole and never
    /// notices, having no reset-acknowledgement check to break.
    fn rearm_withdrawn_reset(&mut self, carried_reset: ResetConnectionMode) {
        if carried_reset == ResetConnectionMode::None {
            return;
        }
        // Also clears the dispatch record packet 1 left behind.
        self.transport.as_writer().set_reset_mode(carried_reset);
    }

    /// Completes a send, retracting the half-sent message when serialization
    /// failed so the failure costs the request rather than the connection.
    ///
    /// SQL batch and RPC sends that can fail after bytes reach an otherwise
    /// usable transport must pass their result and suspended message here.
    /// TODO(AB#47772): move these sends behind one API.
    ///
    /// The `drop(rpc)` stays at each call site: `SqlRpc` borrows
    /// `&self.execution_context`, so that borrow has to end before `&mut self`.
    pub(super) async fn finish_send(
        &mut self,
        serialize_result: TdsResult<()>,
        message: SuspendedMessage,
    ) -> TdsResult<()> {
        if let Err(e) = serialize_result {
            self.retract_partial_request(message).await;
            return Err(e);
        }
        Ok(())
    }

    /// Closes the transport after a request could not be retracted.
    /// RESETCONNECTION applies to a later request and cannot terminate an
    /// incomplete one, so the socket is all that is left to discard. Clearing
    /// the open-batch flag lets the next `check_and_reconnect` recover.
    async fn abort_partial_request(&mut self) {
        self.retire_without_writing();
        if let Err(error) = self.transport.close_transport().await {
            warn!(%error, "Failed to close transport after a partial request abort");
        }
    }

    /// Retires the transport without shutting the stream down.
    ///
    /// For a write that was dropped mid-flight the stream may still hold a
    /// half-flushed record, and `close_transport` shuts it down — which on the
    /// native-tls engine emits a close_notify, one more write on exactly that
    /// stream. `send_attention_and_wait` avoids it the same way, by marking the
    /// connection dead and never writing again.
    fn retire_without_writing(&mut self) {
        self.execution_context.set_has_open_batch(false);
        self.abort_pending_prepare_capture();
        self.transport.mark_known_dead();
    }

    /// Marks the streamed parameter currently open for data as SQL NULL.
    ///
    /// Call this instead of [`write_streamed_chunk`](Self::write_streamed_chunk)
    /// when a data-at-execution parameter resolves to NULL (the ODBC
    /// `SQLPutData(SQL_NULL_DATA)` case). No bytes are written now; when the
    /// parameter is closed with [`end_streamed_param`](Self::end_streamed_param)
    /// the driver emits `PLP_NULL` instead of an unknown-length opener +
    /// terminator. Mirrors msodbcsql, which writes `VARMAX_LENGTH_NULL` with no
    /// chunks for a DAE parameter that resolves to NULL.
    ///
    /// # Errors
    /// Returns a usage error if no streamed parameter is currently open, or if
    /// value chunks have already been written for this parameter (a value that
    /// has begun streaming cannot become NULL).
    pub fn write_streamed_null(&mut self) -> TdsResult<()> {
        let ctx = match std::mem::replace(&mut self.streamed_write_state, StreamedWriteState::Idle)
        {
            StreamedWriteState::Active(ctx) => ctx,
            StreamedWriteState::Idle => {
                return Err(UsageError(
                    "write_streamed_null called with no active streamed parameter.".to_string(),
                ));
            }
        };
        let StreamedWriteContext {
            message,
            pending,
            db_collation,
            value_opened,
            null_signaled: _,
            timeout_sec,
        } = *ctx;

        if value_opened {
            // Chunks are already on the wire; the value cannot become NULL. Re-park
            // the (still-clean) message — this is a caller sequencing error.
            self.streamed_write_state =
                StreamedWriteState::Active(Box::new(StreamedWriteContext {
                    message,
                    pending,
                    db_collation,
                    value_opened,
                    null_signaled: false,
                    timeout_sec,
                }));
            return Err(UsageError(
                "write_streamed_null called after value chunks were already written.".to_string(),
            ));
        }

        self.streamed_write_state = StreamedWriteState::Active(Box::new(StreamedWriteContext {
            message,
            pending,
            db_collation,
            value_opened: false,
            null_signaled: true,
            timeout_sec,
        }));
        Ok(())
    }

    /// Closes the streamed parameter currently open for data.
    ///
    /// The current parameter's value is closed on the wire:
    /// - if it was marked NULL via [`write_streamed_null`](Self::write_streamed_null),
    ///   `PLP_NULL` is written (no opener, no terminator);
    /// - if one or more chunks were written, the `PLP_TERMINATOR` is written; and
    /// - if neither (an untouched parameter), the unknown-length opener +
    ///   terminator are written, encoding a present, zero-length value.
    ///
    /// If more streamed parameters remain, the next one's header is written and
    /// [`StreamedParamStatus::NeedData`] is returned (stream its chunks next).
    /// When the last streamed parameter closes, the RPC message is finalized and
    /// sent, then the real server result is returned in
    /// [`StreamedParamStatus::Complete`].
    ///
    /// # Errors
    /// Returns a usage error if no streamed parameter is currently open, or an
    /// I/O error if sending fails.
    pub async fn end_streamed_param(&mut self) -> TdsResult<StreamedParamStatus> {
        let ctx = match std::mem::replace(&mut self.streamed_write_state, StreamedWriteState::Idle)
        {
            StreamedWriteState::Active(ctx) => ctx,
            StreamedWriteState::Idle => {
                return Err(UsageError(
                    "end_streamed_param called with no active streamed parameter.".to_string(),
                ));
            }
        };
        let StreamedWriteContext {
            message,
            mut pending,
            db_collation,
            value_opened,
            null_signaled,
            timeout_sec,
        } = *ctx;
        self.remaining_request_timeout = timeout_sec.map(|s| Duration::from_secs(u64::from(s)));

        let mut packet_writer = PacketWriter::resume(message, self.transport.as_writer());

        // Close the current value, then either open the next streamed parameter's
        // header or (for the last one) finalize the send. Anything that fails
        // mid-message aborts the whole streamed write.
        let write_outcome = async {
            if null_signaled {
                // NULL: the length field is PLP_NULL and no chunks/terminator
                // follow.
                packet_writer.write_u64_async(PLP_NULL).await?;
            } else {
                // An untouched parameter never wrote its opener; write it now so
                // the value is a present, zero-length value rather than absent.
                if !value_opened {
                    packet_writer.write_u64_async(PLP_UNKNOWN_LEN).await?;
                }
                packet_writer.write_u32_async(PLP_TERMINATOR).await?;
            }
            match pending.pop_front() {
                Some(next) => {
                    let next_name = next
                        .name
                        .clone()
                        .expect("streamed parameter names validated at begin");
                    next.serialize(
                        &mut packet_writer,
                        &db_collation,
                        false,
                        &GenericEncoder::new(),
                    )
                    .await?;
                    Ok(Some(next_name))
                }
                None => {
                    packet_writer.finalize().await?;
                    Ok(None)
                }
            }
        }
        .await;

        match write_outcome {
            // Another streamed parameter is now open for data.
            Ok(Some(next_name)) => {
                let message = packet_writer.suspend();
                self.streamed_write_state =
                    StreamedWriteState::Active(Box::new(StreamedWriteContext {
                        message,
                        pending,
                        db_collation,
                        // Fresh parameter: its opener has not been written and it
                        // has not been marked NULL.
                        value_opened: false,
                        null_signaled: false,
                        timeout_sec,
                    }));
                Ok(StreamedParamStatus::NeedData {
                    param_name: next_name,
                })
            }
            // Last streamed parameter closed and the message was sent: consume
            // the response exactly like execute_sp_executesql does. A failure
            // reading the response also aborts (the request is already on the
            // wire, so the connection must be reset before reuse).
            Ok(None) => {
                drop(packet_writer);
                match self.position_on_first_result().await {
                    Ok(result) => Ok(StreamedParamStatus::Complete(result)),
                    Err(e) => {
                        self.abort_streamed_write().await;
                        Err(e)
                    }
                }
            }
            // Terminator or next-parameter header write failed mid-message:
            // withdraw it rather than leaving it resumable or discarding the
            // connection for a failure that cost only the request.
            Err(e) => {
                let message = packet_writer.suspend();
                self.retract_partial_request(message).await;
                Err(e)
            }
        }
    }

    /// Executes a bulk load operation using zero-copy streaming.
    ///
    /// This method provides superior performance by eliminating per-row Vec allocations.
    /// Rows are serialized directly to the packet writer via the `BulkLoadRow` trait.
    ///
    /// # Performance Benefits
    ///
    /// - **Zero allocations per row**: No `dest_buffer.clone()` needed
    /// - **Direct serialization**: Columns written directly to TDS packet
    /// - **Column context reuse**: Created once, reused for all rows
    ///
    /// # Type Parameters
    ///
    /// * `R` - Row type implementing `BulkLoadRow` trait
    ///
    /// # Arguments
    ///
    /// * `table_name` - Target table name
    /// * `column_metadata` - Column metadata for destination columns
    /// * `options` - Bulk copy options
    /// * `timeout_sec` - Optional timeout in seconds
    /// * `cancel_handle` - Optional cancellation handle
    /// * `rows` - Vector of rows to insert
    /// * `resolved_mappings` - Column mapping information
    ///
    /// # Returns
    ///
    /// Returns the number of rows this client serialized to the wire, matching
    /// `Microsoft.Data.SqlClient`'s `SqlBulkCopy.RowsCopied` semantics. This is
    /// a client-side count, not the server's DONE token row count, so it is not
    /// affected by distributed engines that acknowledge one load with multiple
    /// DONE_COUNT tokens (issue #209). It also does not reflect server-side row
    /// count changes from triggers on the destination table.
    #[instrument(skip(self, rows), level = "info")]
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn execute_bulk_load_streaming_zerocopy<R>(
        &mut self,
        table_name: String,
        column_metadata: Vec<BulkCopyColumnMetadata>,
        options: BulkCopyOptions,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
        rows: impl Iterator<Item = R>,
        resolved_mappings: &[ResolvedColumnMapping],
    ) -> TdsResult<u64>
    where
        R: BulkLoadRow,
    {
        if self.command_is_busy() {
            return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
        }

        self.begin_command();
        let reconnect_elapsed = self.check_and_reconnect(timeout_sec, cancel_handle).await?;
        let budget = Self::deduct_timeout(timeout_sec, reconnect_elapsed);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        let request_timeout = resolved.duration();

        // Store timeout and cancel handle for this operation
        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());

        self.transport.reset_reader();

        // STEP 1: Filter column metadata to only include mapped columns
        // If we have column mappings, only include the destination columns that are mapped.
        // This allows SQL Server to handle NULL/defaults for unmapped columns.
        let mapped_column_metadata = if resolved_mappings.is_empty() {
            // No mappings specified - use all columns (ordinal mapping)
            column_metadata.clone()
        } else {
            // Filter to only mapped destination columns, preserving their order
            resolved_mappings
                .iter()
                .map(|mapping| column_metadata[mapping.destination_index].clone())
                .collect()
        };

        // STEP 2: Send INSERT BULK command and consume response
        // Use the filtered metadata so the command only references mapped columns
        let insert_bulk_command =
            build_insert_bulk_command(&table_name, &mapped_column_metadata, &options)?;
        self.send_batch_and_consume_response(insert_bulk_command, timeout_sec, cancel_handle)
            .await?;

        // STEP 3: Create streaming writer and begin
        let default_collation = self.get_collation();

        // Always Encrypted: when column encryption is negotiated and enabled,
        // resolve the plaintext CEK for each encrypted destination column so the
        // writer can encrypt row values and emit the encrypted COLMETADATA.
        //
        // With `allow_encrypted_value_modifications`, the caller supplies
        // ciphertext directly, so we skip CEK resolution entirely and let the
        // writer pass those values through verbatim.
        let has_encrypted_columns = mapped_column_metadata.iter().any(|c| c.is_encrypted);
        let encrypt_bulk_copy = self.should_encrypt_bulk_copy() && has_encrypted_columns;
        let passthrough_ciphertext =
            encrypt_bulk_copy && options.allow_encrypted_value_modifications;

        let plaintext_ceks: Vec<Option<std::sync::Arc<zeroize::Zeroizing<Vec<u8>>>>> =
            if encrypt_bulk_copy && !passthrough_ciphertext {
                use crate::security::keystore::decrypt_cek;

                let (providers, cek_cache, trusted_key_paths) = {
                    let client_context =
                        self.recovery_context
                            .client_context
                            .as_ref()
                            .ok_or_else(|| {
                                crate::error::Error::ColumnEncryptionError(
                                    "Cannot encrypt bulk copy values without a client context"
                                        .to_string(),
                                )
                            })?;
                    (
                        client_context.column_encryption_key_store_providers.clone(),
                        client_context.cek_cache.clone(),
                        client_context
                            .trusted_key_paths_for_current_server()
                            .to_vec(),
                    )
                };

                let mut ceks = Vec::with_capacity(mapped_column_metadata.len());
                for col in &mapped_column_metadata {
                    match &col.encryption {
                        Some(enc) => {
                            let cek = decrypt_cek(
                                &providers,
                                &cek_cache,
                                &enc.cek_entry,
                                &trusted_key_paths,
                            )
                            .await?;
                            ceks.push(Some(cek));
                        }
                        None => ceks.push(None),
                    }
                }
                ceks
            } else {
                Vec::new()
            };

        let mut packet_writer = PacketWriter::new(
            PacketType::BulkLoad,
            self.transport.as_writer(),
            timeout_sec,
            cancel_handle,
        );

        let mut writer = StreamingBulkLoadWriter::new(
            &mut packet_writer,
            table_name,
            mapped_column_metadata,
            default_collation,
        );

        // Enable Always Encrypted serialization before writing metadata so the
        // COLMETADATA carries the CEK table and per-column crypto metadata. Under
        // ciphertext passthrough the metadata is still emitted, but values are
        // sent verbatim rather than encrypted, so no plaintext CEKs are attached.
        if passthrough_ciphertext {
            writer.set_column_encryption_enabled(true);
            writer.set_allow_encrypted_value_modifications(true);
        } else if !plaintext_ceks.is_empty() {
            writer.set_column_encryption_enabled(true);
            writer.set_plaintext_ceks(plaintext_ceks);
        }

        // Begin streaming (write metadata)
        writer.begin().await?;

        // STEP 3: Stream rows using zero-copy path
        // If an error occurs during row writing, we need to send an attention packet
        // to gracefully cancel the bulk load operation and leave the connection usable.
        let mut row_write_error: Option<crate::error::Error> = None;
        for row in rows {
            // Write the row directly using the streaming writer
            if let Err(e) = writer.write_row_zerocopy(&row).await {
                row_write_error = Some(e);
                break;
            }
        }

        // Handle error during row streaming
        if let Some(original_error) = row_write_error {
            // Send attention packet to cancel the bulk load operation gracefully.
            // This tells SQL Server to abort the current operation and resets the
            // TDS protocol state so the connection can be reused.
            // The stream is always in a clean state here because writes are never
            // dropped mid-flight (issue #513).
            // If the attention is never acknowledged the transport marks itself
            // dead, so clearing the batch flag below cannot hand out a connection
            // with an ATTENTION still outstanding.
            let attention_timeout = Duration::from_secs(ATTENTION_TIMEOUT_SECONDS);
            let _ = self.send_attention_with_timeout(attention_timeout).await;
            return Err(original_error);
        }

        // STEP 4: End streaming (write DONE token and finalize)
        let rows_written = writer.end().await?;

        // STEP 5: Drain the server response for error handling and INFO capture.
        // Its returned count is informational only; callers receive the client-side
        // `rows_written` (see the `# Returns` doc and `consume_done_token`).
        self.consume_done_token().await?;

        Ok(rows_written)
    }

    /// Consumes response tokens until a DONE token is received.
    ///
    /// Returns the last counted DONE row count. This value is currently
    /// informational: both call sites discard it, and the bulk-load path reports
    /// the client-side rows written instead (issue #209). It is retained for
    /// error/INFO draining and as defensive last-DONE_COUNT-wins hardening.
    ///
    /// This helper method implements the standard TDS response consumption pattern,
    /// handling INFO, ERROR, and DONE tokens appropriately.
    async fn consume_done_token(&mut self) -> TdsResult<u64> {
        let parser_context = ParserContext::None(());
        let mut rows_affected = 0_u64;
        let mut collected_errors: Vec<SqlErrorInfo> = Vec::new();

        loop {
            let token = self.next_response_token(&parser_context).await?;

            match token {
                Tokens::Done(done) | Tokens::DoneProc(done) | Tokens::DoneInProc(done) => {
                    info!("Done token: {:?}", done);

                    if done.has_error() && collected_errors.is_empty() {
                        return Err(crate::error::Error::ProtocolError(
                            "Server reported error in DONE token without preceding ERROR token"
                                .to_string(),
                        ));
                    }

                    // Distributed engines send multiple DONE_COUNT tokens each
                    // carrying the full count; summing them double-counts (#209).
                    // Last counted DONE wins.
                    if done.has_count() {
                        rows_affected = done.row_count;
                    }

                    // Stop when we receive a DONE token without the MORE flag
                    if !done.has_more() {
                        break;
                    }
                }
                Tokens::Error(error_token) => {
                    info!(?error_token);
                    collected_errors.push(self.record_error_token(&error_token));
                }
                Tokens::Info(info_token) => {
                    info!(?info_token);
                    self.capture_info_message(&info_token);
                    continue;
                }
                Tokens::EnvChange(env_change) => {
                    info!(?env_change);
                    if env_change.sub_type == EnvChangeTokenSubType::ResetConnection {
                        self.on_reset_connection_ack();
                    }
                    self.execution_context
                        .capture_change_property(&env_change, &mut self.negotiated_settings)?;
                    continue;
                }
                Tokens::SessionState(session_state) => {
                    self.recovery_context
                        .process_session_state(&session_state)?;
                    continue;
                }
                _ => {
                    info!("Unexpected token during bulk load: {:?}", token);
                    return Err(UsageError(format!(
                        "Unexpected token while executing bulk load: {token:?}"
                    )));
                }
            }
        }

        if !collected_errors.is_empty() {
            return Err(crate::error::Error::from_sql_errors(collected_errors));
        }

        Ok(rows_affected)
    }

    /// Sends a SQL batch and consumes the response without expecting column metadata.
    /// This is used for commands that don't return result sets (DML statements, etc.).
    ///
    /// Returns the DONE token row count. Its only caller (the INSERT BULK preamble)
    /// discards it; see `consume_done_token` for why the count is informational.
    async fn send_batch_and_consume_response(
        &mut self,
        sql_command: String,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<u64> {
        let batch = SqlBatch::new(sql_command, &self.execution_context);
        let mut packet_writer =
            batch.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = batch.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        self.finish_send(serialize_result, message).await?;

        // Consume the response
        self.consume_done_token().await
    }

    /// Executes a stored procedure via the TDS RPC protocol.
    ///
    /// Sends an `sp_executesql`-style RPC request for the named procedure.
    /// Parameters can be supplied positionally, by name, or both. If the
    /// procedure returns result sets, read the rows of each and move between
    /// result sets with [`advance_to_rows()`](Self::advance_to_rows). After all
    /// result sets are consumed, retrieve output parameters with
    /// [`get_return_values()`](Self::get_return_values).
    ///
    /// Only one batch may be active at a time — calling this while a previous
    /// result set is unread returns [`Error::UsageError`](crate::error::Error::UsageError).
    ///
    /// # Cancel / Timeout
    ///
    /// Pass `timeout_sec` to cap server-side execution time, or supply a
    /// [`CancelHandle`] to cancel the operation cooperatively from another
    /// task.
    #[instrument(
        skip(self, positional_parameters, named_parameters, options),
        level = "info"
    )]
    pub async fn execute_stored_procedure<'a>(
        &mut self,
        stored_procedure_name: String,
        positional_parameters: Option<Vec<RpcParameter>>,
        named_parameters: Option<Vec<RpcParameter>>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementResult> {
        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            column_encryption,
        } = options.into();
        self.current_command_ce_setting = column_encryption;

        let mut positional_parameters = positional_parameters;
        let mut named_parameters = named_parameters;

        if self.command_is_busy() {
            return Err(crate::error::Error::UsageError(
                ALREADY_EXECUTING_ERROR.to_string(),
            ));
        };

        RpcParameter::reject_data_at_exec(
            positional_parameters
                .iter()
                .flatten()
                .chain(named_parameters.iter().flatten()),
        )?;

        self.begin_command();
        let reconnect_elapsed = self.check_and_reconnect(timeout_sec, cancel_handle).await?;
        let budget = Self::deduct_timeout(timeout_sec, reconnect_elapsed);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        let request_timeout = resolved.duration();

        // Store timeout and cancel handle for this operation
        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());

        self.transport.reset_reader();

        // Always Encrypted: when the connection enabled column encryption and the
        // server acknowledged the feature, ask the server which parameters need
        // encryption (via `sp_describe_parameter_encryption` against an `EXEC`
        // form of the call) and encrypt them in place before sending the real
        // stored-procedure RPC. Positional parameters are described under
        // synthetic names bound by position; named parameters bind by name.
        self.ensure_force_column_encryption_supported(
            positional_parameters
                .iter()
                .flatten()
                .chain(named_parameters.iter().flatten()),
        )?;
        let has_positional = positional_parameters
            .as_ref()
            .is_some_and(|p| !p.is_empty());
        let has_named = named_parameters
            .as_ref()
            .is_some_and(|p| p.iter().any(|param| param.name.is_some()));
        if self.should_encrypt_parameters() && (has_positional || has_named) {
            let (tsql, params_decl) = Self::build_stored_procedure_describe_request(
                &stored_procedure_name,
                positional_parameters.as_deref().unwrap_or(&[]),
                named_parameters.as_deref().unwrap_or(&[]),
            )?;

            // Assemble one slice of mutable references in declaration order
            // (positional first, then named) so the describe result maps back by
            // ordinal (positional) or name (named).
            let mut combined: Vec<&mut RpcParameter> = Vec::new();
            if let Some(positional) = positional_parameters.as_mut() {
                combined.extend(positional.iter_mut());
            }
            if let Some(named) = named_parameters.as_mut() {
                combined.extend(named.iter_mut());
            }

            self.encrypt_combined_parameters(
                &tsql,
                &params_decl,
                &mut combined,
                timeout_sec,
                cancel_handle,
            )
            .await?;

            // The describe round-trip closes its own batch, which clears
            // the per-operation timeout/cancel state; restore it for the
            // real RPC.
            self.remaining_request_timeout = request_timeout;
            self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());
            self.transport.reset_reader();
        }

        let database_collation = self.negotiated_settings.database_collation;

        let rpc = SqlRpc::new(
            RpcType::Named(stored_procedure_name),
            positional_parameters,
            named_parameters,
            &database_collation,
            &self.execution_context,
        );

        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = rpc.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        drop(rpc);
        self.finish_send(serialize_result, message).await?;

        self.position_on_first_result().await
    }

    /// Prepares a parameterized statement via `sp_prepare`, returning the
    /// [`StatementId`] it issues for the statement.
    ///
    /// The server handle stays inside the client, keyed by that id, alongside
    /// the statement's cached Always Encrypted metadata. Pass the id to
    /// [`execute_sp_execute()`](Self::execute_sp_execute) for repeated execution
    /// without re-parsing, and to
    /// [`execute_sp_unprepare()`](Self::execute_sp_unprepare) when the statement
    /// is no longer needed.
    ///
    /// Drains the token stream internally — no rows are returned.
    ///
    /// # Arguments
    ///
    /// * `sql` — the parameterized T-SQL statement to prepare. Parameter
    ///   placeholders (e.g. `@p1`, `@db_name`) referenced here must be
    ///   declared in `named_params`.
    /// * `named_params` — declarations of the statement's parameters. Only
    ///   the `name` and SQL `type` of each entry are used to build the
    ///   `@params` declaration string passed to `sp_prepare`; any values
    ///   carried by the entries are ignored. Supply the actual parameter
    ///   values later on the matching
    ///   [`execute_sp_execute()`](Self::execute_sp_execute) call.
    /// # Recovery
    ///
    /// Unlike the other prepared RPCs, this method reconnects
    /// before sending. This is safe because `sp_prepare` accepts no existing
    /// handle that recovery could invalidate; the handle it records belongs to
    /// the resulting live session. Prefer the managed
    /// [`execute_prepared`](Self::execute_prepared) / [`unprepare`](Self::unprepare) API.
    #[allow(dead_code)]
    #[instrument(skip(self, named_params, options), level = "info")]
    async fn execute_sp_prepare<'a>(
        &mut self,
        sql: String,
        named_params: Vec<RpcParameter>,
        command_started: bool,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementId> {
        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            column_encryption,
        } = options.into();
        self.current_command_ce_setting = column_encryption;

        let reconnect_elapsed = if command_started {
            Duration::ZERO
        } else {
            if self.command_is_busy() {
                return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
            }
            self.begin_command();
            self.check_and_reconnect(timeout_sec, cancel_handle).await?
        };
        let budget = Self::deduct_timeout(timeout_sec, reconnect_elapsed);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        let request_timeout = resolved.duration();

        // Store timeout and cancel handle for this operation
        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());

        self.transport.reset_reader();

        let database_collation = self.negotiated_settings.database_collation;

        let sql_statement_value =
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(sql.clone())));

        // Create the parameter list for sp_prepare
        let execute_sql_statement_parameter =
            RpcParameter::new(None, StatusFlags::NONE, sql_statement_value);

        // Build the comma separated list of parameters
        let mut params_list_as_string = String::new();

        build_parameter_list_string(&named_params, &mut params_list_as_string)?;

        // Always Encrypted: describe the statement's parameters now (serving from
        // or populating the query-metadata cache) and pin the result under the
        // statement's id so a later sp_execute can encrypt values without
        // describing again. sp_prepare itself sends no user parameter values, so
        // nothing is encrypted here.
        let describe_for_cache = if self.should_encrypt_parameters() && !named_params.is_empty() {
            let has_output = named_params.iter().any(|p| p.is_output());
            let describe = self
                .describe_parameters_cached(
                    &sql,
                    &params_list_as_string,
                    has_output,
                    timeout_sec,
                    cancel_handle,
                )
                .await?;
            // A describe round-trip (on a cache miss) closes its own batch and
            // clears the per-operation timeout/cancel state; restore it for the
            // prepare RPC.
            self.remaining_request_timeout = request_timeout;
            self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());
            self.transport.reset_reader();
            Some(describe)
        } else {
            None
        };

        let params_as_sql_string =
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(params_list_as_string)));

        let params_parameter = RpcParameter::new(None, StatusFlags::NONE, params_as_sql_string);

        let output_handler_value = SqlType::Int(None);

        let output_handler_parameter = RpcParameter::new(
            None,
            StatusFlags::BY_REF_VALUE, // Output parameter
            output_handler_value,
        );

        // Create the parameter list for positional parameters of sp_prepare.
        let positional_parameters_vec = vec![
            output_handler_parameter,
            params_parameter,
            execute_sql_statement_parameter,
        ];
        let positional_parameters = Some(positional_parameters_vec);

        // Build the RPC request.
        // sp_prepare's RPC contract is fixed: @handle (output int), @params (ntext),
        // @stmt (ntext), @options (int, optional). It does not accept any user
        // parameter values; those are sent later on sp_execute (or together on
        // sp_prepexec / sp_executesql). Forwarding `named_params` here causes the
        // server to surface "Procedure expects parameter '@options' of type 'int'."
        // for any non-int user parameter type.
        let rpc = SqlRpc::new(
            RpcType::ProcId(RpcProcs::Prepare),
            positional_parameters,
            None,
            &database_collation,
            &self.execution_context,
        );

        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = rpc.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        drop(rpc);
        self.finish_send(serialize_result, message).await?;

        // Drain to completion to get output parameters and any server errors.
        let server_errors = self.drain_stream_or_retire().await?;

        // We need to get the return value, and then extract the handle from it.
        // If the server reported errors during prepare, surface them instead of a
        // generic ProtocolError so callers can see the underlying SQL Server
        // diagnostic.
        if !server_errors.is_empty() {
            return Err(crate::error::Error::from_sql_errors(server_errors));
        }
        if self.return_values.len() == 1 {
            let returned_parameter = self.return_values.first().unwrap();
            if let ColumnValues::Int(handle) = &returned_parameter.value {
                let handle = *handle;
                let statement_id = self.issue_statement_id();
                let previous = self.prepared_handles.insert(statement_id, handle);
                debug_assert!(
                    previous.is_none(),
                    "prepared handle map overwrote a live entry for a reused StatementId"
                );
                if let Some(describe) = describe_for_cache {
                    self.prepared_param_encryption
                        .insert(statement_id, describe);
                }
                Ok(statement_id)
            } else {
                Err(crate::error::Error::ProtocolError(
                    "Expected an integer value".to_string(),
                ))
            }
        } else {
            Err(crate::error::Error::ProtocolError(
                "Expected exactly one output parameter".to_string(),
            ))
        }
    }

    /// Releases a prepared statement handle via `sp_unprepare`.
    ///
    /// Frees server-side resources associated with the handle returned by
    /// [`execute_sp_prepare()`](Self::execute_sp_prepare) or
    /// [`execute_sp_prepexec()`](Self::execute_sp_prepexec).
    ///
    /// # Recovery
    ///
    /// This method never reconnects. `sp_unprepare` releases an *existing*
    /// server handle, so once the connection has reconnected that handle is
    /// already gone — reusing it hits SQL Server error 8179. Staleness needs no
    /// caller check: a reconnect clears `prepared_handles`, so an id with no
    /// entry is skipped below without an RPC; on a dead connection the send just
    /// fails and is ignored (best-effort). Forcing recovery, if ever wanted, is
    /// the caller's job (see
    /// [`check_and_reconnect`](Self::check_and_reconnect)).
    /// A low-level wire call with caller-owned recovery — prefer the
    /// managed [`execute_prepared`](Self::execute_prepared) / [`unprepare`](Self::unprepare) API.
    ///
    /// Drops `statement_id`'s handle and cached Always Encrypted metadata from
    /// the client's maps before sending, whether or not the RPC succeeds: a
    /// failure is ambiguous (the send may have landed and the response been
    /// lost), and a map entry naming a plan the server already dropped would
    /// make the next execute fail with error 8179 instead of re-preparing.
    /// Absent is the recoverable state; stale-but-present is not.
    ///
    /// `command_started`: `true` when the caller already opened the command
    /// boundary via `begin_command` (as `unprepare` does before recovery, so the
    /// reconnect's info messages survive); `false` opens it here. It does not
    /// affect recovery — this method never reconnects.
    #[instrument(skip(self, options), level = "info")]
    async fn execute_sp_unprepare<'a>(
        &mut self,
        statement_id: StatementId,
        command_started: bool,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<()> {
        if !command_started {
            if self.command_is_busy() {
                return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
            }
            self.begin_command();
        }
        // No reconnect here — recovery is caller-owned (see this method's
        // `# Recovery` docs).

        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            ..
        } = options.into();

        // Store timeout and cancel handle for this operation
        let budget = Self::deduct_timeout(timeout_sec, Duration::ZERO);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        let request_timeout = resolved.duration();
        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());

        self.transport.reset_reader();

        // Evicted before the send: a failed RPC is ambiguous, and keeping an
        // entry the server may already have dropped is the worse of the two
        // wrong answers (see this method's docs).
        let Some(handle) = self.prepared_handles.remove(&statement_id) else {
            return Ok(());
        };
        self.prepared_param_encryption.remove(&statement_id);

        let database_collation = self.negotiated_settings.database_collation;

        let handle_value = SqlType::Int(Some(handle));
        let handle_parameter = RpcParameter::new(None, StatusFlags::NONE, handle_value);

        let positional_parameters_vec = vec![handle_parameter];
        let positional_parameters = Some(positional_parameters_vec);

        // Build the RPC request.
        let rpc = SqlRpc::new(
            RpcType::ProcId(RpcProcs::Unprepare),
            positional_parameters,
            None,
            &database_collation,
            &self.execution_context,
        );

        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = rpc.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        drop(rpc);
        self.finish_send(serialize_result, message).await?;

        // Drain the result set. A successful unprepare returns no results,
        // but surface any server errors collected during the drain instead of
        // silently discarding them.
        let server_errors = self.drain_stream_or_retire().await?;
        if !server_errors.is_empty() {
            return Err(crate::error::Error::from_sql_errors(server_errors));
        }
        Ok(())
    }

    /// Executes `statement`, transparently recovering the connection and
    /// re-preparing the server handle when it no longer belongs to the live
    /// session.
    ///
    /// Owns the full recovery protocol so callers never juggle raw handle ids or
    /// session epochs:
    ///
    /// 1. Recover the connection if the socket died, and charge the elapsed
    ///    time against the command timeout.
    /// 2. If `statement` holds a handle from the live session, reuse it via
    ///    `sp_execute`.
    /// 3. Otherwise prepare and execute in one round trip via `sp_prepexec`; the
    ///    new handle is recorded inside the client, keyed by the statement's
    ///    [`StatementId`], when the `@handle` RETURNVALUE lands during the drain
    ///    — no caller step is required.
    ///
    /// `orphaned` names a statement superseded by a re-prepare/rebind whose
    /// server handle should be released: its drop is piggybacked onto the
    /// `sp_prepexec` `@handle` argument when the handle is still live in this
    /// session, and skipped when the map no longer holds it (a reconnect already
    /// discarded it server-side). The id is cleared from `orphaned` only once the
    /// drop crosses the serialization boundary, so callers retain it across
    /// reconnect, validation, parameter-building, and encryption failures that
    /// precede the send and can retry its release.
    ///
    /// Returns positioned on the first result; drain rows with
    /// [`next_row`](ResultSet::next_row) / [`advance`](Self::advance).
    pub async fn execute_prepared<'a>(
        &mut self,
        statement: &mut PreparedStatement,
        named_params: Vec<RpcParameter>,
        orphaned: &mut Option<StatementId>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementResult> {
        if self.command_is_busy() {
            return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
        }

        RpcParameter::reject_data_at_exec(named_params.iter())?;

        // Open the command boundary before recovery so a transparent reconnect's
        // login info messages land in this command's buffer; the inner RPC skips
        // its own `begin_command` via `command_started`.
        self.begin_command();

        let mut opts = options.into();
        let reconnect_elapsed = self.check_and_reconnect(opts.timeout, opts.cancel).await?;
        let budget = Self::deduct_timeout(opts.timeout, reconnect_elapsed);
        opts.timeout = budget.into_timeout()?.seconds();

        // Reuse the statement's handle when the client still holds one; a
        // reconnect clears the map, so an id from a dead session re-prepares.
        match statement
            .id
            .filter(|id| self.prepared_handles.contains_key(id))
        {
            Some(statement_id) => {
                self.execute_sp_execute(statement_id, None, Some(named_params), true, opts)
                    .await
            }
            None => {
                // Reported by `sp_prepexec` whenever the server's prepare `@handle`
                // landed - including on a failed batch, where the plan still
                // exists and must stay releasable (Ex: prepare passed but execute failed).
                let mut issued_id = None;
                let result = self
                    .execute_sp_prepexec(
                        statement.sql.clone(),
                        named_params,
                        &mut issued_id,
                        orphaned,
                        true,
                        opts,
                    )
                    .await;
                if issued_id.is_some() {
                    statement.id = issued_id;
                }
                result
            }
        }
    }

    /// Executes parameter rows against one prepared statement in a single TDS
    /// RPC request.
    ///
    /// Rows are pulled from `rows` as each RPC is serialized, so callers can
    /// convert application buffers lazily without retaining the complete batch.
    /// The `usize` carried with each row is returned unchanged for result/status
    /// correlation.
    ///
    /// The method recovers once before preparing or sending, reuses one server
    /// handle for every row, and applies one timeout/cancellation budget to the
    /// complete operation. Data-at-execution and Always Encrypted parameters are
    /// rejected; callers must use the scalar execution path for those shapes.
    pub async fn execute_prepared_batch<'a, I>(
        &mut self,
        statement: &mut PreparedStatement,
        rows: I,
        orphaned: &mut Option<StatementId>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<PreparedBatchResult>
    where
        I: IntoIterator<Item = TdsResult<(usize, Vec<RpcParameter>)>>,
    {
        if self.command_is_busy() {
            return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
        }

        let mut rows = rows.into_iter().peekable();
        // A row that fails to build is skipped rather than aborting the batch,
        // so the parameter declaration comes from the first row that builds -
        // not from row 0. The caller's iterator has already recorded the ones
        // skipped here, so consuming them loses nothing.
        while matches!(rows.peek(), Some(Err(_))) {
            rows.next();
        }
        let Some(Ok((_, first_params))) = rows.peek() else {
            return Ok(PreparedBatchResult {
                rows: Vec::new(),
                complete: true,
            });
        };
        let declaration_params = first_params.clone();
        RpcParameter::reject_data_at_exec(declaration_params.iter())?;
        let mut opts = options.into();
        self.current_command_ce_setting = opts.column_encryption;
        if self.should_encrypt_parameters() {
            return Err(UsageError(
                "Batched prepared execution is not supported with Always Encrypted.".to_string(),
            ));
        }

        self.begin_command();
        let started = Instant::now();
        let reconnect_elapsed = self.check_and_reconnect(opts.timeout, opts.cancel).await?;
        let original_timeout = opts.timeout;
        let mut budget = Self::deduct_timeout(original_timeout, reconnect_elapsed);
        opts.timeout = budget.into_timeout()?.seconds();

        let live_id = statement
            .id
            .filter(|id| self.prepared_handles.contains_key(id));
        let statement_id = match live_id {
            Some(id) => id,
            None => {
                if let Some(orphan_id) = orphaned.take() {
                    self.execute_sp_unprepare(orphan_id, true, opts.clone())
                        .await?;
                    budget = Self::deduct_timeout(original_timeout, started.elapsed());
                    opts.timeout = budget.into_timeout()?.seconds();
                }

                let declaration_params = declaration_params
                    .iter()
                    .cloned()
                    .enumerate()
                    .map(|(index, mut parameter)| {
                        parameter.name = Some(format!("@P{}", index + 1));
                        parameter
                    })
                    .collect();
                let statement_id = self
                    .execute_sp_prepare(
                        statement.sql.clone(),
                        declaration_params,
                        true,
                        opts.clone(),
                    )
                    .await?;
                statement.id = Some(statement_id);
                budget = Self::deduct_timeout(original_timeout, started.elapsed());
                opts.timeout = budget.into_timeout()?.seconds();
                statement_id
            }
        };

        self.execute_sp_execute_batch(statement_id, rows, opts)
            .await
    }

    /// Streaming counterpart to [`execute_prepared`](Self::execute_prepared) for
    /// statements carrying [`RpcParameter::data_at_exec`] parameters.
    ///
    /// Data-at-execution does not change which procedure runs the statement: the
    /// streamed values are written into the same `sp_prepexec` / `sp_execute`
    /// RPC the statement would have used with materialized values, so a prepared
    /// statement stays prepared and keeps reusing its handle. This mirrors
    /// msodbcsql, which discovers data-at-execution while building the RPC and
    /// parks the half-written request rather than switching procedures.
    ///
    /// Routing matches [`execute_prepared`](Self::execute_prepared): a handle
    /// belonging to the live session is reused via `sp_execute`, otherwise the
    /// statement is prepared and executed in one round trip via `sp_prepexec`.
    /// With no streamed parameters this defers to
    /// [`execute_prepared`](Self::execute_prepared) and reports
    /// [`StreamedParamStatus::Complete`].
    ///
    /// On the `sp_prepexec` route `statement` receives its issued
    /// [`StatementId`] as soon as the request is parked, because the server's
    /// `@handle` trails the result set and is only captured during the drain —
    /// long after this returns. The id resolves through the client's handle map,
    /// so a sequence that never reaches the server (a
    /// [`cancel_streamed_write`](Self::cancel_streamed_write), a mid-stream
    /// failure) leaves it inert and the next execute re-prepares.
    ///
    /// Unlike [`execute_prepared`](Self::execute_prepared), `orphaned` is never
    /// consumed here: its drop is not piggybacked onto the `@handle` argument.
    /// The request stays open for the whole application-driven chunk sequence
    /// and may be discarded server-side, which would evict the orphan from the
    /// client's map while the server still held the plan. The caller keeps it
    /// and releases it with [`unprepare`](Self::unprepare).
    ///
    /// # Errors
    /// Returns a usage error for invalid streamed parameters, for an already
    /// executing command, or when Always Encrypted is active for this command,
    /// plus transport/serialization errors from the parked request.
    pub async fn begin_execute_prepared<'a>(
        &mut self,
        statement: &mut PreparedStatement,
        named_params: Vec<RpcParameter>,
        orphaned: &mut Option<StatementId>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StreamedParamStatus> {
        if self.command_is_busy() {
            return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
        }

        let opts = options.into();
        self.current_command_ce_setting = opts.column_encryption;
        self.ensure_force_column_encryption_supported(named_params.iter())?;

        let (streamed_params, materialized_params) =
            Self::split_and_validate_streamed_params(named_params)?;

        if streamed_params.is_empty() {
            let result = self
                .execute_prepared(statement, materialized_params, orphaned, opts)
                .await?;
            return Ok(StreamedParamStatus::Complete(result));
        }

        if self.should_encrypt_parameters() {
            return Err(UsageError(
                "Streamed PLP parameter writes are not supported with Always Encrypted."
                    .to_string(),
            ));
        }

        let (timeout_sec, _request_timeout, database_collation) =
            self.prepare_rpc_command(opts.timeout, opts.cancel).await?;

        // Reuse the statement's handle when the client still holds one; a
        // reconnect clears the map, so an id from a dead session re-prepares.
        let live_handle = statement
            .id
            .and_then(|id| self.prepared_handles.get(&id).copied());

        let (rpc, issued_id) = match live_handle {
            Some(handle) => {
                // `sp_execute` carries the handle plus the parameter values; the
                // prepared plan already declares their types, so there is no
                // `@params` string the streamed entries have to appear in.
                let handle_parameter =
                    RpcParameter::new(None, StatusFlags::NONE, SqlType::Int(Some(handle)));
                let rpc = SqlRpc::new(
                    RpcType::ProcId(RpcProcs::Execute),
                    Some(vec![handle_parameter]),
                    Some(materialized_params),
                    &database_collation,
                    &self.execution_context,
                );
                (rpc, None)
            }
            None => {
                // The `@params` declaration covers the streamed parameters too,
                // even though their values arrive later.
                let mut declaration_params = materialized_params.clone();
                declaration_params.extend(streamed_params.iter().cloned());
                let mut params_list_as_string = String::new();
                build_parameter_list_string(&declaration_params, &mut params_list_as_string)?;

                let statement_parameter = RpcParameter::new(
                    None,
                    StatusFlags::NONE,
                    SqlType::NVarcharMax(Some(SqlString::from_utf8_string(statement.sql.clone()))),
                );
                let params_parameter = RpcParameter::new(
                    None,
                    StatusFlags::NONE,
                    SqlType::NVarcharMax(Some(SqlString::from_utf8_string(params_list_as_string))),
                );
                // NULL by-reference `@handle`: prepare fresh, with no piggybacked
                // drop — see this method's docs on `orphaned`.
                let handle_parameter =
                    RpcParameter::new(None, StatusFlags::BY_REF_VALUE, SqlType::Int(None));

                let rpc = SqlRpc::new(
                    RpcType::ProcId(RpcProcs::PrepExec),
                    Some(vec![
                        handle_parameter,
                        params_parameter,
                        statement_parameter,
                    ]),
                    Some(materialized_params),
                    &database_collation,
                    &self.execution_context,
                );

                // Armed after the RPC is built, so a build failure cannot leave a
                // stale target: the `@handle` RETURNVALUE trailing the result set
                // is recorded under this id during the drain.
                self.pending_prepared_param_encryption = None;
                let issued_id = self.issue_statement_id();
                self.pending_capture = Some(issued_id);
                (rpc, Some(issued_id))
            }
        };

        // A serialization failure in here aborts the streamed write, which also
        // disarms the capture armed above.
        let status = self
            .start_streamed_rpc(
                rpc,
                streamed_params,
                timeout_sec,
                opts.cancel,
                database_collation,
            )
            .await?;

        if let Some(issued_id) = issued_id {
            statement.id = Some(issued_id);
        }
        Ok(status)
    }

    /// Issues the next unique [`StatementId`] for a managed prepared statement.
    fn issue_statement_id(&mut self) -> StatementId {
        let id = StatementId(self.next_statement_id);
        // Exhausting u64 (~1.8e19 prepares on one connection) is unreachable, so
        // wrap rather than branch; the insert-site debug_assert catches the
        // impossible id-0 collision in tests.
        self.next_statement_id = self.next_statement_id.wrapping_add(1);
        id
    }

    /// Releases a managed prepared statement's server handle via `sp_unprepare`.
    ///
    /// Recovers a dead connection first (charging the elapsed time against the
    /// command budget), then releases the handle only if the client still holds
    /// one for `statement_id` in the live session. A statement whose handle is
    /// absent — never materialized, or dropped when a reconnect cleared the map —
    /// is already gone server-side, so it is skipped with no RPC. This mirrors
    /// msodbcsql's `DropPrepHandle`, which recovers via `GetBatchCtxOrRecover`
    /// and sends `sp_unprepare` only when the statement's connection id still
    /// matches the recovered connection. Take the id with
    /// [`PreparedStatement::take_id`] once the statement is done.
    pub async fn unprepare<'a>(
        &mut self,
        statement_id: StatementId,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<()> {
        if self.command_is_busy() {
            return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
        }

        // Open the command boundary before recovery so a transparent reconnect's
        // login info messages land in this command's buffer; the inner RPC skips
        // its own `begin_command` via `command_started`.
        self.begin_command();

        let mut opts = options.into();
        let reconnect_elapsed = self.check_and_reconnect(opts.timeout, opts.cancel).await?;
        let budget = Self::deduct_timeout(opts.timeout, reconnect_elapsed);
        // Absent handle (never materialized, or a reconnect cleared the map):
        // already gone server-side, skip with no RPC — including the timeout
        // check below, since releasing nothing cannot time out.
        if !self.prepared_handles.contains_key(&statement_id) {
            return Ok(());
        }
        opts.timeout = budget.into_timeout()?.seconds();
        self.execute_sp_unprepare(statement_id, true, opts).await
    }

    /// Prepares and executes a parameterized statement in a single round-trip
    /// via `sp_prepexec`, combining
    /// [`execute_sp_prepare()`](Self::execute_sp_prepare) and
    /// [`execute_sp_execute()`](Self::execute_sp_execute).
    ///
    /// The `@handle` RETURNVALUE trails the result set, so it is captured during
    /// the push_return_values and recorded under the issued [`StatementId`]; the statement
    /// becomes reusable via `sp_execute` once drained. Rows are read with
    /// [`read_row()`](Self::read_row).
    ///
    /// A low-level wire call - prefer the managed
    /// [`execute_prepared`](Self::execute_prepared) /
    /// [`unprepare`](Self::unprepare) API.
    ///
    /// # Parameters
    ///
    /// - `named_params` - the statement's parameters. Unlike `sp_prepare`,
    ///   their values are sent and executed, not just declared.
    ///
    /// - `statement_id` - **out**: the id this call issues. Set whenever the
    ///   server allocated a plan, which is not the same as "the batch
    ///   succeeded":
    ///   - success - always set (the `@handle` may still be in flight);
    ///   - error *with* a `@handle` (e.g. Prepare passed but execute failed)
    ///     - set, so the caller can reuse or [`unprepare`](Self::unprepare) it;
    ///   - error *without* one (compile failure, or the stream broke first) -
    ///     left untouched, leaving the statement unmaterialized.
    ///
    /// - `orphan` - **in/out**: a statement whose prepared handle is to be
    ///   released, piggybacked onto this prepexec.
    ///   `Some(id)` sends its handle as the by-reference `@handle`
    ///   input so the server drops that plan while preparing the new one,
    ///   saving a separate `sp_unprepare` round trip; `None`, or an id with
    ///   no live handle, sends NULL and prepares fresh. On return it reports
    ///   ownership: still `Some` if the call failed before serialization (the
    ///   caller may retry the release), `None` once the drop crossed that
    ///   boundary - past which the server may have consumed it even if the call
    ///   then fails after the dropping of orphan.
    ///
    /// - `command_started` - `true` when the caller already opened the command
    ///   boundary via `begin_command` (as
    ///   [`execute_prepared`](Self::execute_prepared) does before recovering, so
    ///   the reconnect's info messages survive); `false` opens it here.
    ///
    /// Both handle decisions match msodbcsql, which keys them on whether it
    /// holds a handle rather than on the batch's return code.
    ///
    /// # Recovery
    ///
    /// Never reconnects - the caller recovers once up front, as
    /// [`execute_prepared`](Self::execute_prepared) does. Staleness needs no
    /// caller check: a reconnect clears `prepared_handles`, so an `orphan` from
    /// the dead session resolves to no handle and its drop is skipped.
    #[instrument(skip(self, named_params, options), level = "info")]
    async fn execute_sp_prepexec<'a>(
        &mut self,
        sql: String,
        mut named_params: Vec<RpcParameter>,
        statement_id: &mut Option<StatementId>,
        orphan: &mut Option<StatementId>,
        command_started: bool,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementResult> {
        if !command_started {
            if self.command_is_busy() {
                return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
            }
            self.begin_command();
        }
        // No reconnect here — recovery is caller-owned (see this method's
        // `# Recovery` docs).

        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            column_encryption,
        } = options.into();
        self.current_command_ce_setting = column_encryption;

        // Store timeout and cancel handle for this operation
        let budget = Self::deduct_timeout(timeout_sec, Duration::ZERO);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        let request_timeout = resolved.duration();
        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());

        self.transport.reset_reader();

        let database_collation = self.negotiated_settings.database_collation;

        let sql_statement_value =
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(sql.clone())));

        // The capture target is armed just before the send below so a failure
        // while building the RPC cannot leave it set.
        self.pending_prepared_param_encryption = None;
        self.pending_capture = None;

        // Create the parameter list for sp_prepexec
        let statement_parameter = RpcParameter::new(None, StatusFlags::NONE, sql_statement_value);

        // Build the comma separated list of parameters
        let mut params_list_as_string = String::new();

        build_parameter_list_string(&named_params, &mut params_list_as_string)?;

        // Always Encrypted: sp_prepexec prepares and executes in one round-trip,
        // so — like sp_executesql — it runs `sp_describe_parameter_encryption`
        // against the statement and encrypts flagged parameters in place before
        // sending the real RPC. The `@params` declaration keeps each parameter's
        // original type; only the value is replaced with ciphertext plus cipher
        // metadata.
        self.ensure_force_column_encryption_supported(named_params.iter())?;
        if self.should_encrypt_parameters() && !named_params.is_empty() {
            self.pending_prepared_param_encryption = Some(
                self.encrypt_parameters(
                    &sql,
                    &params_list_as_string,
                    &mut named_params,
                    timeout_sec,
                    cancel_handle,
                )
                .await?,
            );
            // The describe round-trip closes its own batch and clears the
            // per-operation timeout/cancel state; restore it for the real RPC.
            self.remaining_request_timeout = request_timeout;
            self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());
            self.transport.reset_reader();
        }

        let params_as_sql_string =
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(params_list_as_string)));

        let params_parameter = RpcParameter::new(None, StatusFlags::NONE, params_as_sql_string);

        // The by-reference `@handle`: NULL input prepares fresh; a `Some(h)`
        // input tells the server to drop prepared statement `h` before
        // preparing. The new handle comes back as the `@handle` RETURNVALUE captured during drain.
        // From this point onward, serialization or response failures are
        // ambiguous: the server may have consumed the piggybacked drop, so the
        // orphan is released and its entries evicted either way.
        let drop_handle = orphan.take().and_then(|orphan_id| {
            self.prepared_param_encryption.remove(&orphan_id);
            self.prepared_handles.remove(&orphan_id)
        });
        let handle_value = SqlType::Int(drop_handle);

        let handle_parameter = RpcParameter::new(None, StatusFlags::BY_REF_VALUE, handle_value);

        // Create the parameter list for positional parameters of sp_prepexec.
        let positional_parameters_list =
            vec![handle_parameter, params_parameter, statement_parameter];
        let positional_parameters = Some(positional_parameters_list);

        // Build the RPC request.
        let rpc = SqlRpc::new(
            RpcType::ProcId(RpcProcs::PrepExec),
            positional_parameters,
            Some(named_params),
            &database_collation,
            &self.execution_context,
        );

        // Armed here, not earlier: the AE describe round-trip above emits its own
        // RETURNVALUEs, and a build failure must not leave a stale target.
        let issued_id = self.issue_statement_id();
        self.pending_capture = Some(issued_id);

        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = rpc.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        drop(rpc);
        if let Err(e) = self.finish_send(serialize_result, message).await {
            self.report_issued_id(issued_id, statement_id);
            return Err(e);
        }

        let boundary = match self.advance_to_result_boundary().await {
            Ok(boundary) => boundary,
            Err(e) => {
                self.abort_pending_prepare_capture();
                self.report_issued_id(issued_id, statement_id);
                return Err(e);
            }
        };
        // The handle may still be in flight (it follows the result set), so the id
        // is always reported here.
        *statement_id = Some(issued_id);
        Ok(self.apply_result_boundary(boundary))
    }

    /// Reports `issued_id` to the caller only if the server's `@handle` actually
    /// arrived.
    ///
    /// Call this after aborting the capture, so no later token can land: the map
    /// lookup is then a final answer to "did we get a prepared plan?". Reporting an id
    /// with no handle behind it would leave the statement claiming to be
    /// prepared when nothing was.
    fn report_issued_id(&self, issued_id: StatementId, out: &mut Option<StatementId>) {
        if self.prepared_handles.contains_key(&issued_id) {
            *out = Some(issued_id);
        }
    }

    /// Executes a previously prepared statement by handle via `sp_execute`.
    ///
    /// Re-uses the execution plan from an earlier
    /// [`execute_sp_prepare()`](Self::execute_sp_prepare) or
    /// [`execute_sp_prepexec()`](Self::execute_sp_prepexec) call.
    /// Supply fresh parameter values through `positional_parameters` and/or
    /// `named_parameters`.
    ///
    /// # Recovery
    ///
    /// This method never reconnects; callers that need it recover once with
    /// [`check_and_reconnect`](Self::check_and_reconnect) first, as
    /// [`execute_prepared`](Self::execute_prepared) does. Staleness needs no
    /// caller check: a reconnect clears `prepared_handles`, so `statement_id`
    /// either resolves to a handle belonging to the live session or the call
    /// fails before reaching the wire.
    /// A low-level wire call with caller-owned recovery — prefer the
    /// managed [`execute_prepared`](Self::execute_prepared) / [`unprepare`](Self::unprepare) API.
    ///
    /// `command_started`: `true` when the caller already opened the command
    /// boundary via `begin_command` (as `execute_prepared` does before recovery,
    /// so the reconnect's info messages survive); `false` opens it here. It does
    /// not affect recovery — this method never reconnects.
    #[instrument(
        skip(self, positional_parameters, named_parameters, options),
        level = "info"
    )]
    async fn execute_sp_execute<'a>(
        &mut self,
        statement_id: StatementId,
        mut positional_parameters: Option<Vec<RpcParameter>>,
        mut named_parameters: Option<Vec<RpcParameter>>,
        command_started: bool,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementResult> {
        let Some(handle) = self.prepared_handles.get(&statement_id).copied() else {
            return Err(UsageError(
                "Cannot execute. Given prepared statement is not materialized on this connection"
                    .to_string(),
            ));
        };
        if !command_started {
            if self.command_is_busy() {
                return Err(UsageError(ALREADY_EXECUTING_ERROR.to_string()));
            }
            self.begin_command();
        }
        // No reconnect here — recovery is caller-owned (see this method's
        // `# Recovery` docs).

        let ExecuteOptions {
            timeout: timeout_sec,
            cancel: cancel_handle,
            column_encryption,
        } = options.into();
        self.current_command_ce_setting = column_encryption;

        // Store timeout and cancel handle for this operation
        let budget = Self::deduct_timeout(timeout_sec, Duration::ZERO);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        let request_timeout = resolved.duration();
        self.remaining_request_timeout = request_timeout;
        self.cancel_handle = cancel_handle.map(|handle| handle.child_handle());

        self.transport.reset_reader();

        // Always Encrypted: encrypt the supplied parameter values in place using
        // the metadata captured when the statement was prepared, then send the
        // real RPC. sp_execute never describes — the metadata must already have
        // been cached by execute_sp_prepare on this connection.
        self.ensure_force_column_encryption_supported(
            positional_parameters
                .iter()
                .flatten()
                .chain(named_parameters.iter().flatten()),
        )?;
        if self.should_encrypt_parameters()
            && (positional_parameters
                .as_ref()
                .is_some_and(|p| !p.is_empty())
                || named_parameters.as_ref().is_some_and(|p| !p.is_empty()))
        {
            let (providers, cek_cache, trusted_key_paths) = self.cloned_ce_key_material()?;
            let describe = self
                .prepared_param_encryption
                .get(&statement_id)
                .cloned()
                .ok_or_else(|| {
                    crate::error::Error::ColumnEncryptionError(format!(
                        "Prepared statement handle {handle} has no Always Encrypted parameter \
                         metadata; prepare it with execute_sp_prepare on this connection before \
                         executing with parameters"
                    ))
                })?;
            // Encrypt positional and named parameters together in one pass so a
            // describe entry that lives in the other list is not misreported as
            // "not supplied".
            let mut param_refs: Vec<&mut RpcParameter> = Vec::new();
            if let Some(params) = positional_parameters.as_mut() {
                param_refs.extend(params.iter_mut());
            }
            if let Some(params) = named_parameters.as_mut() {
                param_refs.extend(params.iter_mut());
            }
            Self::apply_parameter_encryption(
                &describe,
                &providers,
                &cek_cache,
                &mut param_refs,
                &mut self.output_param_ceks,
                &trusted_key_paths,
            )
            .await?;
        }

        let database_collation = self.negotiated_settings.database_collation;

        let handle_value = SqlType::Int(Some(handle));
        let handle_parameter = RpcParameter::new(None, StatusFlags::NONE, handle_value);

        // Create the parameter list for positional parameters of sp_execute.
        let mut all_positional_parameters = vec![handle_parameter];

        if let Some(mut params) = positional_parameters {
            all_positional_parameters.append(&mut params);
        }
        let all_positional_parameters = Some(all_positional_parameters);

        // Build the RPC request.
        let rpc = SqlRpc::new(
            RpcType::ProcId(RpcProcs::Execute),
            all_positional_parameters,
            named_parameters,
            &database_collation,
            &self.execution_context,
        );

        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = rpc.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        drop(rpc);
        self.finish_send(serialize_result, message).await?;

        self.position_on_first_result().await
    }

    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub async fn execute_sp_prepare_for_test<'a>(
        &mut self,
        sql: String,
        named_params: Vec<RpcParameter>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementId> {
        self.execute_sp_prepare(sql, named_params, false, options)
            .await
    }

    /// Records `handle` under a fresh id without a round-trip, so wire-protocol
    /// tests can drive the sp_* RPCs with a handle the server never issued (or
    /// issued to a session that has since died).
    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub fn register_prepared_handle_for_test(&mut self, handle: i32) -> StatementId {
        let statement_id = self.issue_statement_id();
        self.prepared_handles.insert(statement_id, handle);
        statement_id
    }

    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub async fn execute_sp_unprepare_for_test<'a>(
        &mut self,
        statement_id: StatementId,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<()> {
        self.execute_sp_unprepare(statement_id, false, options)
            .await
    }

    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub async fn execute_sp_prepexec_for_test<'a>(
        &mut self,
        sql: String,
        named_params: Vec<RpcParameter>,
        orphan: &mut Option<StatementId>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<(StatementId, StatementResult)> {
        let mut issued_id = None;
        let result = self
            .execute_sp_prepexec(sql, named_params, &mut issued_id, orphan, false, options)
            .await?;
        Ok((
            issued_id.expect("a successful sp_prepexec always reports its id"),
            result,
        ))
    }

    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub async fn execute_sp_execute_for_test<'a>(
        &mut self,
        statement_id: StatementId,
        positional_parameters: Option<Vec<RpcParameter>>,
        named_parameters: Option<Vec<RpcParameter>>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<StatementResult> {
        self.execute_sp_execute(
            statement_id,
            positional_parameters,
            named_parameters,
            false,
            options,
        )
        .await
    }

    /// Collects a return value. While an `sp_prepexec` is in flight (an armed
    /// `pending_capture`) the `@handle` (RETURNVALUE ordinal 0) is diverted into
    /// the client's prepared handle map instead of being surfaced; every
    /// `Tokens::ReturnValue` funnels through here so capture works regardless of
    /// which drain path reads the stream. For every other RPC `pending_capture`
    /// is `None` and ordinal 0 is a genuine output parameter, so it falls
    /// through to `return_values`.
    fn push_return_value(&mut self, return_value: ReturnValue) {
        if let Some(statement_id) = self.pending_capture
            && return_value.param_ordinal == 0
            && let ColumnValues::Int(handle) = &return_value.value
        {
            // Route the handle into the client's map under the
            // statement's id and divert it from `return_values`. `execute_prepared`
            // arms `pending_capture` only when the id was absent from the map, so
            // this never overwrites a live handle.
            self.pending_capture = None;
            let previous = self.prepared_handles.insert(statement_id, *handle);
            debug_assert!(
                previous.is_none(),
                "prepared handle map overwrote a live entry for a reused StatementId"
            );
            if let Some(describe) = self.pending_prepared_param_encryption.take() {
                self.prepared_param_encryption
                    .insert(statement_id, describe);
            }
            return;
        }
        self.return_values.push(return_value);
    }

    #[instrument(skip(self), level = "info")]
    async fn drain_rows(&mut self) -> TdsResult<()> {
        if self.maybe_has_unread_rows() {
            // A pull cursor (`next_row_cursor`) may have left the current row
            // partially read (`RowPaused`/`PlpPaused`). The push API used below
            // rejects that state to avoid silently skipping a row the caller
            // still expects to see — but here we are intentionally discarding
            // the rest of the result set, so realign the stream past that parked
            // row first. `drain_active_row` is a no-op when nothing is parked.
            self.drain_active_row_if_needed().await?;
            // Drain the current result set.
            let mut writer = DiscardRowWriter;
            while self.next_row_into(&mut writer).await? {
                info!(
                    column_count = self
                        .current_metadata
                        .as_ref()
                        .map_or(0, |m| m.columns.len()),
                    "Consuming row while draining result set"
                );
            }
        }
        Ok(())
    }

    /// True when a drain failed because the transport went away, rather than
    /// because the token stream lost sync.
    ///
    /// The distinction decides the remedy, so the two must not be collapsed. A
    /// desynchronized stream is unrecoverable: the reader is parked at an
    /// unknown offset in a response that is otherwise fine, and nothing can
    /// resynchronize it. A socket that dropped mid-drain has no offset left to
    /// recover — there is nothing to read from — and that is exactly the case
    /// connection resiliency was built to handle transparently.
    fn drain_failure_lost_the_transport(error: &crate::error::Error) -> bool {
        matches!(
            error,
            crate::error::Error::Io(_)
                | crate::error::Error::ConnectionClosed(_)
                | crate::error::Error::ConnectionError(_)
                | crate::error::Error::TlsError(_)
                | crate::error::Error::TlsHandshakeError { .. }
        )
    }

    /// Retires the connection after a drain failed, picking the remedy that
    /// fits the cause.
    ///
    /// A timeout or cancellation returned after a successful ATTENTION is not a
    /// failed drain: the one-shot settlement marker proves DONE_ATTN was reached,
    /// so that interruption leaves the connection live.
    ///
    /// Both cases mark the transport dead, which is what a pool consults, so a
    /// pooled consumer discards the connection either way. They differ in
    /// whether session recovery stays armed:
    ///
    /// * **Stream desync** (protocol error, or an interruption with no successful
    ///   settlement) — recovery is disarmed. The socket may be perfectly healthy,
    ///   so leaving it armed would let the next command silently reconnect and
    ///   paper over a decoder bug instead of surfacing it.
    /// * **Transport loss** (I/O, TLS, connection closed) — recovery is left
    ///   armed. Disarming it would turn a network blip that resiliency handles
    ///   transparently into a hard failure, and these run on routine cursor
    ///   open/close/fetch paths, not just exceptional ones.
    ///
    /// See [`Self::drain_failure_lost_the_transport`] for the split.
    ///
    /// What this does not do: it does not close the socket, and no execute path
    /// consults `is_connection_dead`, so a caller reusing this `TdsClient`
    /// directly can still issue another command. That command is not left
    /// parked mid-value — entry points call `reset_reader`, which discards the
    /// client-side buffer — but stale bytes may remain queued in the kernel
    /// receive buffer. Closing the socket here is the wrong remedy:
    /// `close_transport` writes a TLS close_notify on a socket we just failed to
    /// read from, and its `?` returns before `self.stream = None`, so a
    /// swallowed error would leave the stream alive in exactly the degraded case
    /// retirement exists for. Dropping the stream with no I/O is the fix; it
    /// needs a new transport method and is left as follow-up.
    fn retire_after_failed_drain(&mut self, error: &crate::error::Error) {
        if self.take_settled_drain_interruption(error) {
            return;
        }
        self.transport.mark_known_dead();
        if !Self::drain_failure_lost_the_transport(error) {
            self.recovery_context.session_recovery_negotiated = false;
        }
    }

    /// Consumes the settlement evidence produced by the failing drain itself.
    ///
    /// A successful ATTENTION still returns the original timeout or cancellation,
    /// but DONE_ATTN proves the stream is synchronized and must not be retired.
    fn take_settled_drain_interruption(&mut self, error: &crate::error::Error) -> bool {
        let settled = std::mem::take(&mut self.interrupted_read_settled);
        settled
            && matches!(
                error,
                crate::error::Error::TimeoutError(_)
                    | crate::error::Error::OperationCancelledError(_)
            )
            && !self.transport.connection_known_dead()
    }

    /// Drains the stream, retiring the connection if the drain gives up partway.
    ///
    /// Call sites that would otherwise propagate a drain failure with a bare `?`
    /// use this instead, so the rule "a drain either reaches the terminal DONE
    /// or the connection is retired where it gave up" lives in one place rather
    /// than being re-derived at each site. A site added later that forgets the
    /// rule is then a missing call here, not a silent hole.
    ///
    /// The open-batch flag is cleared on failure for the same reason
    /// [`Self::close_query`] clears it: leaving it set masks the real error
    /// behind `ALREADY_EXECUTING_ERROR` on every later call, which is what made
    /// the original failure look like a permanent wedge.
    pub(in crate::connection) async fn drain_stream_or_retire(
        &mut self,
    ) -> TdsResult<Vec<SqlErrorInfo>> {
        match self.drain_stream().await {
            Ok(errors) => Ok(errors),
            Err(error) => {
                self.execution_context.set_has_open_batch(false);
                self.retire_after_failed_drain(&error);
                Err(error)
            }
        }
    }

    /// Drains all remaining tokens from the stream until a terminal DONE token.
    /// Collects any ERROR tokens encountered and returns them.
    ///
    /// A statement-scoped error (for example lock timeout 1222) does not abort
    /// the batch, so the server keeps streaming any result sets that follow it.
    /// A trailing row-returning result set must therefore be consumed through
    /// the row-decoding path: ROW/NBCROW tokens carry no length prefix and can
    /// only be parsed with the preceding COLMETADATA in the parser context.
    /// Skipping that step would leave unparsed row bytes in the transport and
    /// corrupt the connection for reuse.
    pub(in crate::connection) async fn drain_stream(&mut self) -> TdsResult<Vec<SqlErrorInfo>> {
        self.interrupted_read_settled = false;
        let mut collected_errors: Vec<SqlErrorInfo> = Vec::new();
        // A COLMETADATA reached at the top level of the drain must be parsed with
        // the same Always Encrypted awareness as advance_to_result_boundary: when
        // column encryption is negotiated the token carries a CEK-table prefix
        // (empty or not) before the first column, and reading it with
        // ParserContext::None would misinterpret those bytes and desynchronize the
        // stream — the very corruption this drain exists to prevent.
        let parser_context = ParserContext::ColumnEncryption(
            self.negotiated_settings.is_column_encryption_supported(),
        );
        loop {
            let token = self.next_response_token(&parser_context).await?;

            match token {
                Tokens::Done(done) | Tokens::DoneProc(done) | Tokens::DoneInProc(done) => {
                    info!(?done);
                    info!(?done.status);
                    if !done.has_more() {
                        if !collected_errors.is_empty() || done.has_error() {
                            self.abort_pending_prepare_capture();
                        }
                        break;
                    }
                }
                Tokens::ColMetadata(colmetadata) => {
                    // A row-returning result set began. Consume its rows via the
                    // row-decoding path; the trailing DONE tells us whether the
                    // batch continues.
                    let batch_ended = self
                        .drain_result_set_rows(Arc::new(colmetadata), &mut collected_errors)
                        .await?;
                    if batch_ended {
                        break;
                    }
                }
                other => self.apply_drain_side_effect(other, &mut collected_errors)?,
            }
        }
        Ok(collected_errors)
    }

    /// Consumes every ROW/NBCROW token of one result set (given its
    /// `metadata`), discarding the decoded values, and returns `true` when the
    /// result set's DONE token terminates the batch (no MORE flag).
    ///
    /// Rows are read with [`ColumnPolicy::SkipAll`] into a [`DiscardRowWriter`],
    /// so `receive_row_into` fully consumes each row — including PLP payloads —
    /// without materializing any column and never yields a pause result here.
    async fn drain_result_set_rows(
        &mut self,
        metadata: Arc<ColMetadataToken>,
        collected_errors: &mut Vec<SqlErrorInfo>,
    ) -> TdsResult<bool> {
        // Rows are skipped, so no cell decryptor is resolved: encrypted columns
        // are consumed as raw ciphertext bytes without decoding. Resolving a
        // decryptor here would add key-store round trips and decryption
        // failures — any of which returns `Err` and would mask the SQL error
        // that this drain exists to surface — and would overwrite
        // `self.current_decryptor` with a discarded set's metadata.
        let parser_context = ParserContext::ColumnMetadata(metadata, None);
        let mut discarded_rows: u64 = 0;
        loop {
            let start = Instant::now();
            let mut writer = DiscardRowWriter;
            let result = self
                .transport
                .receive_row_into(
                    &parser_context,
                    self.remaining_request_timeout,
                    self.cancel_handle.as_ref(),
                    ColumnPolicy::SkipAll,
                    &mut writer,
                )
                .await;
            self.update_remaining_timeout(start);
            let result = match result {
                Ok(result) => result,
                Err(error) => {
                    self.settle_interrupted_read(&error);
                    return Err(error);
                }
            };

            match result {
                RowReadResult::RowWritten => {
                    discarded_rows += 1;
                }
                RowReadResult::RowPaused(_) | RowReadResult::PlpPaused(_) => {
                    return Err(crate::error::Error::ProtocolError(
                        "Row read paused while draining a result set; the drain writer never requests a pause".to_string(),
                    ));
                }
                RowReadResult::Token(token) => match token {
                    Tokens::Done(done) | Tokens::DoneProc(done) | Tokens::DoneInProc(done) => {
                        info!(
                            ?done,
                            discarded_rows, "Draining DONE token ending result set"
                        );
                        return Ok(!done.has_more());
                    }
                    Tokens::ColMetadata(_) => {
                        return Err(crate::error::Error::ProtocolError(
                            "Unexpected COLMETADATA token before the previous result set's DONE while draining".to_string(),
                        ));
                    }
                    other => self.apply_drain_side_effect(other, collected_errors)?,
                },
            }
        }
    }

    /// Applies the side effects of a non-terminal control token seen while
    /// draining. DONE and COLMETADATA are handled by the callers because they
    /// steer the drain loop; everything else is either recorded or skipped.
    fn apply_drain_side_effect(
        &mut self,
        token: Tokens,
        collected_errors: &mut Vec<SqlErrorInfo>,
    ) -> TdsResult<()> {
        match token {
            Tokens::Error(error_token) => {
                info!(?error_token, "Draining ERROR token from stream");
                collected_errors.push(self.record_error_token(&error_token));
            }
            Tokens::Info(info_token) => {
                info!(?info_token, "Draining INFO token from stream");
                self.capture_info_message(&info_token);
            }
            Tokens::EnvChange(t1) => {
                if t1.sub_type == EnvChangeTokenSubType::ResetConnection {
                    self.on_reset_connection_ack();
                }
                self.execution_context
                    .capture_change_property(&t1, &mut self.negotiated_settings)?;
            }
            Tokens::SessionState(session_state) => {
                self.recovery_context
                    .process_session_state(&session_state)?;
            }
            Tokens::ReturnValue(return_value_token) => {
                let return_value = self.finalize_return_value(return_value_token)?;
                self.push_return_value(return_value);
            }
            Tokens::ReturnStatus(return_status) => {
                self.last_return_status = ReturnStatus::Received(return_status.value);
                info!(?return_status);
            }
            other => {
                info!(?other);
            }
        }
        Ok(())
    }

    /// Clears result-local state after ATTENTION handling finishes.
    ///
    /// Whether the transport reached DONE_ATTN or retired the connection, the
    /// cancelled result can no longer be resumed. Retaining its metadata,
    /// timeout, row cursor, or open-batch flag would expose stale state.
    fn normalize_after_attention(&mut self) {
        self.current_metadata = None;
        self.current_decryptor = None;
        self.buffered_row_support = None;
        self.count_map.clear();
        self.last_rows_affected = -1;
        self.dml_result_counts.clear();
        self.return_values.clear();
        self.output_param_ceks.clear();
        self.last_return_status = ReturnStatus::NotReceived;
        self.abort_pending_prepare_capture();
        self.remaining_request_timeout = None;
        self.cancel_handle = None;
        self.active_row_read_state = ActiveRowReadState::Idle;
        self.row_already_positioned = false;
        self.parked_token = None;
        self.current_result_set_has_been_read_till_end = true;
        self.current_result_ended_with_done_in_proc = false;
        self.current_command_ce_setting = ExecutionColumnEncryptionSetting::UseConnectionSetting;
        self.execution_context.set_has_open_batch(false);
    }

    /// Applies connection-level control tokens consumed by an ATTENTION drain.
    ///
    /// Result-local output and status are intentionally discarded: cancellation
    /// normalization clears them, and finalizing an encrypted return value could
    /// fail and retire a stream that already reached DONE_ATTN. The managed
    /// `sp_prepexec` handle is the exception: it is a plain integer needed to
    /// release the server-side prepared statement later.
    fn apply_attention_side_effect(&mut self, token: Tokens) -> TdsResult<()> {
        match token {
            Tokens::Error(error_token) => {
                let _ = self.record_error_token(&error_token);
            }
            Tokens::Info(info_token) => self.capture_info_message(&info_token),
            Tokens::EnvChange(env_change) => {
                if env_change.sub_type == EnvChangeTokenSubType::ResetConnection {
                    self.on_reset_connection_ack();
                }
                self.execution_context
                    .capture_change_property(&env_change, &mut self.negotiated_settings)?;
            }
            Tokens::SessionState(session_state) => {
                self.recovery_context
                    .process_session_state(&session_state)?;
            }
            Tokens::ReturnValue(return_value)
                if self.pending_capture.is_some()
                    && return_value.param_ordinal == 0
                    && return_value.column_metadata.crypto_metadata.is_none()
                    && matches!(&return_value.value, ColumnValues::Int(_)) =>
            {
                self.push_return_value(return_value.into());
            }
            _ => {}
        }
        Ok(())
    }

    /// Applies client-visible session state consumed by the transport's drain.
    ///
    /// The transport must read through DONE_ATTN to realign the wire, but
    /// `TdsClient` still owns transaction, environment, recovery, and reset
    /// acknowledgement state.
    fn apply_attention_settlement(
        &mut self,
        settlement: crate::connection::transport::network_transport::AttentionSettlement,
    ) -> bool {
        if settlement.overflowed {
            // Replaying only a prefix of ENVCHANGE/SESSIONSTATE could expose
            // client state that no longer matches the server. Fail closed even
            // though the wire itself reached DONE_ATTN.
            warn!(
                retained_tokens = settlement.retained_token_count(),
                "ATTENTION settlement state exceeded its retention limit"
            );
            self.transport.mark_known_dead();
            return false;
        }
        for token in settlement.tokens {
            if let Err(error) = self
                .observe_response_token(&token)
                .and_then(|_| self.apply_attention_side_effect(token))
            {
                warn!(?error, "Failed to apply state from the attention drain");
                self.retire_after_failed_drain(&error);
                return false;
            }
        }
        true
    }

    fn consume_attention_settlement(&mut self) -> bool {
        let Some(settlement) = self.transport.take_attention_settlement() else {
            return false;
        };
        self.apply_attention_settlement(settlement)
    }

    /// Finalizes client state after a read ended through cancellation or timeout.
    ///
    /// Every interruptible read surface calls this so settlement tokens are
    /// applied once and the cancelled result is discarded before reuse.
    fn settle_interrupted_read(&mut self, error: &crate::error::Error) {
        self.interrupted_read_settled = false;
        if !matches!(
            error,
            crate::error::Error::TimeoutError(_) | crate::error::Error::OperationCancelledError(_)
        ) {
            return;
        }

        let settlement_applied = self.consume_attention_settlement();
        self.normalize_after_attention();
        self.interrupted_read_settled =
            settlement_applied && !self.transport.connection_known_dead();
    }

    /// Reads tokens up to the next result boundary in the response stream.
    ///
    /// With `expose_norow_statements = false` (result-set navigation used by
    /// batch execution and the JS/Python consumers), a no-row statement's DONE
    /// token carrying the MORE flag is skipped so the method advances to the
    /// next COLMETADATA — consecutive no-row statements collapse into the
    /// following row-returning result set.
    ///
    /// With `true` (ODBC statement-wise navigation, matching msodbcsql), a
    /// no-row statement's DONE token can be its own result boundary, returned
    /// as [`ResultBoundaryKind::NoRows`] instead of always being skipped. It is
    /// surfaced only when the statement carries an update count (DONE `COUNT`
    /// on a non-`SQLSELECT` command) or produced an informational message
    /// (PRINT / low-severity RAISERROR);
    /// a pure no-op statement with neither — e.g. a bare `CREATE TABLE` — is
    /// still collapsed into the following result, exactly as in result-set
    /// navigation. This mirrors msodbcsql, which exposes a statement as its own
    /// result iff it returns rows, carries a count, or produced a message. A
    /// DONE reached in this method (without a COLMETADATA earlier in the same
    /// call) always belongs to a no-row statement, because a row-returning
    /// statement's DONE is consumed while its rows are read/drained.
    async fn advance_to_result_boundary(&mut self) -> TdsResult<ResultBoundaryKind> {
        // Tell the COLMETADATA parser whether Always Encrypted was negotiated so
        // it can parse the CEK table and per-column crypto metadata.
        let parser_context = ParserContext::ColumnEncryption(
            self.negotiated_settings.is_column_encryption_supported(),
        );
        let mut loop_count = 0u32;
        // Whether the statement whose DONE we are about to reach produced any
        // informational message. In statement-wise navigation, msodbcsql exposes
        // a statement as its own result when it returns rows, carries a row count
        // (DONE COUNT flag), or produced messages; pure DDL / no-op statements
        // with none of these are collapsed. Tracks messages since the last
        // boundary so a PRINT / low-severity RAISERROR is surfaced individually.
        let mut saw_message = false;

        loop {
            loop_count += 1;

            // Warn when approaching iteration limit to help diagnose issues
            if loop_count.is_multiple_of(1000) {
                debug!(
                    loop_count,
                    "High iteration count in advance_to_result_boundary"
                );
            }

            let token = self.next_response_token(&parser_context).await?;
            // `Tokens` moves into the match below; capture the one distinction
            // the shared DONE arm erases — only an RPC emits DONEINPROC, and
            // only there is the MORE flag ambiguous.
            let is_done_in_proc = matches!(token, Tokens::DoneInProc(_));
            match token {
                Tokens::ColMetadata(md) => {
                    info!(?md);
                    self.current_result_set_has_been_read_till_end = false;
                    self.current_result_ended_with_done_in_proc = false;
                    // Positioning on a row-returning result: its count is
                    // unavailable on a forward-only cursor. Clear any count
                    // captured from a preceding DONE-only (DML) result in the
                    // same batch so it is not misreported for this SELECT.
                    self.last_rows_affected = -1;
                    self.dml_result_counts.clear();
                    return Ok(ResultBoundaryKind::RowSet(Arc::new(md)));
                }
                Tokens::DoneInProc(done) | Tokens::DoneProc(done) | Tokens::Done(done) => {
                    info!(
                        ?done,
                        "Received Done token with has_more={}",
                        done.has_more()
                    );

                    if done.has_error() {
                        return Err(crate::error::Error::ProtocolError(
                            "Server reported error in DONE token without preceding ERROR token"
                                .to_string(),
                        ));
                    }

                    let count = self.count_map.entry(done.cur_cmd).or_insert(0);
                    // Use saturating_add to prevent integer overflow from malicious/corrupted TDS responses
                    *count = count.saturating_add(done.row_count);
                    self.current_result_set_has_been_read_till_end = true;
                    self.current_result_ended_with_done_in_proc = is_done_in_proc;

                    let is_last = !done.has_more();

                    // Capture update counts for `SQLRowCount`. DONE_COUNT on a
                    // SQLSELECT command is not an update-count result.
                    let has_count = done.status.contains(DoneStatus::COUNT);
                    // SQL Server compiles variable assignment (`DECLARE @x int = 1`,
                    // `SET @x = 1`, `SELECT @x = col FROM t`) as a SQLSELECT command
                    // and still sets DONE_COUNT. Neither reference driver exposes
                    // those as update-count results, so neither do we:
                    //   - msodbcsql: `Info != SQLSELECT` (sqlctokn.cpp:2150)
                    //   - .NET SqlClient: `if (curCmd != TdsEnums.SELECT)`
                    //     (TdsParser.cs `TryProcessDone`, "Skip the bogus DONE
                    //     counts sent by the server")
                    //
                    // msodbcsql additionally excludes SQLFETCHCURSOR (0x21) and
                    // SQLDBCC (0xe6) (sqlctokn.cpp:2151-2152); SqlClient does not,
                    // and does not even define those constants. We follow SqlClient
                    // because neither is observable here: no DBCC was found to set
                    // DONE_COUNT, and although `cursor_ops::cursor_fetch` does route
                    // `sp_cursorfetch` through `next_rowset` into this function, a
                    // live SQL Server 2022 tags that DONEINPROC
                    // `status: MORE|COUNT, cur_cmd: 0xc1` — SQLSELECT, already
                    // handled below. `last_rows_affected` measured -1 across block
                    // fetches with and without this guard. Add the variants only if
                    // a capture ever shows 0x21 or 0xe6 arriving with DONE_COUNT.
                    let has_update_count = has_count && done.cur_cmd != CurrentCommand::Select;
                    if has_update_count {
                        let count = i64::try_from(done.row_count).unwrap_or(i64::MAX);
                        self.last_rows_affected = count;
                        self.dml_result_counts.push(count);
                    }

                    // Statement-wise navigation (msodbcsql parity): this DONE is
                    // a navigable result only if the statement returned an update
                    // count or produced messages. Pure DDL / no-op
                    // statements (no count, no messages) are collapsed, exactly
                    // like result-set navigation, so a batch such as
                    // `CREATE; INSERT; SELECT` exposes the INSERT's row count and
                    // the SELECT, not the bare CREATE. `rows_affected` is
                    // `Some(n)` only for an update-count result.
                    if has_update_count || saw_message {
                        if !has_update_count {
                            // A message-only result carries no count. Clear any
                            // count captured from a preceding statement in the
                            // same batch so it is not re-reported as this
                            // result's `SQLRowCount` — msodbcsql reports -1
                            // here (verified for `UPDATE; PRINT`,
                            // `UPDATE; RAISERROR` and `UPDATE;` followed by a
                            // warning-raising assignment).
                            self.last_rows_affected = -1;
                        }
                        self.execution_context.set_has_open_batch(!is_last);
                        if !is_last && is_done_in_proc {
                            // The MORE flag may only be reporting the RPC's own
                            // trailing DONEPROC; find out before the caller
                            // treats it as another result.
                            self.settle_rpc_terminator(&parser_context).await?;
                            self.current_result_ended_with_done_in_proc = false;
                        }
                        return Ok(ResultBoundaryKind::NoRows {
                            rows_affected: if has_update_count {
                                Some(done.row_count)
                            } else {
                                None
                            },
                        });
                    }

                    if is_last {
                        // No more result sets - end of batch.
                        info!("No more result sets (has_more=false), ending batch");
                        self.execution_context.set_has_open_batch(false);
                        return Ok(ResultBoundaryKind::End);
                    }

                    // has_more() is true - there are more result sets coming.
                    // For no-row statements (PRINT / RAISERROR / DDL / DML) there
                    // is no ColMetadata; in result-set navigation (and for
                    // collapsed no-op statements above) we skip over their DONE
                    // token to find the next result set with ColMetadata (SELECT).
                    info!(
                        "More result sets available (has_more=true), continuing to look for ColMetadata"
                    );

                    // Prevent infinite loops from malicious inputs sending endless Done tokens with has_more=true
                    if loop_count > 10000 {
                        error!(
                            loop_count,
                            "Excessive iterations in advance_to_result_boundary - possible malicious input or protocol violation"
                        );
                        return Err(crate::error::Error::UsageError(
                            "Too many Done tokens with has_more=true without ColMetadata"
                                .to_string(),
                        ));
                    }
                    continue;
                }
                Tokens::EnvChange(env_change) => {
                    info!(?env_change);
                    if env_change.sub_type == EnvChangeTokenSubType::ResetConnection {
                        self.on_reset_connection_ack();
                    }
                    self.execution_context
                        .capture_change_property(&env_change, &mut self.negotiated_settings)?;
                }
                Tokens::SessionState(session_state) => {
                    self.recovery_context
                        .process_session_state(&session_state)?;
                }
                Tokens::ReturnValue(return_value_token) => {
                    let return_value = self.finalize_return_value(return_value_token)?;
                    self.push_return_value(return_value);
                }
                Tokens::ReturnStatus(return_status) => {
                    self.last_return_status = ReturnStatus::Received(return_status.value);
                    info!("Received return_status token: {:?}", return_status);
                    continue;
                }
                Tokens::Error(error_token) => {
                    info!(?error_token);
                    let mut all_errors = vec![self.record_error_token(&error_token)];
                    let drain_result = self.drain_stream().await;
                    // Reset batch state before propagating: the error terminates
                    // the batch regardless of whether the drain fully consumed
                    // it, so a subsequent `next_row` / `advance` must not pass
                    // the `maybe_has_unread_rows` guard and read a stream we have
                    // given up on (mirrors `handle_row_read_token`).
                    self.execution_context.set_has_open_batch(false);
                    self.current_result_set_has_been_read_till_end = true;
                    self.current_metadata = None;
                    match drain_result {
                        Ok(mut drain_errors) => all_errors.append(&mut drain_errors),
                        Err(e) => {
                            warn!(error = ?e, "Drain after statement error failed; retiring the connection");
                            // The SQL error still surfaces to the caller, but the
                            // stream is now desynchronized. Without this the error
                            // returns as `SqlServerError`, which callers treat as a
                            // healthy connection reporting a failed statement.
                            self.retire_after_failed_drain(&e);
                        }
                    }
                    return Err(crate::error::Error::from_sql_errors(all_errors));
                }
                Tokens::Info(info_token) => {
                    info!(?info_token);
                    self.capture_info_message(&info_token);
                    // Marks the current statement as message-bearing so
                    // statement-wise navigation surfaces it as its own result.
                    saw_message = true;
                    continue;
                }
                Tokens::TabName | Tokens::ColInfo => {
                    continue;
                }
                _ => {
                    info!("advance_to_result_boundary: {:?}", token);
                    return Err(UsageError(format!(
                        "Unexpected token while moving to next result boundary: {token:?}"
                    )));
                }
            }
        }
    }

    /// Positions on the next **row-returning** result set, collapsing (skipping)
    /// any no-row statements, and returns its column metadata — or `None` at end
    /// of batch. Internal helper for paths that only consume row sets (e.g.
    /// reading the result sets of `sp_describe_parameter_encryption`).
    #[instrument(skip(self), level = "debug", name = "next_rowset")]
    pub(crate) async fn next_rowset(&mut self) -> TdsResult<Option<Arc<ColMetadataToken>>> {
        loop {
            match self.advance_to_result_boundary().await? {
                ResultBoundaryKind::RowSet(md) => return Ok(Some(md)),
                // A no-row statement can also be the *last* thing in the
                // response — a terminal DONE with a count, or an RPC whose
                // terminator the look-ahead already consumed. Reading on would
                // block on a token that is never coming, so honour the same
                // guard `advance` applies.
                ResultBoundaryKind::NoRows { .. } => {
                    if !self.execution_context.has_open_batch() {
                        return Ok(None);
                    }
                }
                ResultBoundaryKind::End => return Ok(None),
            }
        }
    }

    /// Applies a [`ResultBoundaryKind`] to the client's current-result state and
    /// maps it to the public [`StatementResult`] returned by
    /// [`execute`](Self::execute) and [`advance`](Self::advance).
    fn apply_result_boundary(&mut self, boundary: ResultBoundaryKind) -> StatementResult {
        match boundary {
            ResultBoundaryKind::RowSet(md) => {
                self.current_metadata = Some(md);
                self.execution_context.set_has_open_batch(true);
                self.current_result_set_has_been_read_till_end = false;
                self.current_result_ended_with_done_in_proc = false;
                StatementResult::Rows
            }
            ResultBoundaryKind::NoRows { rows_affected } => {
                // A no-row statement has zero columns; `has_open_batch` was set
                // by `advance_to_result_boundary` based on the DONE MORE flag.
                self.current_metadata = None;
                StatementResult::NoRows { rows_affected }
            }
            ResultBoundaryKind::End => {
                self.current_metadata = None;
                self.execution_context.set_has_open_batch(false);
                self.current_result_set_has_been_read_till_end = true;
                StatementResult::End
            }
        }
    }

    /// Returns `true` while the current batch still has unconsumed results (a
    /// positioned result set, or further statements to navigate to).
    /// Used by the ODBC layer to decide whether the connection stays busy after
    /// positioning on a no-row statement result.
    ///
    /// A token parked by the RPC-terminator look-ahead is covered without being
    /// inspected here: parking means the terminal DONEPROC was not reached, so
    /// the flag this reads is still set.
    pub fn has_open_batch(&self) -> bool {
        self.execution_context.has_open_batch()
    }

    /// Reads the next response token, replaying one parked by the RPC-terminator
    /// look-ahead before touching the wire.
    ///
    /// A parked token was already timed and observed when it was first read, so
    /// it is replayed as-is; re-observing it would charge one token's evidence
    /// to the reset acknowledgement twice.
    async fn next_response_token(&mut self, parser_context: &ParserContext) -> TdsResult<Tokens> {
        if let Some(token) = self.parked_token.take() {
            return Ok(*token);
        }
        let start = Instant::now();
        let result = self
            .transport
            .receive_token(
                parser_context,
                self.remaining_request_timeout,
                self.cancel_handle.as_ref(),
            )
            .await;
        self.update_remaining_timeout(start);
        let token = match result {
            Ok(token) => token,
            Err(error) => {
                self.settle_interrupted_read(&error);
                return Err(error);
            }
        };
        self.observe_response_token(&token)?;
        Ok(token)
    }

    /// Resolves whether an RPC response has anything left after the no-row
    /// result just positioned on, closing the batch when it does not.
    ///
    /// Every `DONEINPROC` carries the MORE flag, because the RPC's own
    /// `DONEPROC` still follows it, so the flag alone cannot tell "another
    /// statement result is coming" from "that was the last one". Resolving that
    /// ambiguity here lets every caller distinguish an exhausted RPC from one
    /// with another result still available.
    ///
    /// Anything that is not the terminator is parked for the next read, so the
    /// look-ahead never consumes a result the caller has yet to navigate to.
    /// The response-tail control tokens that precede `DONEPROC` are absorbed
    /// exactly as the main loop absorbs them.
    ///
    /// Every error exit ends the batch, so no caller can propagate a tail
    /// failure over a batch nothing will finish reading.
    ///
    /// Unlike msodbcsql's short, non-failing single-byte peek, this consumes the
    /// trailer under the request's remaining timeout. An expiry therefore fails
    /// the request after the attention acknowledgement restores synchronization;
    /// the connection remains reusable.
    async fn settle_rpc_terminator(&mut self, parser_context: &ParserContext) -> TdsResult<()> {
        let mut processing_error = None;
        let mut loop_count = 0u32;
        loop {
            loop_count += 1;
            if loop_count > 10000 {
                let error = crate::error::Error::ProtocolError(
                    "Too many RPC trailer tokens without terminal DONEPROC".to_string(),
                );
                self.fail_rpc_terminator_look_ahead(&error);
                return Err(error);
            }

            let token = match self.next_response_token(parser_context).await {
                Ok(token) => token,
                Err(error) => {
                    self.fail_rpc_terminator_look_ahead(&error);
                    return Err(error);
                }
            };
            match token {
                Tokens::ReturnStatus(return_status) => {
                    self.last_return_status = ReturnStatus::Received(return_status.value);
                }
                Tokens::ReturnValue(return_value_token) => {
                    match self.finalize_return_value(return_value_token) {
                        Ok(return_value) => self.push_return_value(return_value),
                        Err(error) => {
                            processing_error.get_or_insert(error);
                        }
                    };
                }
                Tokens::EnvChange(env_change) => {
                    if env_change.sub_type == EnvChangeTokenSubType::ResetConnection {
                        self.on_reset_connection_ack();
                    }
                    if let Err(error) = self
                        .execution_context
                        .capture_change_property(&env_change, &mut self.negotiated_settings)
                    {
                        processing_error.get_or_insert(error);
                    }
                }
                Tokens::SessionState(session_state) => {
                    if let Err(error) = self.recovery_context.process_session_state(&session_state)
                    {
                        processing_error.get_or_insert(error);
                    }
                }
                Tokens::DoneProc(done) if !done.has_more() && !done.has_error() => {
                    self.remaining_request_timeout = None;
                    self.cancel_handle = None;
                    self.execution_context.set_has_open_batch(false);
                    return processing_error.map_or(Ok(()), Err);
                }
                other => {
                    self.parked_token = Some(Box::new(other));
                    return match processing_error {
                        None => Ok(()),
                        Some(error) => Err(self.abandon_after_tail_failure(error).await),
                    };
                }
            }
        }
    }

    /// Ends the batch after a tail token failed to process, keeping the rule
    /// "a tail failure always ends the batch" with the loop that breaks it.
    ///
    /// The look-ahead parked whatever it could not process, so the rest of the
    /// response is unread and nothing will come back for it. Leaving the batch
    /// open masks the returned error behind `ALREADY_EXECUTING_ERROR` on every
    /// later command for the whole connection.
    async fn abandon_after_tail_failure(
        &mut self,
        error: crate::error::Error,
    ) -> crate::error::Error {
        if self.execution_context.has_open_batch() {
            if let Err(drain_error) = self.drain_stream_or_retire().await {
                warn!(error = ?drain_error, "Drain after an RPC tail failure failed");
            }
            self.execution_context.set_has_open_batch(false);
        }
        error
    }

    fn fail_rpc_terminator_look_ahead(&mut self, error: &crate::error::Error) {
        self.execution_context.set_has_open_batch(false);
        self.remaining_request_timeout = None;
        self.cancel_handle = None;
        let attention_error = matches!(
            error,
            crate::error::Error::TimeoutError(_) | crate::error::Error::OperationCancelledError(_)
        );
        if attention_error && self.transport.connection_known_dead() {
            // ATTENTION did not restore a message boundary. Reconnecting would
            // hide failed cancellation cleanup, so do not recover this session.
            self.recovery_context.session_recovery_negotiated = false;
        } else if !attention_error {
            self.retire_after_failed_drain(error);
        }
    }

    /// Returns `true` when an open result batch or streamed write blocks a new command.
    pub(in crate::connection) fn command_is_busy(&self) -> bool {
        self.execution_context.has_open_batch()
            || !matches!(self.streamed_write_state, StreamedWriteState::Idle)
    }

    /// Returns `true` when the client is currently positioned on a row-returning
    /// result set (the last [`execute`](Self::execute) / [`advance`](Self::advance)
    /// returned [`StatementResult::Rows`]). Row-reading via the [`ResultSet`] API
    /// is only meaningful in this state.
    pub fn on_rows(&self) -> bool {
        self.current_metadata.is_some()
    }

    /// Positions on the first navigable result after a request has been sent to
    /// the wire. Shared tail of the `execute*` entry points.
    async fn position_on_first_result(&mut self) -> TdsResult<StatementResult> {
        let boundary = self.advance_to_result_boundary().await?;
        Ok(self.apply_result_boundary(boundary))
    }

    /// Advances to the next navigable result in the current batch, draining any
    /// unread rows of the current result set first. Returns
    /// [`StatementResult::End`] when the batch is exhausted.
    ///
    /// This is the lossless, statement-wise "next": each DML count, message-only
    /// statement, and row set is surfaced individually (matching msodbcsql's
    /// `SQLMoreResults`). Use [`advance_to_rows()`](Self::advance_to_rows) to
    /// skip straight to the next row-returning result set.
    #[instrument(skip(self), level = "info")]
    pub async fn advance(&mut self) -> TdsResult<StatementResult> {
        if !self.has_open_batch() {
            return Ok(StatementResult::End);
        }
        if self.maybe_has_unread_rows()
            && let Err(error) = self.drain_rows().await
        {
            self.abort_pending_prepare_capture();
            return Err(error);
        }
        // Draining the current result set may have consumed the batch's final
        // DONE token (has_more=false), which closes the batch. If so there is
        // nothing left on the wire to advance to; reading again would block
        // forever waiting for a token that never arrives.
        if !self.has_open_batch() {
            return Ok(StatementResult::End);
        }
        match self.position_on_first_result().await {
            Ok(result) => Ok(result),
            Err(error) => {
                self.abort_pending_prepare_capture();
                Err(error)
            }
        }
    }

    /// Advances to the next **row-returning** result set, collapsing (skipping)
    /// no-row statements (DML counts / message-only statements). Returns `true`
    /// when positioned on rows, or `false` at end of batch. This is the
    /// "give me the next rowset" convenience for consumers that don't care about
    /// per-statement counts — the equivalent of ADO.NET's `NextResult`.
    #[instrument(skip(self), level = "info")]
    pub async fn advance_to_rows(&mut self) -> TdsResult<bool> {
        loop {
            match self.advance().await? {
                StatementResult::Rows => return Ok(true),
                StatementResult::NoRows { .. } => continue,
                StatementResult::End => return Ok(false),
            }
        }
    }

    /// Settles the protocol-only tail after an exhausted RPC row set.
    ///
    /// SQL Server RPC responses can end a row set with `DONE_MORE`, then emit
    /// RETURNVALUE/RETURNSTATUS tokens and a terminal DONEPROC. For a
    /// `DONEINPROC`, [`settle_rpc_terminator`](Self::settle_rpc_terminator)
    /// consumes only that control-token tail and parks the first non-tail token
    /// for [`advance`](Self::advance). Plain batch DONE tokens are never probed.
    ///
    /// The `DONEINPROC` gate is msodbcsql's: `OnDone` probes the tail only for
    /// `RS_SELECTION && DONEINPROC && DONE_MORE` (`sqlctokn.cpp:2208-2240`).
    /// Widening it to every DONE would make an ordinary multi-statement batch
    /// block here on the next statement's result.
    ///
    /// Returns `true` only when the batch is fully exhausted.
    pub async fn complete_current_result(&mut self) -> TdsResult<bool> {
        if !self.current_result_set_has_been_read_till_end {
            return Ok(false);
        }
        if !self.execution_context.has_open_batch() {
            return Ok(true);
        }
        if !self.current_result_ended_with_done_in_proc {
            return Ok(false);
        }

        let parser_context = ParserContext::ColumnEncryption(
            self.negotiated_settings.is_column_encryption_supported(),
        );
        if let Err(error) = self.settle_rpc_terminator(&parser_context).await {
            self.current_metadata = None;
            self.abort_pending_prepare_capture();
            return Err(error);
        }
        Ok(!self.execution_context.has_open_batch())
    }

    /// This functions returns to the next row in the result set.
    /// If there are no more rows, it returns None.
    // Not instrumented: the span pushes ResultSet::next_row over the 4 KiB
    // hot-path future budget. Successful rows still emit `Row Received`.
    pub(crate) async fn get_next_row(&mut self) -> TdsResult<Option<Vec<ColumnValues>>> {
        let col_count = self
            .current_metadata
            .as_ref()
            .map(|m| m.columns.len())
            .unwrap_or(0);
        let mut writer = DefaultRowWriter::new(col_count);
        if self.next_row_into(&mut writer).await? {
            Ok(Some(writer.take_row()))
        } else {
            Ok(None)
        }
    }

    /// Returns `true` when transparent parameter encryption should be attempted:
    /// the connection requested Always Encrypted and the server acknowledged the
    /// feature during login.
    fn should_encrypt_parameters(&self) -> bool {
        self.negotiated_settings.is_column_encryption_supported()
            && self.effective_command_ce_setting() == ExecutionColumnEncryptionSetting::Enabled
    }

    /// Enforces the ForceColumnEncryption precondition: if any supplied parameter
    /// requires encryption but Always Encrypted is not enabled for this command,
    /// fail rather than sending it as plaintext. The per-parameter downgrade
    /// check (server reports the column plaintext) is enforced separately in
    /// [`apply_parameter_encryption`](Self::apply_parameter_encryption).
    fn ensure_force_column_encryption_supported<'p>(
        &self,
        params: impl IntoIterator<Item = &'p RpcParameter>,
    ) -> TdsResult<()> {
        if !self.should_encrypt_parameters()
            && params.into_iter().any(|p| p.force_column_encryption())
        {
            return Err(crate::error::Error::UsageError(
                "A parameter has ForceColumnEncryption set, but Always Encrypted is not enabled \
                 for this command; enable column encryption on the connection, or clear the flag."
                    .to_string(),
            ));
        }
        Ok(())
    }

    /// Returns `true` when the connection negotiated Always Encrypted and
    /// enabled column encryption, ignoring any per-command override. Used by
    /// paths that have no per-command setting (bulk copy, prepared statements).
    fn column_encryption_enabled_on_connection(&self) -> bool {
        use crate::connection::client_context::ColumnEncryptionSetting;

        self.negotiated_settings.is_column_encryption_supported()
            && self
                .recovery_context
                .client_context
                .as_ref()
                .map(|c| c.column_encryption_setting == ColumnEncryptionSetting::Enabled)
                .unwrap_or(false)
    }

    /// Returns `true` when bulk copy row values should be encrypted: the server
    /// acknowledged Always Encrypted during login and the connection enabled
    /// column encryption. Bulk copy has no per-command override, so this folds
    /// directly against the connection setting.
    fn should_encrypt_bulk_copy(&self) -> bool {
        self.column_encryption_enabled_on_connection()
    }

    /// Normalizes a parameter name for matching across
    /// `sp_describe_parameter_encryption` output and RETURNVALUE tokens: strips a
    /// single leading `@` and ASCII-uppercases it, mirroring T-SQL's
    /// case-insensitive identifier matching.
    fn normalize_param_name(name: &str) -> String {
        name.strip_prefix('@').unwrap_or(name).to_ascii_uppercase()
    }

    /// Converts a RETURNVALUE token into a [`ReturnValue`], decrypting the value
    /// when it is an encrypted Always Encrypted output parameter and result
    /// decryption is active for the current command.
    ///
    /// An encrypted output parameter arrives as ciphertext with `CryptoMetaData`
    /// but no CEK table; its CEK is the one resolved when the matching input
    /// parameter was encrypted (retained in `output_param_ceks`). Decryption only
    /// happens when the command's effective Column Encryption setting is
    /// `Enabled` — under a `Disabled` or `ResultSetOnly` setting the ciphertext is
    /// passed through unchanged, mirroring the result-column path and ensuring a
    /// stale CEK from an earlier command is never consulted. A plaintext parameter
    /// is returned unchanged. Returns an error if an encrypted output parameter
    /// has no retained CEK or did not arrive as varbinary ciphertext, rather than
    /// surfacing ciphertext to the caller.
    fn finalize_return_value(
        &self,
        token: crate::token::tokens::ReturnValueToken,
    ) -> TdsResult<ReturnValue> {
        // Only decrypt when the encrypted value carries crypto metadata and
        // result decryption is enabled for this command. Otherwise pass the value
        // through unchanged (plaintext, or ciphertext varbinary when encryption is
        // disabled), consistent with how encrypted result columns are decoded.
        let crypto = match token.column_metadata.crypto_metadata.as_ref() {
            Some(crypto)
                if self.effective_command_ce_setting()
                    == ExecutionColumnEncryptionSetting::Enabled =>
            {
                crypto
            }
            _ => return Ok(token.into()),
        };

        let cek = self
            .output_param_ceks
            .get(&Self::normalize_param_name(&token.param_name))
            .ok_or_else(|| {
                crate::error::Error::ColumnEncryptionError(format!(
                    "No column encryption key available to decrypt encrypted output parameter {}",
                    token.param_name
                ))
            })?;

        let decrypted = match &token.value {
            ColumnValues::Null => ColumnValues::Null,
            ColumnValues::Bytes(cipher) => {
                crate::security::encryption::decrypt_cell(crypto, cek.as_slice(), cipher)?
            }
            other => {
                return Err(crate::error::Error::ColumnEncryptionError(format!(
                    "Encrypted output parameter {} was expected to arrive as varbinary cipher \
                     bytes, but decoded as {other:?}",
                    token.param_name
                )));
            }
        };

        // Reuse the `From<ReturnValueToken>` conversion for the field mapping and
        // only override the decrypted value, so this stays in sync if
        // `ReturnValue` gains fields later.
        let mut return_value: ReturnValue = token.into();
        return_value.value = decrypted;
        Ok(return_value)
    }

    /// Resolves the effective Column Encryption setting for the current command,
    /// folding the per-command override against the connection setting.
    ///
    /// A command's [`ExecutionColumnEncryptionSetting::UseConnectionSetting`]
    /// maps to `Enabled` when the connection enabled Always Encrypted, otherwise
    /// `Disabled`. Explicit per-command values are returned as-is.
    fn effective_command_ce_setting(&self) -> ExecutionColumnEncryptionSetting {
        use crate::connection::client_context::ColumnEncryptionSetting;

        match self.current_command_ce_setting {
            ExecutionColumnEncryptionSetting::UseConnectionSetting => {
                let connection_enabled = self
                    .recovery_context
                    .client_context
                    .as_ref()
                    .map(|c| c.column_encryption_setting == ColumnEncryptionSetting::Enabled)
                    .unwrap_or(false);
                if connection_enabled {
                    ExecutionColumnEncryptionSetting::Enabled
                } else {
                    ExecutionColumnEncryptionSetting::Disabled
                }
            }
            other => other,
        }
    }

    /// Calls `sp_describe_parameter_encryption` for the given statement and
    /// parameter declaration, parsing the two result sets into a
    /// [`DescribeParameterEncryptionResult`](crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult).
    ///
    /// The first result set carries the CEK table (keyed by ordinal); the second
    /// describes, per parameter, whether and how it must be encrypted.
    async fn describe_parameter_encryption(
        &mut self,
        tsql: &str,
        params_decl: &str,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult>
    {
        use crate::security::describe_parameter_encryption::{
            DescribeParameterEncryptionResult, accumulate_cek_entry, parse_parameter_info,
        };

        // Count every actual describe round-trip so callers/tests can confirm the
        // query-metadata cache is eliding repeats.
        self.describe_round_trips = self.describe_round_trips.saturating_add(1);

        self.transport.reset_reader();
        let database_collation = self.negotiated_settings.database_collation;

        let tsql_param = RpcParameter::new(
            Some("@tsql".to_string()),
            StatusFlags::NONE,
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(tsql.to_string()))),
        );
        let params_param = RpcParameter::new(
            Some("@params".to_string()),
            StatusFlags::NONE,
            SqlType::NVarcharMax(Some(SqlString::from_utf8_string(params_decl.to_string()))),
        );

        let rpc = SqlRpc::new(
            RpcType::Named("sp_describe_parameter_encryption".to_string()),
            None,
            Some(vec![tsql_param, params_param]),
            &database_collation,
            &self.execution_context,
        );
        let mut packet_writer =
            rpc.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel_handle);
        let serialize_result = rpc.serialize(&mut packet_writer).await;
        let message = packet_writer.suspend();
        drop(rpc);
        self.finish_send(serialize_result, message).await?;

        let mut result = DescribeParameterEncryptionResult::new();

        // Result set 1: CEK table metadata.
        match self.next_rowset().await? {
            Some(metadata) => {
                self.current_metadata = Some(metadata);
                self.execution_context.set_has_open_batch(true);
                self.current_result_set_has_been_read_till_end = false;
            }
            None => {
                self.execution_context.set_has_open_batch(false);
                self.current_metadata = None;
                self.current_result_set_has_been_read_till_end = true;
                return Err(crate::error::Error::ColumnEncryptionError(
                    "sp_describe_parameter_encryption returned no result sets".to_string(),
                ));
            }
        }
        while let Some(row) = self.get_next_row().await? {
            accumulate_cek_entry(&mut result.cek_entries, &row)?;
        }

        // Result set 2: per-parameter encryption info.
        if self.advance_to_rows().await? {
            while let Some(row) = self.get_next_row().await? {
                result.parameters.push(parse_parameter_info(&row)?);
            }
        }

        self.close_query().await?;
        Ok(result)
    }

    /// Encrypts, in place, the parameters that `sp_describe_parameter_encryption`
    /// reports as requiring encryption: each flagged parameter's CEK is unwrapped
    /// through the registered key store providers, its plaintext value is
    /// normalized and encrypted, and the resulting ciphertext plus cipher
    /// metadata are stored on the [`RpcParameter`] for serialization.
    ///
    /// The describe result is served from (and populated into) the connection's
    /// query-metadata cache, so repeat executions of the same statement avoid the
    /// extra round-trip.
    async fn encrypt_parameters(
        &mut self,
        sql: &str,
        params_decl: &str,
        named_params: &mut [RpcParameter],
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<
        Arc<crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult>,
    > {
        let mut param_refs: Vec<&mut RpcParameter> = named_params.iter_mut().collect();
        self.encrypt_combined_parameters(
            sql,
            params_decl,
            &mut param_refs,
            timeout_sec,
            cancel_handle,
        )
        .await
    }

    /// Describes and encrypts, in place, a combined set of parameter references.
    ///
    /// This is the shared core behind [`encrypt_parameters`](Self::encrypt_parameters)
    /// (all-named) and the stored-procedure path (positional and/or named): the
    /// caller assembles one slice of mutable parameter references in the same
    /// order they were declared in `params_decl`, and
    /// [`apply_parameter_encryption`](Self::apply_parameter_encryption) matches
    /// each describe entry back by name (named) or ordinal (positional).
    async fn encrypt_combined_parameters(
        &mut self,
        sql: &str,
        params_decl: &str,
        params: &mut [&mut RpcParameter],
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<
        Arc<crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult>,
    > {
        // Mirror SqlClient: don't cache metadata for statements with output
        // parameters — the client can't validate cached describe results against
        // a RETURNVALUE — but still use it for this call.
        let has_output = params.iter().any(|p| p.is_output());
        let describe = self
            .describe_parameters_cached(sql, params_decl, has_output, timeout_sec, cancel_handle)
            .await?;

        let (providers, cek_cache, trusted_key_paths) = self.cloned_ce_key_material()?;
        Self::apply_parameter_encryption(
            &describe,
            &providers,
            &cek_cache,
            params,
            &mut self.output_param_ceks,
            &trusted_key_paths,
        )
        .await?;
        Ok(describe)
    }

    /// Returns the describe result for a statement, serving it from the
    /// connection's query-metadata cache when present and otherwise calling
    /// `sp_describe_parameter_encryption` and caching the result.
    ///
    /// When `skip_cache` is set (a statement with output parameters), the fresh
    /// describe result is returned but not stored, matching SqlClient.
    async fn describe_parameters_cached(
        &mut self,
        sql: &str,
        params_decl: &str,
        skip_cache: bool,
        timeout_sec: Option<u32>,
        cancel_handle: Option<&CancelHandle>,
    ) -> TdsResult<
        std::sync::Arc<
            crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult,
        >,
    > {
        use crate::security::query_metadata_cache::QueryMetadataCache;

        let key = QueryMetadataCache::key(&self.negotiated_settings.database, sql);
        if let Some(describe) = self.query_metadata_cache.get(&key) {
            return Ok(describe);
        }

        let describe = std::sync::Arc::new(
            self.describe_parameter_encryption(sql, params_decl, timeout_sec, cancel_handle)
                .await?,
        );
        if !skip_cache {
            self.query_metadata_cache
                .insert(key, std::sync::Arc::clone(&describe));
        }
        Ok(describe)
    }

    /// Number of `sp_describe_parameter_encryption` round-trips this connection
    /// has sent to the server (query-metadata cache misses). Useful for
    /// observability and for verifying the metadata cache is effective.
    pub fn describe_round_trips(&self) -> u64 {
        self.describe_round_trips
    }

    /// Clones the `Arc` handles to the column-master-key provider registry and
    /// the CEK cache from the client context, plus the trusted master key path
    /// allow-list for the connected server, so the parameter-encryption paths
    /// can pass them around without holding a borrow on `self`.
    fn cloned_ce_key_material(
        &self,
    ) -> TdsResult<(
        std::sync::Arc<crate::security::keystore::ColumnEncryptionKeyStoreProviderRegistry>,
        std::sync::Arc<crate::security::keystore::CekCache>,
        Vec<String>,
    )> {
        let client_context = self
            .recovery_context
            .client_context
            .as_ref()
            .ok_or_else(|| {
                crate::error::Error::ColumnEncryptionError(
                    "Cannot encrypt parameters without a client context".to_string(),
                )
            })?;
        Ok((
            client_context.column_encryption_key_store_providers.clone(),
            client_context.cek_cache.clone(),
            client_context
                .trusted_key_paths_for_current_server()
                .to_vec(),
        ))
    }

    /// Matches a `sp_describe_parameter_encryption` result entry to a supplied
    /// parameter: by name first (case-insensitively, like a T-SQL identifier),
    /// otherwise falling back to the *unnamed* parameter at the describe's
    /// 1-based ordinal (the positional case). Requiring the ordinal slot to be
    /// unnamed keeps a named parameter from being matched by position.
    fn match_describe_param_index(
        params: &[&mut RpcParameter],
        info: &crate::security::describe_parameter_encryption::ParameterEncryptionInfo,
    ) -> Option<usize> {
        params
            .iter()
            .position(|p| {
                p.name
                    .as_deref()
                    .map(|n| n.eq_ignore_ascii_case(&info.parameter_name))
                    .unwrap_or(false)
            })
            .or_else(|| {
                (info.parameter_ordinal as usize)
                    .checked_sub(1)
                    .filter(|&i| i < params.len() && params[i].name.is_none())
            })
    }

    /// Encrypts, in place, the parameters that a prior
    /// `sp_describe_parameter_encryption` call reported as requiring encryption.
    ///
    /// Each describe parameter is matched to a supplied parameter by name
    /// (case-insensitively, like a T-SQL identifier); if no name matches it falls
    /// back to the *unnamed* parameter at the describe's 1-based ordinal (the
    /// positional case used by `sp_execute`). Accepting one combined slice of
    /// mutable references lets a single call cover all-named, all-positional, and
    /// mixed positional/named parameter lists. Each flagged parameter's CEK is
    /// unwrapped through the key store providers, its value is normalized and
    /// encrypted, and the ciphertext plus cipher metadata are stored on the
    /// [`RpcParameter`] for serialization.
    async fn apply_parameter_encryption(
        describe: &crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult,
        providers: &crate::security::keystore::ColumnEncryptionKeyStoreProviderRegistry,
        cek_cache: &crate::security::keystore::CekCache,
        params: &mut [&mut RpcParameter],
        output_param_ceks: &mut HashMap<String, Arc<zeroize::Zeroizing<Vec<u8>>>>,
        trusted_key_paths: &[String],
    ) -> TdsResult<()> {
        use crate::message::parameters::rpc_parameters::RpcEncryptionMetadata;
        use crate::security::encryption::encrypt_parameter;
        use crate::security::keystore::decrypt_cek;

        // Reset the per-command retained CEKs before (re)populating them for this
        // command's parameters, so a previous command's keys cannot leak into
        // this one's output-parameter decryption.
        output_param_ceks.clear();

        // ForceColumnEncryption: every supplied parameter that demands
        // encryption must be reported as encrypted by the server. Validate before
        // any work — and before the "nothing encrypted" early return below — so a
        // server that downgrades a forced parameter is caught rather than
        // silently sending its value as plaintext. A downgrade takes two forms,
        // both rejected here: the server reports the parameter's target column as
        // plaintext, or it omits a row for the parameter entirely (which would
        // otherwise slip past a describe-driven check and be serialized in the
        // clear).
        //
        // This is a server-trust failure — the "compromised server downgrades to
        // harvest plaintext" threat this flag defends against — so it is a
        // `ColumnEncryptionError`, matching the "parameter not supplied" mismatch
        // below and the trusted-master-key-path rejection in `decrypt_cek`. It is
        // deliberately distinct from the caller-misconfiguration case (the flag
        // set while Always Encrypted is off) that
        // `ensure_force_column_encryption_supported` reports as a `UsageError`.
        for index in 0..params.len() {
            if !params[index].force_column_encryption() {
                continue;
            }
            let reported_encrypted = describe.parameters.iter().any(|info| {
                info.is_encrypted() && Self::match_describe_param_index(params, info) == Some(index)
            });
            if !reported_encrypted {
                let name = params[index]
                    .name
                    .as_deref()
                    .unwrap_or("<positional>")
                    .to_string();
                return Err(crate::error::Error::ColumnEncryptionError(format!(
                    "Parameter {name} has ForceColumnEncryption set, but the server did not \
                     report it as encrypted; refusing to send it as plaintext.",
                )));
            }
        }

        // Nothing to do when the server reports no encrypted parameters.
        if !describe.parameters.iter().any(|p| p.is_encrypted()) {
            return Ok(());
        }

        for info in &describe.parameters {
            if !info.is_encrypted() {
                continue;
            }

            let cek_entry = describe.cek_entry_for(info.cek_ordinal).ok_or_else(|| {
                crate::error::Error::ColumnEncryptionError(format!(
                    "sp_describe_parameter_encryption referenced unknown CEK ordinal {} for parameter {}",
                    info.cek_ordinal, info.parameter_name
                ))
            })?;

            let Some(index) = Self::match_describe_param_index(params, info) else {
                return Err(crate::error::Error::ColumnEncryptionError(format!(
                    "sp_describe_parameter_encryption returned encryption info for parameter {} \
                     that was not supplied to the call",
                    info.parameter_name
                )));
            };

            // An encrypted positional (unnamed) OUTPUT parameter cannot have its
            // returned value decrypted: the RETURNVALUE token arrives unnamed, so
            // its ciphertext can't be matched back to the CEK, which is retained
            // under the parameter's synthetic describe name (`@ce_pos_N`). Reject
            // it with an actionable error instead of returning ciphertext the
            // caller can't read. Named OUTPUT parameters are unaffected (the
            // RETURNVALUE name matches), as are non-encrypted positional OUTPUT
            // parameters (they never reach this encrypted-parameter branch).
            if params[index].is_output() && params[index].name.is_none() {
                return Err(crate::error::Error::UsageError(
                    "Encrypted positional OUTPUT stored-procedure parameters are not supported \
                     because their returned value cannot be matched back to a column encryption \
                     key; pass the output parameter by name so it can be decrypted on return."
                        .to_string(),
                ));
            }

            let plaintext_cek =
                decrypt_cek(providers, cek_cache, cek_entry, trusted_key_paths).await?;

            // An encrypted RETURNVALUE output parameter carries no CEK table and
            // reuses the CEK that encrypted the matching input parameter. Retain
            // it here, keyed by normalized name, so the RETURNVALUE decode path
            // can decrypt the returned value.
            output_param_ceks.insert(
                Self::normalize_param_name(&info.parameter_name),
                plaintext_cek.clone(),
            );

            let param = &mut *params[index];

            let ciphertext = encrypt_parameter(
                param.value()?,
                plaintext_cek.as_slice(),
                info.cipher_algorithm_id,
                info.encryption_type,
                info.normalization_rule_version,
            )?;

            param.set_encrypted(
                ciphertext,
                RpcEncryptionMetadata {
                    cipher_algorithm_id: info.cipher_algorithm_id,
                    encryption_type: info.encryption_type,
                    database_id: cek_entry.database_id,
                    cek_id: cek_entry.cek_id,
                    cek_version: cek_entry.cek_version,
                    cek_md_version: cek_entry.cek_md_version,
                    normalization_rule_version: info.normalization_rule_version,
                },
            );
        }
        Ok(())
    }

    /// Builds the `@tsql` and `@params` arguments for
    /// `sp_describe_parameter_encryption` when the original call is a stored
    /// procedure (rather than an `sp_executesql` statement).
    ///
    /// `@tsql` is an `EXEC` form of the call. Positional parameters bind by
    /// position and are given synthetic names (`@ce_pos_0`, `@ce_pos_1`, ...) so
    /// they can be declared in `@params` and referenced in the `EXEC`; named
    /// parameters bind by name. Positional arguments precede named ones, as
    /// T-SQL requires. `@params` is the matching declaration list. The synthetic
    /// names exist only in the describe request — the real RPC still sends the
    /// positional parameters unnamed, and the describe result is mapped back by
    /// ordinal (positional) or name (named) in
    /// [`apply_parameter_encryption`](Self::apply_parameter_encryption).
    ///
    /// Example: `EXEC dbo.p @ce_pos_0, @name1=@name1 OUTPUT` with
    /// `@ce_pos_0 int, @name1 nvarchar(10) OUTPUT`. Mirrors dotnet
    /// `BuildStoredProcedureStatementForColumnEncryption`, extended to cover the
    /// positional-parameter case the Rust API exposes.
    fn build_stored_procedure_describe_request(
        stored_procedure_name: &str,
        positional_params: &[RpcParameter],
        named_params: &[RpcParameter],
    ) -> TdsResult<(String, String)> {
        use std::fmt::Write as _;

        for named in named_params
            .iter()
            .filter_map(|param| param.name.as_deref())
        {
            for ordinal in 0..positional_params.len() {
                let synthetic = format!("@{SYNTHETIC_POSITIONAL_PARAM_PREFIX}{ordinal}");
                if named.eq_ignore_ascii_case(&synthetic) {
                    return Err(UsageError(format!(
                        "Named parameter '{named}' conflicts with internally generated positional parameter name '{synthetic}'"
                    )));
                }
            }
        }

        let mut tsql = format!("EXEC {stored_procedure_name}");
        let mut params_decl = String::new();
        let mut first = true;

        // Positional parameters: synthetic name, bound by position in the EXEC.
        for (ordinal, param) in positional_params.iter().enumerate() {
            let synthetic = format!("@{SYNTHETIC_POSITIONAL_PARAM_PREFIX}{ordinal}");
            let type_name = param.sql_declaration()?;
            let output = if param.is_output() { " OUTPUT" } else { "" };

            if first {
                tsql.push(' ');
                first = false;
            } else {
                tsql.push_str(", ");
                params_decl.push_str(", ");
            }

            // `write!` into a String is infallible.
            let _ = write!(tsql, "{synthetic}{output}");
            let _ = write!(params_decl, "{synthetic} {type_name}{output}");
        }

        // Named parameters: bound by name.
        for param in named_params {
            let Some(name) = param.name.as_deref() else {
                continue;
            };
            let type_name = param.sql_declaration()?;
            let output = if param.is_output() { " OUTPUT" } else { "" };

            if first {
                tsql.push(' ');
                first = false;
            } else {
                tsql.push_str(", ");
                params_decl.push_str(", ");
            }

            // `write!` into a String is infallible.
            let _ = write!(tsql, "{name}={name}{output}");
            let _ = write!(params_decl, "{name} {type_name}{output}");
        }

        Ok((tsql, params_decl))
    }

    /// Resolves (and memoizes) the cell decryptor for the current result set's
    /// CEK table, used to decrypt Always Encrypted columns while decoding rows.
    ///
    /// Returns `None` when the result set has no encrypted columns. The
    /// decryptor is rebuilt only when the result set (column metadata) changes,
    /// so the CEK table is resolved at most once per result set.
    async fn resolve_cell_decryptor(
        &mut self,
        metadata: &Arc<ColMetadataToken>,
    ) -> TdsResult<Option<Arc<dyn crate::security::cell_decryptor::CellDecryptor>>> {
        use crate::security::cell_decryptor::CellDecryptor;
        use crate::security::keystore::ResolvedCekDecryptor;

        // No CEK table normally means no encrypted columns in this result set.
        // A per-command `Disabled` override suppresses result decryption: any
        // encrypted column is then decoded as varbinary and its ciphertext is
        // returned through the normal decode path.
        if self.effective_command_ce_setting() == ExecutionColumnEncryptionSetting::Disabled {
            return Ok(None);
        }

        // An empty CEK table normally means the result set has no encrypted
        // columns. But the table can be empty even when a column carries
        // `CryptoMetadata` (a protocol/server anomaly); decryption is then
        // impossible, so fail fast rather than silently surface ciphertext for a
        // column we were asked to decrypt.
        if metadata.cek_table.is_empty() {
            if metadata.columns.iter().any(|c| c.crypto_metadata.is_some()) {
                return Err(crate::error::Error::ColumnEncryptionError(
                    "Result set has encrypted column metadata but an empty CEK table; \
                     cannot resolve column encryption keys"
                        .to_string(),
                ));
            }
            return Ok(None);
        }

        // Reuse the decryptor if it was built for this exact result set.
        if let Some((built_for, decryptor)) = &self.current_decryptor
            && Arc::ptr_eq(built_for, metadata)
        {
            return Ok(decryptor.clone());
        }

        let client_context = self
            .recovery_context
            .client_context
            .as_ref()
            .ok_or_else(|| {
                crate::error::Error::ColumnEncryptionError(
                    "Cannot decrypt encrypted columns without a client context".to_string(),
                )
            })?;

        let resolved = ResolvedCekDecryptor::resolve(
            &client_context.column_encryption_key_store_providers,
            &client_context.cek_cache,
            &metadata.cek_table,
            client_context.trusted_key_paths_for_current_server(),
        )
        .await;
        let decryptor: Arc<dyn CellDecryptor> = Arc::new(resolved);
        self.current_decryptor = Some((Arc::clone(metadata), Some(decryptor.clone())));
        Ok(Some(decryptor))
    }

    pub(crate) fn active_plp_reached_end(&self) -> bool {
        match &self.active_row_read_state {
            ActiveRowReadState::PlpPaused(plp_state) => plp_state.reached_end(),
            _ => true,
        }
    }

    /// Declared total length (wire bytes) of the active PLP value when the
    /// server sent a known-length header; `None` when no PLP stream is active
    /// or the value is unknown-length (streamed).
    pub(crate) fn active_plp_known_len(&self) -> Option<u64> {
        match &self.active_row_read_state {
            ActiveRowReadState::PlpPaused(plp_state) => plp_state.known_len(),
            _ => None,
        }
    }

    /// Cumulative wire bytes consumed from the active PLP value across all
    /// chunks; `0` when no PLP stream is active.
    pub(crate) fn active_plp_total_read(&self) -> usize {
        match &self.active_row_read_state {
            ActiveRowReadState::PlpPaused(plp_state) => plp_state.total_read(),
            _ => 0,
        }
    }

    pub(crate) async fn read_active_plp_bytes(&mut self, out: &mut [u8]) -> TdsResult<usize> {
        let ActiveRowReadState::PlpPaused(plp_state) = &mut self.active_row_read_state else {
            // No active stream is a sequencing error, not EOF: returning `Ok(0)`
            // here is indistinguishable from a legitimately exhausted stream, so
            // a mis-ordered call would silently yield an empty value instead of
            // surfacing the bug.
            return Err(UsageError(
                "read_active_plp_bytes called with no active PLP stream; \
                 read_row_column must report CursorColumn::PlpStreaming first"
                    .to_string(),
            ));
        };

        let start = Instant::now();
        let result = self
            .transport
            .read_active_plp_bytes(
                plp_state,
                self.remaining_request_timeout,
                self.cancel_handle.as_ref(),
                out,
            )
            .await;
        self.update_remaining_timeout(start);
        match result {
            Ok(read) => Ok(read),
            Err(error) => {
                self.settle_interrupted_read(&error);
                self.abort_pending_prepare_capture();
                Err(error)
            }
        }
    }

    /// Streams the next chunk of the active PLP column into `out`, returning the
    /// bytes written and whether the stream is now finished ([`PlpChunk`]).
    ///
    /// This is the public continuation for [`CursorColumn::PlpStreaming`]: after
    /// [`read_row_column`](Self::read_row_column) reports a PLP column, call this
    /// in a loop until [`PlpChunk::reached_end`] is `true`, then resume the
    /// cursor with the next [`read_row_column`](Self::read_row_column).
    ///
    /// # Errors
    ///
    /// Returns `UsageError` when no PLP stream is active — i.e. when called
    /// without a preceding [`CursorColumn::PlpStreaming`] from
    /// [`read_row_column`](Self::read_row_column). This is a sequencing error,
    /// deliberately distinct from a legitimately exhausted stream (which reports
    /// `read == 0, reached_end == true`).
    #[instrument(skip(self, out), level = "info")]
    pub async fn read_active_plp_chunk(&mut self, out: &mut [u8]) -> TdsResult<PlpChunk> {
        let read = self.read_active_plp_bytes(out).await?;
        Ok(PlpChunk {
            read,
            reached_end: self.active_plp_reached_end(),
            known_total: self.active_plp_known_len(),
            total_read: self.active_plp_total_read(),
        })
    }

    /// Attempts to consume the next PLP output chunk entirely from buffered bytes.
    pub fn try_read_active_plp_chunk(&mut self, out: &mut [u8]) -> TdsResult<CursorPoll<PlpChunk>> {
        if self
            .cancel_handle
            .as_ref()
            .is_some_and(|handle| handle.cancel_token.is_cancelled())
        {
            return Ok(CursorPoll::Pending);
        }
        let start = self.request_timeout_start();
        let read = match &mut self.active_row_read_state {
            ActiveRowReadState::PlpPaused(plp_state) => {
                self.transport.try_read_buffered_plp(plp_state, out)?
            }
            _ => {
                return Err(UsageError(
                    "try_read_active_plp_chunk called with no active PLP stream".to_string(),
                ));
            }
        };
        let Some(read) = read else {
            return Ok(CursorPoll::Pending);
        };
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }
        Ok(CursorPoll::Ready(PlpChunk {
            read,
            reached_end: self.active_plp_reached_end(),
            known_total: self.active_plp_known_len(),
            total_read: self.active_plp_total_read(),
        }))
    }

    /// Decodes the next row directly into a [`RowWriter`], returning `true` if
    /// a row was written or `false` when the result set is exhausted.
    ///
    /// This is the **push** entry point used by bulk consumers (Arrow / N-API /
    /// `next_row`). It always decodes a full row ([`ColumnPolicy::DecodeAll`]) and
    /// never pauses. If the pull cursor
    /// ([`next_row_cursor`](Self::next_row_cursor)) left a row *partially* read,
    /// this returns a [`UsageError`] rather than silently draining and skipping
    /// that row; a fully-consumed or absent row is accepted.
    ///
    /// Buffered, unencrypted, non-PLP rows are decoded synchronously first.
    /// Incomplete rows continue asynchronously with the same writer; other
    /// unsupported buffered shapes use `receive_row_into`. All paths bypass the
    /// intermediate `RowToken { all_values }`. Concrete writers stay concrete
    /// through the production transport and decode chain.
    /// [`ResultSet::next_row_into`] provides the same operation through
    /// statically dispatched trait calls.
    // `#[instrument]` adds enough state to exceed the 4096 B budget once the
    // lazy timeout future is inlined. Successful rows still emit `Row Received`.
    pub async fn next_row_into<W>(&mut self, writer: &mut W) -> TdsResult<bool>
    where
        W: RowWriter + Send + ?Sized,
    {
        // Every error return below must abort the pending prepare capture. A
        // wrapper that centralizes this cleanup exceeds the row-future size budget.
        // End-of-set reads are idempotent even after advancing clears metadata.
        if self.current_result_set_has_been_read_till_end {
            return Ok(false);
        }

        if self.current_metadata.is_none() {
            self.abort_pending_prepare_capture();
            return Err(UsageError(
                "No metadata found while fetching the next row. Have you called the execute method or was the query supposed to return resultset?".to_string(),
            ));
        }

        // The push path decodes whole rows and never pauses, so it must not run
        // while the pull cursor has a row *partially* read: silently draining it
        // would discard that row and return the *next* one, mapping the caller's
        // earlier `next_row_cursor() == true` to a row it never sees. An absent
        // (`Idle`) row is fine because there is nothing left to skip.
        match &self.active_row_read_state {
            ActiveRowReadState::Idle => {}
            ActiveRowReadState::RowPaused(_) | ActiveRowReadState::PlpPaused(_) => {
                self.abort_pending_prepare_capture();
                return Err(UsageError(
                    "next_row_into called while a pull-cursor row is still active; \
                     advance the cursor with next_row_cursor before using the push row API"
                        .to_string(),
                ));
            }
        }

        match self.try_next_buffered_row_into(writer) {
            Ok(BufferedRowPoll::Complete) => {
                info!("Row Received");
                return Ok(true);
            }
            Ok(BufferedRowPoll::Partial) => {
                if let Err(error) = self.finish_row_into(writer).await {
                    self.abort_pending_prepare_capture();
                    return Err(error);
                }
                info!("Row Received");
                return Ok(true);
            }
            Ok(BufferedRowPoll::Exhausted) => return Ok(false),
            Ok(BufferedRowPoll::Pending) => {}
            Err(error) => {
                self.abort_pending_prepare_capture();
                return Err(error);
            }
        }

        let metadata = Arc::clone(self.current_metadata.as_ref().unwrap());
        let decryptor = match self.resolve_cell_decryptor(&metadata).await {
            Ok(decryptor) => decryptor,
            Err(error) => {
                self.abort_pending_prepare_capture();
                return Err(error);
            }
        };
        let parser_context = ParserContext::ColumnMetadata(metadata, decryptor);
        loop {
            let start = Instant::now();
            let result = match self
                .transport
                .receive_row_into(
                    &parser_context,
                    self.remaining_request_timeout,
                    self.cancel_handle.as_ref(),
                    ColumnPolicy::DecodeAll,
                    writer,
                )
                .await
            {
                Ok(result) => result,
                Err(error) => {
                    self.settle_interrupted_read(&error);
                    self.abort_pending_prepare_capture();
                    return Err(error);
                }
            };
            self.update_remaining_timeout(start);

            match result {
                RowReadResult::RowWritten => {
                    writer.end_row();
                    info!("Row Received");
                    return Ok(true);
                }
                RowReadResult::RowPaused(_) | RowReadResult::PlpPaused(_) => {
                    // DecodeAll never pauses; a pause here is a protocol/logic error.
                    self.abort_pending_prepare_capture();
                    return Err(crate::error::Error::ProtocolError(
                        "Unexpected pause while decoding a full row (ColumnPolicy::DecodeAll)"
                            .to_string(),
                    ));
                }
                RowReadResult::Token(token) => {
                    let handled = match Box::pin(self.handle_row_read_token(token)).await {
                        Ok(handled) => handled,
                        Err(error) => {
                            self.abort_pending_prepare_capture();
                            return Err(error);
                        }
                    };
                    if let Some(has_row) = handled {
                        return Ok(has_row);
                    }
                }
            }
        }
    }

    /// Attempts to position the cursor from bytes already buffered by the transport.
    ///
    /// Returns [`CursorPoll::Pending`] without consuming bytes or cursor state
    /// when the current row must first be drained, the next token needs async
    /// parsing, encryption keys need resolving, or the row header is incomplete.
    pub fn try_next_row_cursor(&mut self) -> TdsResult<CursorPoll<bool>> {
        let Some(metadata) = self.current_metadata.as_ref().map(Arc::clone) else {
            return Err(UsageError(
                "No metadata found while fetching the next row. Have you called the execute method or was the query supposed to return resultset?".to_string(),
            ));
        };
        if self.current_result_set_has_been_read_till_end {
            return Ok(CursorPoll::Ready(false));
        }
        if !matches!(self.active_row_read_state, ActiveRowReadState::Idle)
            || self
                .cancel_handle
                .as_ref()
                .is_some_and(|handle| handle.cancel_token.is_cancelled())
        {
            return Ok(CursorPoll::Pending);
        }

        // Resolving a CEK can call an async key-store provider. Keep encrypted
        // result sets on the existing async path.
        if !metadata.cek_table.is_empty()
            || metadata
                .columns
                .iter()
                .any(|column| column.crypto_metadata.is_some())
        {
            return Ok(CursorPoll::Pending);
        }

        let context = ParserContext::ColumnMetadata(metadata, None);
        let start = self.request_timeout_start();
        let pause_state = self.transport.try_receive_row_header(&context)?;
        let Some(pause_state) = pause_state else {
            return Ok(CursorPoll::Pending);
        };
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }
        self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
        Ok(CursorPoll::Ready(true))
    }

    /// Attempts to decode the next row directly into `writer` from bytes already
    /// buffered by the transport.
    ///
    /// [`BufferedRowPoll::Pending`] is non-destructive. A
    /// [`BufferedRowPoll::Partial`] result may already have written a row prefix;
    /// the same writer must be passed to [`Self::finish_row_into`].
    pub fn try_next_buffered_row_into<W>(&mut self, writer: &mut W) -> TdsResult<BufferedRowPoll>
    where
        W: RowWriter + Send + ?Sized,
    {
        if self.current_metadata.is_none() {
            return Err(UsageError(
                "No metadata found while fetching the next row. Have you called the execute method or was the query supposed to return resultset?".to_string(),
            ));
        }
        if self.current_result_set_has_been_read_till_end {
            return Ok(BufferedRowPoll::Exhausted);
        }
        if !matches!(self.active_row_read_state, ActiveRowReadState::Idle)
            || self
                .cancel_handle
                .as_ref()
                .is_some_and(|handle| handle.cancel_token.is_cancelled())
            || !self.buffered_row_support()
        {
            return Ok(BufferedRowPoll::Pending);
        }
        let metadata = Arc::clone(
            self.current_metadata
                .as_ref()
                .ok_or_else(|| UsageError("Buffered row metadata was cleared".to_string()))?,
        );

        let context = ParserContext::ColumnMetadata(metadata, None);
        let start = self.request_timeout_start();
        let Some(mut pause_state) = self.transport.try_receive_row_header(&context)? else {
            return Ok(BufferedRowPoll::Pending);
        };
        let complete = self
            .transport
            .try_read_buffered_row_into(&mut pause_state, writer)?;
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }

        if complete {
            writer.end_row();
            Ok(BufferedRowPoll::Complete)
        } else {
            self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
            Ok(BufferedRowPoll::Partial)
        }
    }

    /// Attempts to position a row and capture its inline prefix from buffered bytes.
    pub fn try_next_buffered_row_prefix_into<W>(
        &mut self,
        prefix_len: usize,
        writer: &mut W,
    ) -> TdsResult<BufferedRowPoll>
    where
        W: RowWriter + Send + ?Sized,
    {
        if self.current_metadata.is_none() {
            return Err(UsageError(
                "No metadata found while fetching the next row. Have you called the execute method or was the query supposed to return resultset?".to_string(),
            ));
        }
        if self.current_result_set_has_been_read_till_end {
            return Ok(BufferedRowPoll::Exhausted);
        }
        if !matches!(self.active_row_read_state, ActiveRowReadState::Idle)
            || self
                .cancel_handle
                .as_ref()
                .is_some_and(|handle| handle.cancel_token.is_cancelled())
            || self.current_result_bufferable_prefix_len() != Some(prefix_len)
        {
            return Ok(BufferedRowPoll::Pending);
        }
        let metadata = Arc::clone(
            self.current_metadata
                .as_ref()
                .ok_or_else(|| UsageError("Buffered row metadata was cleared".to_string()))?,
        );
        let context = ParserContext::ColumnMetadata(metadata, None);
        let start = self.request_timeout_start();
        let Some(mut pause_state) = self.transport.try_receive_row_header(&context)? else {
            return Ok(BufferedRowPoll::Pending);
        };
        let complete = self.transport.try_read_buffered_row_prefix_into(
            &mut pause_state,
            prefix_len,
            writer,
        )?;
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }
        self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
        Ok(if complete {
            BufferedRowPoll::Complete
        } else {
            BufferedRowPoll::Partial
        })
    }

    /// Positions the cursor on the next row without decoding any column
    /// (ODBC `SQLFetch`). Returns `Ok(true)` when positioned on a row and
    /// `Ok(false)` when the result set is exhausted.
    ///
    /// After this returns `true`, individual columns are pulled with
    /// [`read_row_column`](Self::read_row_column). Any previously positioned row
    /// is drained first; its remaining column bytes are read and discarded rather
    /// than returned to the caller. Use this directly, or after
    /// [`Self::try_next_row_cursor`] returns [`CursorPoll::Pending`].
    #[instrument(skip(self), level = "info")]
    pub async fn next_row_cursor(&mut self) -> TdsResult<bool> {
        // A previous `peek_past_current_row` already read this row's header
        // off the wire and parked it in `active_row_read_state` — hand it
        // over as-is instead of draining it (see `drain_active_row_if_needed`,
        // which would otherwise treat an unread `RowPaused` as abandoned).
        if self.row_already_positioned {
            self.row_already_positioned = false;
            return Ok(true);
        }

        if self.current_metadata.is_none() {
            return Err(UsageError(
                "No metadata found while fetching the next row. Have you called the execute method or was the query supposed to return resultset?".to_string(),
            ));
        }

        // Idempotent at end-of-set: once the terminating DONE has been read the
        // wire holds nothing more for this result set until the caller advances
        // (SQLMoreResults). Re-reading here would block on a packet the server
        // will never send, so report exhaustion without touching the transport.
        if self.current_result_set_has_been_read_till_end {
            return Ok(false);
        }

        self.drain_active_row_if_needed().await?;

        let metadata = Arc::clone(self.current_metadata.as_ref().unwrap());
        let decryptor = self.resolve_cell_decryptor(&metadata).await?;
        let parser_context = ParserContext::ColumnMetadata(metadata, decryptor);
        loop {
            let start = self.request_timeout_start();
            let header = self
                .transport
                .receive_row_header(
                    &parser_context,
                    self.remaining_request_timeout,
                    self.cancel_handle.as_ref(),
                )
                .await;
            if let Some(start) = start {
                self.update_remaining_timeout(start);
            }
            let header = match header {
                Ok(header) => header,
                Err(error) => {
                    self.settle_interrupted_read(&error);
                    return Err(error);
                }
            };

            match header {
                RowHeader::Positioned(pause_state) => {
                    // Positioned before column 0; columns are pulled lazily via
                    // `read_row_column`. A zero-column row parks here too and
                    // drains as a no-op on the next advance.
                    self.active_row_read_state =
                        ActiveRowReadState::RowPaused(Box::new(pause_state));
                    return Ok(true);
                }
                RowHeader::Token(token) => {
                    if let Some(has_row) = Box::pin(self.handle_row_read_token(token)).await? {
                        return Ok(has_row);
                    }
                }
            }
        }
    }

    /// Attempts to peek ahead to the next row from buffered bytes and preserves
    /// it for the next cursor advance.
    ///
    /// ODBC execution uses this before its first fetch so an ERROR token sent
    /// after COLMETADATA is reported by SQLExecDirect/SQLExecute. The ODBC busy
    /// gate also uses it after delivering a row to discover whether another
    /// row follows or the wire is now idle.
    ///
    /// A row found by [`CursorPoll::Ready`] is parked for the next
    /// [`next_row_cursor`](Self::next_row_cursor) call. [`CursorPoll::Pending`]
    /// leaves the peek for [`peek_past_current_row`](Self::peek_past_current_row).
    pub fn try_peek_past_current_row(&mut self) -> TdsResult<CursorPoll<bool>> {
        let poll = self.try_next_row_cursor()?;
        if let CursorPoll::Ready(has_row) = poll {
            self.row_already_positioned = has_row;
        }
        Ok(poll)
    }

    /// Peeks past the fully consumed row, parking the next row if one exists.
    ///
    /// Call this before the first row is positioned, or after every column of
    /// the current row has been read. Like `next_row_cursor`, it discards any
    /// unread columns from an already-positioned row.
    pub async fn peek_past_current_row(&mut self) -> TdsResult<bool> {
        let has_row = self.next_row_cursor().await?;
        self.row_already_positioned = has_row;
        Ok(has_row)
    }

    /// Attempts to decode the next sequential column from buffered bytes.
    ///
    /// Returns [`CursorPoll::Pending`] without consuming bytes or cursor state
    /// for PLP, encrypted, skipped, unsupported, or incomplete columns. The
    /// caller then continues with [`Self::read_row_column`].
    pub fn try_read_row_column(&mut self, target: usize) -> TdsResult<CursorPoll<CursorColumn>> {
        let (next_column, column_count) = match &self.active_row_read_state {
            ActiveRowReadState::Idle => return Ok(CursorPoll::Ready(CursorColumn::RowEnded)),
            ActiveRowReadState::PlpPaused(_) => return Ok(CursorPoll::Pending),
            ActiveRowReadState::RowPaused(pause_state) => {
                (pause_state.next_column_index, pause_state.columns().len())
            }
        };
        if self
            .cancel_handle
            .as_ref()
            .is_some_and(|handle| handle.cancel_token.is_cancelled())
        {
            return Ok(CursorPoll::Pending);
        }
        if target >= column_count {
            return Err(UsageError(format!(
                "read_row_column target column {target} is out of range (row has {column_count} columns)"
            )));
        }
        if target < next_column {
            return Ok(CursorPoll::Ready(CursorColumn::AlreadyConsumed));
        }
        if target != next_column {
            // Skipping intervening columns can require arbitrarily shaped
            // decoders. The async path remains authoritative for that case.
            return Ok(CursorPoll::Pending);
        }

        let buffered_null = matches!(
            &self.active_row_read_state,
            ActiveRowReadState::RowPaused(pause_state)
                if pause_state
                    .nbc_null_bitmap
                    .as_ref()
                    .is_some_and(|bitmap| bitmap[target / 8] & (1 << (target % 8)) != 0)
        );
        if buffered_null {
            let ActiveRowReadState::RowPaused(mut pause_state) =
                std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle)
            else {
                return Err(crate::error::Error::ImplementationError(
                    "buffered NULL decode lost its row pause state".to_string(),
                ));
            };
            pause_state.next_column_index = target + 1;
            if pause_state.next_column_index < column_count {
                self.active_row_read_state = ActiveRowReadState::RowPaused(pause_state);
            }
            return Ok(CursorPoll::Ready(CursorColumn::Value {
                value: ColumnValues::Null,
                variant_base: None,
            }));
        }

        let buffered_plp = match &self.active_row_read_state {
            ActiveRowReadState::RowPaused(pause_state)
                if pause_state
                    .columns()
                    .get(target)
                    .is_some_and(|metadata| metadata.is_plp()) =>
            {
                self.transport.try_begin_buffered_plp(pause_state, target)?
            }
            _ => None,
        };
        if let Some(stream) = buffered_plp {
            let ActiveRowReadState::RowPaused(mut pause_state) =
                std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle)
            else {
                return Err(crate::error::Error::ImplementationError(
                    "buffered PLP decode lost its row pause state".to_string(),
                ));
            };
            pause_state.next_column_index = target + 1;
            return if let Some(plp_stream) = stream {
                let collation = plp_stream.collation();
                self.active_row_read_state =
                    ActiveRowReadState::PlpPaused(Box::new(PlpPauseState {
                        row_pause_state: *pause_state,
                        plp_stream,
                    }));
                Ok(CursorPoll::Ready(CursorColumn::PlpStreaming { collation }))
            } else {
                if pause_state.next_column_index < column_count {
                    self.active_row_read_state = ActiveRowReadState::RowPaused(pause_state);
                }
                Ok(CursorPoll::Ready(CursorColumn::Value {
                    value: ColumnValues::Null,
                    variant_base: None,
                }))
            };
        }

        let start = self.request_timeout_start();
        let value = match &self.active_row_read_state {
            ActiveRowReadState::RowPaused(pause_state) => self
                .transport
                .try_read_buffered_column_with_base(pause_state, target)?,
            ActiveRowReadState::Idle | ActiveRowReadState::PlpPaused(_) => None,
        };
        let Some((value, variant_base)) = value else {
            return Ok(CursorPoll::Pending);
        };
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }

        let ActiveRowReadState::RowPaused(mut pause_state) =
            std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle)
        else {
            return Err(crate::error::Error::ImplementationError(
                "buffered column decode lost its row pause state".to_string(),
            ));
        };
        pause_state.next_column_index = target + 1;
        if pause_state.next_column_index < column_count {
            self.active_row_read_state = ActiveRowReadState::RowPaused(pause_state);
        }
        Ok(CursorPoll::Ready(CursorColumn::Value {
            value,
            variant_base,
        }))
    }

    /// Attempts to consume one complete buffered PLP column without opening a stream.
    pub fn try_read_row_plp_complete(
        &mut self,
        target: usize,
        out: &mut [u8],
    ) -> TdsResult<CursorPoll<Option<PlpChunk>>> {
        if self
            .cancel_handle
            .as_ref()
            .is_some_and(|handle| handle.cancel_token.is_cancelled())
        {
            return Ok(CursorPoll::Pending);
        }
        let (next_column, column_count) = match &self.active_row_read_state {
            ActiveRowReadState::RowPaused(pause_state) => {
                (pause_state.next_column_index, pause_state.columns().len())
            }
            _ => return Ok(CursorPoll::Pending),
        };
        if target != next_column || target >= column_count {
            return Ok(CursorPoll::Pending);
        }
        let is_null = matches!(
            &self.active_row_read_state,
            ActiveRowReadState::RowPaused(pause_state)
                if pause_state
                    .nbc_null_bitmap
                    .as_ref()
                    .is_some_and(|bitmap| bitmap[target / 8] & (1 << (target % 8)) != 0)
        );
        let result = if is_null {
            Some(None)
        } else {
            match &self.active_row_read_state {
                ActiveRowReadState::RowPaused(pause_state) => self
                    .transport
                    .try_read_complete_buffered_plp_column(pause_state, target, out)?,
                _ => None,
            }
        };
        let Some(result) = result else {
            return Ok(CursorPoll::Pending);
        };
        let ActiveRowReadState::RowPaused(mut pause_state) =
            std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle)
        else {
            return Err(crate::error::Error::ImplementationError(
                "complete buffered PLP lost its row pause state".to_string(),
            ));
        };
        pause_state.next_column_index = target + 1;
        if pause_state.next_column_index < column_count {
            self.active_row_read_state = ActiveRowReadState::RowPaused(pause_state);
        }
        Ok(CursorPoll::Ready(result.map(
            |(read, known_total, total_read)| PlpChunk {
                read,
                reached_end: true,
                known_total,
                total_read,
            },
        )))
    }

    /// Attempts to finish the positioned row through `writer` from bytes already
    /// buffered by the transport.
    ///
    /// `false` means the buffered prefix was consumed and the same writer must be
    /// passed to [`Self::finish_row_into`] to decode the remainder.
    pub fn try_finish_row_into<W>(&mut self, writer: &mut W) -> TdsResult<bool>
    where
        W: RowWriter + Send + ?Sized,
    {
        if self
            .cancel_handle
            .as_ref()
            .is_some_and(|handle| handle.cancel_token.is_cancelled())
        {
            return Ok(false);
        }

        let start = self.request_timeout_start();
        let complete = match &mut self.active_row_read_state {
            ActiveRowReadState::RowPaused(pause_state) => self
                .transport
                .try_read_buffered_row_into(pause_state, writer)?,
            ActiveRowReadState::PlpPaused(_) => return Ok(false),
            ActiveRowReadState::Idle => {
                return Err(UsageError(
                    "try_finish_row_into called without a positioned row".to_string(),
                ));
            }
        };
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }
        if complete {
            self.active_row_read_state = ActiveRowReadState::Idle;
            writer.end_row();
        }
        Ok(complete)
    }

    /// Attempts to finish an inline row prefix from bytes already buffered.
    pub fn try_finish_row_prefix_into<W>(
        &mut self,
        prefix_len: usize,
        writer: &mut W,
    ) -> TdsResult<bool>
    where
        W: RowWriter + Send + ?Sized,
    {
        if self
            .cancel_handle
            .as_ref()
            .is_some_and(|handle| handle.cancel_token.is_cancelled())
        {
            return Ok(false);
        }
        let start = self.request_timeout_start();
        let complete = match &mut self.active_row_read_state {
            ActiveRowReadState::RowPaused(pause_state) => self
                .transport
                .try_read_buffered_row_prefix_into(pause_state, prefix_len, writer)?,
            ActiveRowReadState::PlpPaused(_) => return Ok(false),
            ActiveRowReadState::Idle => {
                return Err(UsageError(
                    "try_finish_row_prefix_into called without a positioned row".to_string(),
                ));
            }
        };
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }
        Ok(complete)
    }

    /// Returns whether the current result can be consumed as complete rows
    /// without changing the pull cursor's PLP streaming behavior.
    pub fn current_result_supports_row_into(&self) -> bool {
        let Some(metadata) = self.current_metadata.as_ref() else {
            return false;
        };
        if let Some(cached) = self.buffered_row_support.as_ref()
            && Arc::ptr_eq(metadata, &cached.metadata)
        {
            return cached.whole_row;
        }
        Self::metadata_supports_buffered_rows(metadata)
    }

    /// Returns the contiguous non-PLP prefix eligible for fetch-time capture.
    pub fn current_result_bufferable_prefix_len(&mut self) -> Option<usize> {
        self.buffered_row_support();
        self.buffered_row_support
            .as_ref()
            .and_then(|support| support.prefix_len)
    }

    /// Returns and caches whole-row eligibility for the current metadata allocation.
    fn buffered_row_support(&mut self) -> bool {
        let Some(metadata) = self.current_metadata.as_ref() else {
            return false;
        };
        if let Some(cached) = self.buffered_row_support.as_ref()
            && Arc::ptr_eq(metadata, &cached.metadata)
        {
            return cached.whole_row;
        }

        let whole_row = Self::metadata_supports_buffered_rows(metadata);
        let prefix_len = if metadata.cek_table.is_empty()
            && metadata
                .columns
                .iter()
                .all(|column| column.crypto_metadata.is_none())
        {
            metadata
                .columns
                .iter()
                .position(|column| column.is_plp())
                .filter(|prefix_len| *prefix_len > 0)
        } else {
            None
        };
        self.buffered_row_support = Some(Box::new(BufferedRowSupport {
            metadata: Arc::clone(metadata),
            whole_row,
            prefix_len,
        }));
        whole_row
    }

    /// Checks whether every column can use the non-streaming, non-encrypted row path.
    fn metadata_supports_buffered_rows(metadata: &ColMetadataToken) -> bool {
        metadata.cek_table.is_empty()
            && metadata
                .columns
                .iter()
                .all(|column| !column.is_plp() && column.crypto_metadata.is_none())
    }

    /// Finishes a row partially consumed by [`Self::try_finish_row_into`].
    pub async fn finish_row_into<W>(&mut self, writer: &mut W) -> TdsResult<()>
    where
        W: RowWriter + Send + ?Sized,
    {
        let state = std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle);
        let pause_state = match state {
            ActiveRowReadState::RowPaused(pause_state) => pause_state,
            state => {
                self.active_row_read_state = state;
                return Err(UsageError(
                    "finish_row_into called without a resumable positioned row".to_string(),
                ));
            }
        };

        let start = self.request_timeout_start();
        let result = self
            .transport
            .resume_row_into(
                *pause_state,
                self.remaining_request_timeout,
                self.cancel_handle.as_ref(),
                ColumnPolicy::DecodeAll,
                writer,
            )
            .await;
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }

        match result {
            Ok(RowReadResult::RowWritten) => {
                writer.end_row();
                Ok(())
            }
            Ok(RowReadResult::RowPaused(pause_state)) => {
                self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
                Err(crate::error::Error::ProtocolError(
                    "DecodeAll unexpectedly paused while finishing a row".to_string(),
                ))
            }
            Ok(RowReadResult::PlpPaused(pause_state)) => {
                self.active_row_read_state = ActiveRowReadState::PlpPaused(Box::new(pause_state));
                Err(crate::error::Error::ProtocolError(
                    "DecodeAll unexpectedly paused at a PLP value while finishing a row"
                        .to_string(),
                ))
            }
            Ok(RowReadResult::Token(_)) => Err(crate::error::Error::ProtocolError(
                "row continuation returned a control token".to_string(),
            )),
            Err(error) => {
                self.settle_interrupted_read(&error);
                self.abort_pending_prepare_capture();
                Err(error)
            }
        }
    }

    /// Finishes a partially buffered inline prefix and pauses before its first PLP.
    pub async fn finish_row_prefix_into<W>(
        &mut self,
        prefix_len: usize,
        writer: &mut W,
    ) -> TdsResult<()>
    where
        W: RowWriter + Send + ?Sized,
    {
        let state = std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle);
        let pause_state = match state {
            ActiveRowReadState::RowPaused(pause_state) => pause_state,
            state => {
                self.active_row_read_state = state;
                return Err(UsageError(
                    "finish_row_prefix_into called without a resumable positioned row".to_string(),
                ));
            }
        };
        let start = self.request_timeout_start();
        let result = self
            .transport
            .resume_row_into(
                *pause_state,
                self.remaining_request_timeout,
                self.cancel_handle.as_ref(),
                ColumnPolicy::DecodePrefix(prefix_len),
                writer,
            )
            .await;
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }
        match result {
            Ok(RowReadResult::RowPaused(pause_state))
                if pause_state.next_column_index == prefix_len =>
            {
                self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
                Ok(())
            }
            Ok(RowReadResult::RowPaused(pause_state)) => {
                self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
                Err(crate::error::Error::ProtocolError(
                    "Inline prefix decode paused at the wrong column".to_string(),
                ))
            }
            Ok(RowReadResult::RowWritten) => Err(crate::error::Error::ProtocolError(
                "Inline prefix decode consumed the complete row".to_string(),
            )),
            Ok(RowReadResult::PlpPaused(pause_state)) => {
                self.active_row_read_state = ActiveRowReadState::PlpPaused(Box::new(pause_state));
                Err(crate::error::Error::ProtocolError(
                    "Inline prefix decode consumed the PLP header".to_string(),
                ))
            }
            Ok(RowReadResult::Token(_)) => Err(crate::error::Error::ProtocolError(
                "Inline prefix continuation returned a control token".to_string(),
            )),
            Err(error) => {
                self.settle_interrupted_read(&error);
                self.abort_pending_prepare_capture();
                Err(error)
            }
        }
    }

    /// Pulls column `target` (0-based) of the currently positioned row,
    /// skipping any intervening columns (ODBC `SQLGetData`). Forward-only:
    /// `target` must be at or after the cursor's next undecoded column.
    ///
    /// Returns:
    /// - [`CursorColumn::Value`] with the decoded value for non-PLP columns,
    /// - [`CursorColumn::PlpStreaming`] when `target` is a PLP column whose
    ///   bytes must be pulled via [`read_active_plp_chunk`](Self::read_active_plp_chunk),
    /// - [`CursorColumn::AlreadyConsumed`] if `target` was already read or skipped
    ///   while the row remains positioned,
    /// - [`CursorColumn::RowEnded`] when no row is positioned.
    ///
    /// Use this directly, or after [`Self::try_read_row_column`] returns
    /// [`CursorPoll::Pending`].
    ///
    /// # Errors
    ///
    /// Returns `UsageError` when `target` is out of range **and** a row is
    /// still positioned with unread columns (partially read). When no row is
    /// positioned -- including after the final column has been read -- an
    /// out-of-range or backward `target` yields [`CursorColumn::RowEnded`]
    /// instead of an error.
    ///
    /// # Notes
    ///
    /// Reading the final column advances the cursor to idle, so a subsequent
    /// backward or out-of-range request returns [`CursorColumn::RowEnded`]. A
    /// caller that needs to distinguish "I rewound past the last column" from
    /// "no row is positioned" must track the column it last read itself (as the
    /// ODBC layer does).
    ///
    /// A `true` return from [`next_row_cursor`](Self::next_row_cursor) does not
    /// guarantee `read_row_column(0)` yields a value: a zero-column row is
    /// positioned with a column count of 0, so `read_row_column(0)` is
    /// out-of-range and returns `UsageError`.
    // Avoid a span for every SQLGetData column; row and token events retain observability.
    pub async fn read_row_column(&mut self, target: usize) -> TdsResult<CursorColumn> {
        match std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle) {
            ActiveRowReadState::Idle => Ok(CursorColumn::RowEnded),
            ActiveRowReadState::RowPaused(pause_state) => {
                self.resume_to_column(*pause_state, target).await
            }
            ActiveRowReadState::PlpPaused(mut plp_state) => {
                self.drain_active_plp(&mut plp_state).await?;
                self.resume_to_column(plp_state.row_pause_state, target)
                    .await
            }
        }
    }

    async fn resume_to_column(
        &mut self,
        pause_state: RowPauseState,
        target: usize,
    ) -> TdsResult<CursorColumn> {
        let column_count = pause_state.columns().len();
        if target >= column_count {
            // Out-of-range: decoding with ColumnPolicy::DecodeOne(target) would skip
            // every remaining column and report RowWritten, silently consuming
            // the row. Reject without touching the transport and keep the
            // cursor positioned so valid pulls still work. ODBC validates the
            // column index first, so this guards the public API against other
            // callers.
            self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
            return Err(UsageError(format!(
                "read_row_column target column {target} is out of range (row has {column_count} columns)"
            )));
        }

        if target < pause_state.next_column_index {
            // Forward-only: the target column's bytes are already gone. Keep the
            // cursor where it is so later (valid) pulls still work.
            self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(pause_state));
            return Ok(CursorColumn::AlreadyConsumed);
        }

        let mut capture = DefaultRowWriter::new(1);
        let start = self.request_timeout_start();
        let result = self
            .transport
            .resume_row_into(
                pause_state,
                self.remaining_request_timeout,
                self.cancel_handle.as_ref(),
                ColumnPolicy::DecodeOne(target),
                &mut capture,
            )
            .await;
        if let Some(start) = start {
            self.update_remaining_timeout(start);
        }
        let result = match result {
            Ok(result) => result,
            Err(error) => {
                self.settle_interrupted_read(&error);
                return Err(error);
            }
        };

        match result {
            RowReadResult::RowPaused(next_pause) => {
                self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(next_pause));
                let variant_base = capture.variant_base(0);
                let value = capture.take_row().into_iter().next().ok_or_else(|| {
                    crate::error::Error::ProtocolError(format!(
                        "Decoder produced no value for non-null column {target}"
                    ))
                })?;
                Ok(CursorColumn::Value {
                    value,
                    variant_base,
                })
            }
            RowReadResult::RowWritten => {
                // `target` was the last column; the row is now fully consumed.
                // Advance the cursor to idle — a later out-of-range or backward
                // pull reports `RowEnded`. Callers needing to distinguish a
                // rewind from "no row positioned" track the column themselves.
                self.active_row_read_state = ActiveRowReadState::Idle;
                let variant_base = capture.variant_base(0);
                let value = capture.take_row().into_iter().next().ok_or_else(|| {
                    crate::error::Error::ProtocolError(format!(
                        "Decoder produced no value for non-null column {target}"
                    ))
                })?;
                Ok(CursorColumn::Value {
                    value,
                    variant_base,
                })
            }
            RowReadResult::PlpPaused(plp_state) => {
                let collation = plp_state.collation();
                self.active_row_read_state = ActiveRowReadState::PlpPaused(Box::new(plp_state));
                Ok(CursorColumn::PlpStreaming { collation })
            }
            RowReadResult::Token(_) => Err(crate::error::Error::ProtocolError(
                "Unexpected token while resuming to a target column".to_string(),
            )),
        }
    }

    /// Drains any partially read current row so the stream is aligned on the
    /// next ROW/NBCROW (or terminating) token. Skips remaining column bytes
    /// without materializing them.
    async fn drain_active_row_if_needed(&mut self) -> TdsResult<()> {
        if matches!(self.active_row_read_state, ActiveRowReadState::Idle) {
            return Ok(());
        }

        // Whatever is parked is being discarded now (as an abandoned row, not
        // handed to a caller), so a stale peek can no longer be honored.
        self.row_already_positioned = false;

        // Mixing the pull and push APIs is rare. Keep that large continuation
        // out of every ordinary row-fetch future, paying only on this recovery path.
        Box::pin(self.drain_active_row()).await
    }

    async fn drain_active_row(&mut self) -> TdsResult<()> {
        match std::mem::replace(&mut self.active_row_read_state, ActiveRowReadState::Idle) {
            ActiveRowReadState::Idle => Ok(()),
            ActiveRowReadState::RowPaused(pause_state) => {
                let mut sink = DiscardRowWriter;
                self.resume_row_loop(*pause_state, ColumnPolicy::SkipAll, &mut sink)
                    .await?;
                Ok(())
            }
            ActiveRowReadState::PlpPaused(mut plp_state) => {
                self.drain_active_plp(&mut plp_state).await?;
                let mut sink = DiscardRowWriter;
                self.resume_row_loop(plp_state.row_pause_state, ColumnPolicy::SkipAll, &mut sink)
                    .await?;
                Ok(())
            }
        }
    }

    /// Reads and discards all remaining bytes of an active PLP stream.
    ///
    /// The scratch buffer is heap-allocated rather than a stack array: it is live
    /// across the await below, so a stack array would be stored inline in this
    /// future and propagate into every caller that awaits it — `read_row_column`
    /// directly, plus `drain_rows`, `next_row_into` and `next_row_cursor` via
    /// `drain_active_row`. Abandoning a partially read PLP column is rare and
    /// already network-bound, so one allocation there is negligible; an 8 KiB
    /// per-row state machine is not.
    async fn drain_active_plp(&mut self, plp_state: &mut PlpPauseState) -> TdsResult<()> {
        if plp_state.reached_end() {
            return Ok(());
        }
        let mut buffer = vec![0u8; 8192];
        while !plp_state.reached_end() {
            let start = Instant::now();
            let read = self
                .transport
                .read_active_plp_bytes(
                    plp_state,
                    self.remaining_request_timeout,
                    self.cancel_handle.as_ref(),
                    &mut buffer,
                )
                .await;
            self.update_remaining_timeout(start);
            let read = match read {
                Ok(read) => read,
                Err(error) => {
                    self.settle_interrupted_read(&error);
                    return Err(error);
                }
            };

            if read == 0 && !plp_state.reached_end() {
                return Err(crate::error::Error::ProtocolError(
                    "Active PLP drain made no progress before end-of-stream".to_string(),
                ));
            }
        }
        Ok(())
    }

    async fn resume_row_loop<W>(
        &mut self,
        pause_state: RowPauseState,
        plan: ColumnPolicy,
        writer: &mut W,
    ) -> TdsResult<bool>
    where
        W: RowWriter + Send + ?Sized,
    {
        let current = pause_state;
        let start = Instant::now();
        let result = self
            .transport
            .resume_row_into(
                current,
                self.remaining_request_timeout,
                self.cancel_handle.as_ref(),
                plan,
                writer,
            )
            .await;
        self.update_remaining_timeout(start);
        let result = match result {
            Ok(result) => result,
            Err(error) => {
                self.settle_interrupted_read(&error);
                return Err(error);
            }
        };
        match result {
            RowReadResult::RowWritten => {
                writer.end_row();
                info!("Row Received");
                Ok(true)
            }
            RowReadResult::RowPaused(next_pause) => {
                self.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(next_pause));
                Ok(true)
            }
            RowReadResult::PlpPaused(plp_state) => {
                self.active_row_read_state = ActiveRowReadState::PlpPaused(Box::new(plp_state));
                Ok(true)
            }
            RowReadResult::Token(token) => {
                if let Some(has_row) = self.handle_row_read_token(token).await? {
                    Ok(has_row)
                } else {
                    // This should not happen in normal resume flow; keep as a defensive guard.
                    Err(crate::error::Error::ProtocolError(
                        "Unexpected token during row resume".to_string(),
                    ))
                }
            }
        }
    }

    async fn handle_row_read_token(&mut self, token: Tokens) -> TdsResult<Option<bool>> {
        match token {
            Tokens::DoneInProc(done) => self.handle_row_done(done, true),
            Tokens::DoneProc(done) | Tokens::Done(done) => self.handle_row_done(done, false),
            Tokens::Order(order_token) => {
                info!(?order_token);
                Ok(None)
            }
            Tokens::EnvChange(env_change) => {
                info!(?env_change);
                if env_change.sub_type == EnvChangeTokenSubType::ResetConnection {
                    self.on_reset_connection_ack();
                }
                self.execution_context
                    .capture_change_property(&env_change, &mut self.negotiated_settings)?;
                Ok(None)
            }
            Tokens::SessionState(session_state) => {
                self.recovery_context
                    .process_session_state(&session_state)?;
                Ok(None)
            }
            Tokens::ReturnValue(return_value_token) => {
                let return_value = self.finalize_return_value(return_value_token)?;
                self.push_return_value(return_value);
                Ok(None)
            }
            Tokens::Error(error_token) => {
                info!(?error_token);
                let mut all_errors = vec![self.record_error_token(&error_token)];
                let drain_result = self.drain_stream().await;
                // Reset batch state before propagating: the error terminates the
                // batch regardless of whether the drain fully consumed it, so a
                // subsequent `close_query` / `advance` does not block trying to
                // read a stream we have given up on.
                self.execution_context.set_has_open_batch(false);
                self.current_result_set_has_been_read_till_end = true;
                self.current_metadata = None;
                match drain_result {
                    Ok(drain_errors) => all_errors.extend(drain_errors),
                    Err(e) => {
                        warn!(error = ?e, "Drain after statement error failed; retiring the connection");
                        // Mirrors the ERROR arm in `advance_to_result_boundary`:
                        // the SQL error still surfaces, but a stream we gave up on
                        // must not be handed back to a pool as `SqlServerError`.
                        self.retire_after_failed_drain(&e);
                    }
                }
                Err(crate::error::Error::from_sql_errors(all_errors))
            }
            Tokens::ColMetadata(_) => Err(crate::error::Error::UsageError(
                "Unexpected ColMetadata token encountered while reading rows. \
                     This typically indicates the API was not used correctly - \
                     you may need to call advance_to_rows() to advance to the next result set."
                    .to_string(),
            )),
            Tokens::Info(info_token) => {
                info!(?info_token);
                self.capture_info_message(&info_token);
                Ok(None)
            }
            Tokens::TabName | Tokens::ColInfo => Ok(None),
            _ => Err(crate::error::Error::ProtocolError(format!(
                "Unexpected token while finding the next row: {token:?}"
            ))),
        }
    }

    fn handle_row_done(
        &mut self,
        done: DoneToken,
        ended_with_done_in_proc: bool,
    ) -> TdsResult<Option<bool>> {
        info!("done while get_next_row: {:?}", done);

        if done.has_error() {
            return Err(crate::error::Error::ProtocolError(
                "Server reported error in DONE token without preceding ERROR token".to_string(),
            ));
        }

        let count = self.count_map.entry(done.cur_cmd).or_insert(0);
        *count = count.saturating_add(done.row_count);
        self.current_result_set_has_been_read_till_end = true;
        self.current_result_ended_with_done_in_proc = ended_with_done_in_proc;
        if !done.has_more() {
            info!("No more rows for current command: {:?}", done.cur_cmd);
            self.execution_context.set_has_open_batch(false);
        }
        Ok(Some(false))
    }

    /// Returns a clone of all [`ReturnValue`]s collected during the current
    /// batch — output parameters and UDF return values.
    ///
    /// Values accumulate as the token stream is read; call this after the
    /// result set is fully consumed (e.g. after [`close_query()`](Self::close_query)
    /// or after [`advance_to_rows()`](Self::advance_to_rows) returns `false`).
    pub fn get_return_values(&self) -> Vec<ReturnValue> {
        self.return_values.clone()
    }

    /// Returns the informational (INFO-token) messages captured from the
    /// current or most recent command's token stream — server `PRINT` output
    /// and low-severity `RAISERROR`/context notices.
    ///
    /// The buffer is reset at the start of each command, so this reflects only
    /// the most recent one. Messages are **retained even when that command
    /// returned an error**: a failed statement/RPC/batch surfaces its errors in
    /// [`Error::SqlServerError`](crate::error::Error::SqlServerError) whose
    /// `diagnostics.info_messages` is empty on the statement path, so any INFO it
    /// emitted must still be read from here. ([`close_query()`](Self::close_query)
    /// deliberately preserves the buffer for the same reason.)
    pub fn info_messages(&self) -> &[SqlInfoMessage] {
        &self.info_messages
    }

    /// Drains and returns the captured informational messages, leaving the
    /// buffer empty.
    ///
    /// Same lifecycle as [`info_messages()`](Self::info_messages): the buffer
    /// reflects the current/most-recent command, is populated even when that
    /// command errored (statement-path errors carry no INFO in
    /// [`Error::SqlServerError`](crate::error::Error::SqlServerError)), and is
    /// reset at the next command's start — so drain it before issuing the next
    /// command if you need the messages.
    pub fn take_info_messages(&mut self) -> Vec<SqlInfoMessage> {
        std::mem::take(&mut self.info_messages)
    }

    pub(crate) fn extend_info_messages(&mut self, messages: Vec<SqlInfoMessage>) {
        self.info_messages.extend(messages);
    }

    fn capture_info_message(&mut self, token: &crate::token::tokens::InfoToken) {
        self.info_messages.push(SqlInfoMessage::from(token));
    }

    /// Resets the informational-message buffer at the start of a new command so
    /// [`info_messages()`](Self::info_messages) reflects only that command.
    ///
    /// Call this at the top of every public token-consuming command, before
    /// consuming the response (and before `check_and_reconnect` where
    /// applicable): a transparent reconnect repopulates login messages for the
    /// new session *after* this point, so those remain visible as part of the
    /// command that triggered the reconnect.
    fn begin_command(&mut self) {
        self.settle_abandoned_reset_verification();
        self.interrupted_read_settled = false;
        self.info_messages.clear();
        // A token parked by the look-ahead belongs to the previous response;
        // replaying it here would desynchronize this command's reader.
        self.parked_token = None;
        // Clear output parameters / return values from the previous command so a
        // fully-navigated prior RPC does not leave `get_return_values()` /
        // `retrieve_output_params()` reporting stale values for this new command.
        self.return_values.clear();
        // Every execution RPC path (plain batch, sp_executesql, sp_execute,
        // sp_prepexec, stored proc) funnels through here, so reset the
        // affected-row count for the new command. A prior DML count must not
        // leak into `SQLRowCount` when this command reports none (DDL /
        // `SET NOCOUNT ON` / SELECT).
        self.last_rows_affected = -1;
        self.dml_result_counts.clear();
    }

    /// The live server handle the client holds for `statement_id`, if any.
    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub fn prepared_handle_for_test(&self, statement_id: StatementId) -> Option<i32> {
        self.prepared_handles.get(&statement_id).copied()
    }

    fn abort_pending_prepare_capture(&mut self) {
        self.pending_capture = None;
        self.pending_prepared_param_encryption = None;
    }

    /// Retrieves a snapshot of the output parameters (including return values)
    /// that have been retrieved from the result stream.
    ///
    /// Returns `None` if there are no output parameters, otherwise returns
    /// a reference to the collected return values.
    pub fn retrieve_output_params(&self) -> TdsResult<Option<&Vec<ReturnValue>>> {
        if self.return_values.is_empty() {
            Ok(None)
        } else {
            Ok(Some(&self.return_values))
        }
    }

    /// Drains all remaining result sets and resets the client for the next request.
    ///
    /// Any unread rows and result sets are consumed so the TDS stream is left in
    /// a clean state. Must be called (or the result sets fully iterated) before
    /// executing another query on the same connection.
    ///
    /// If the drain itself fails, the client state is reset regardless and the
    /// connection is retired: a drain that stops partway leaves the reader at an
    /// unknown offset in the response, and a TDS stream cannot be
    /// resynchronized from there. The error is returned to the caller and
    /// pooled consumers discard the connection rather than reusing it. See
    /// [`Self::retire_desynchronized_connection`] for what retirement does not
    /// cover.
    #[instrument(skip(self), level = "info")]
    pub async fn close_query(&mut self) -> TdsResult<()> {
        self.interrupted_read_settled = false;
        if !self.has_open_batch() {
            return Ok(());
        }
        // call next row to consume any remaining tokens
        let drain_result = loop {
            match self.advance_to_rows().await {
                Ok(true) => continue,
                Ok(false) => break Ok(()),
                Err(error) => break Err(error),
            }
        };
        if drain_result.is_ok() {
            info!("No more rows to consume.");
        }
        // Reset the current metadata, return values, and timeout/cancel state.
        // Note: `info_messages` is intentionally NOT cleared here. Draining the
        // trailing token stream above can surface INFO/warning messages (e.g. a
        // PRINT after the last result set), and the caller drains them via
        // `take_info_messages()` after this returns (see the ODBC
        // `drain_and_release` path). Clearing them here would discard them.
        // The sp_prepexec @handle, if any, was captured during the drain above
        // (see push_return_value) and survives this clear.
        self.current_metadata = None;
        self.current_result_ended_with_done_in_proc = false;
        self.return_values.clear();
        self.abort_pending_prepare_capture();
        self.remaining_request_timeout = None;
        self.cancel_handle = None;
        self.active_row_read_state = ActiveRowReadState::Idle;
        self.row_already_positioned = false;
        self.parked_token = None;
        self.current_command_ce_setting = ExecutionColumnEncryptionSetting::UseConnectionSetting;
        self.execution_context.set_has_open_batch(false);

        if let Err(error) = drain_result {
            // A server-reported error is different: the batch ran and failed,
            // and the reader is still on a token boundary, so retiring would
            // poison a healthy pooled connection every time a batch ends in
            // RAISERROR.
            //
            // `SqlServerError` alone does not prove the stream is intact — the
            // ERROR-token handlers build one even when their own drain fails.
            // Those arms call `retire_after_failed_drain` themselves, so
            // by the time such an error reaches here the transport is already
            // marked dead and this exemption cannot revive it.
            //
            // The state above is still cleared first: leaving the batch open
            // would mask this error behind `ALREADY_EXECUTING_ERROR` on every
            // later call, which is what made the original failure look like a
            // permanent wedge.
            if !matches!(error, crate::error::Error::SqlServerError { .. }) {
                self.retire_after_failed_drain(&error);
            }
            return Err(error);
        }
        Ok(())
    }

    /// Close the underlying transport, ending the TDS session.
    #[instrument(skip(self), level = "info")]
    pub async fn close_connection(&mut self) -> TdsResult<()> {
        // An intentional close is not a recoverable disconnect: disable recovery
        // so a later call on a lingering handle cannot silently resurrect it.
        self.recovery_context.session_recovery_negotiated = false;
        self.transport.mark_known_dead();
        self.transport.close_transport().await?;
        Ok(())
    }

    /// Sends ATTENTION and attempts to drain the active response through DONE_ATTN.
    ///
    /// This method:
    /// 1. Send MT_ATTN (0x06) packet to cancel the current operation
    /// 2. Drain unread row and control tokens using the current parser metadata
    /// 3. Apply state-bearing control tokens and clear the cancelled result
    /// 4. Stop at a DONE token with the ATTN (0x0020) status flag
    ///
    /// Draining is required before reuse because ATTENTION is asynchronous; a
    /// later command would otherwise consume bytes from the cancelled response.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum time for sending ATTENTION and draining through its
    ///   acknowledgement
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - Attention acknowledged by server
    /// * `Ok(false)` - Attention sent but timeout expired waiting for ACK
    /// * `Err(_)` - Error sending attention or reading response
    #[instrument(skip(self), level = "info")]
    pub async fn send_attention_with_timeout(&mut self, timeout: Duration) -> TdsResult<bool> {
        self.interrupted_read_settled = false;
        let parser_context = match self.current_metadata.as_ref() {
            Some(metadata) => ParserContext::ColumnMetadata(Arc::clone(metadata), None),
            None => ParserContext::ColumnEncryption(
                self.negotiated_settings.is_column_encryption_supported(),
            ),
        };
        let result = self
            .transport
            .send_attention_with_timeout(&parser_context, timeout)
            .await;
        self.consume_attention_settlement();
        self.normalize_after_attention();
        result
    }

    /// Check if the connection has an active transaction.
    ///
    /// A transaction is considered active when a BEGIN TRANSACTION has been
    /// executed and no corresponding COMMIT or ROLLBACK has occurred.
    ///
    /// # Returns
    ///
    /// * `true` - if a transaction is active on this connection
    /// * `false` - if no transaction is active (autocommit mode)
    pub fn has_active_transaction(&self) -> bool {
        self.execution_context.has_active_transaction()
    }

    /// Returns whether session recovery (idle connection resiliency) was
    /// negotiated with the server during login.
    ///
    /// When `true`, the driver will transparently attempt to reconnect and
    /// restore session state if a dead connection is detected before executing
    /// a command — provided the session is in a recoverable state (no open
    /// transactions, etc.).
    pub fn is_session_recovery_enabled(&self) -> bool {
        self.recovery_context.session_recovery_negotiated
    }

    /// Test only.
    /// Returns the number of times this connection has been successfully
    /// recovered after detecting a dead connection.
    ///
    /// The count is incremented each time [`reconnect()`] completes
    /// successfully, including session-state restoration and server-property
    /// validation.
    #[cfg(any(test, feature = "test-util"))]
    #[doc(hidden)]
    pub fn connection_recovery_count(&self) -> u32 {
        self.recovery_context.recovery_count
    }

    /// Begin a new transaction with the given isolation level and optional name.
    ///
    /// Fails if a batch is currently executing. Use [`has_active_transaction`](Self::has_active_transaction)
    /// to check whether a transaction is already open. Runs unbounded — see
    /// [`begin_transaction_with_options`](Self::begin_transaction_with_options)
    /// to bound the wait (e.g. with a statement's `SQL_ATTR_QUERY_TIMEOUT`).
    #[instrument(skip(self), level = "info")]
    pub async fn begin_transaction(
        &mut self,
        isolation_level: TransactionIsolationLevel,
        name: Option<String>,
    ) -> TdsResult<()> {
        self.begin_transaction_with_options(isolation_level, name, ())
            .await
    }

    /// Like [`begin_transaction`](Self::begin_transaction), but honors
    /// `options` — in particular its timeout, so an implicit transaction begin
    /// (e.g. the autocommit-off prologue a driver runs before every statement)
    /// cannot wait past a caller-supplied deadline. Mirrors msodbcsql's
    /// `CheckOptions`, which passes `GetQueryTimeOut(lpstmt)` to
    /// `ExecTMRImmediate` (`sqlccmd.cpp:10572-10586`).
    #[instrument(skip(self, options), level = "info")]
    pub async fn begin_transaction_with_options<'a>(
        &mut self,
        isolation_level: TransactionIsolationLevel,
        name: Option<String>,
        options: impl Into<ExecuteOptions<'a>>,
    ) -> TdsResult<()> {
        if self.command_is_busy() {
            return Err(UsageError(
                "Cannot begin transaction while another batch is executing.".to_string(),
            ));
        }
        let ExecuteOptions {
            timeout, cancel, ..
        } = options.into();

        self.begin_command();
        let reconnect_elapsed = self.check_and_reconnect(timeout, cancel).await?;
        let budget = Self::deduct_timeout(timeout, reconnect_elapsed);
        let resolved = budget.into_timeout()?;
        let timeout_sec = resolved.seconds();
        self.remaining_request_timeout = resolved.duration();
        self.cancel_handle = cancel.map(|handle| handle.child_handle());

        let transaction_params = TransactionManagementType::Begin(CreateTxnParams {
            level: isolation_level,
            name,
        });
        let transaction =
            TransactionManagementRequest::new(transaction_params, &self.execution_context);
        let mut packet_writer =
            transaction.create_packet_writer(self.transport.as_writer(), timeout_sec, cancel);
        transaction.serialize(&mut packet_writer).await?;

        self.consume_transaction_response().await?;

        Ok(())
    }

    /// Create a savepoint within the current transaction.
    ///
    /// The savepoint `name` can later be passed to
    /// [`rollback_transaction`](Self::rollback_transaction) to partially undo work.
    #[instrument(skip(self), level = "info")]
    pub async fn save_transaction(&mut self, name: String) -> TdsResult<()> {
        if self.command_is_busy() {
            return Err(UsageError(
                "Cannot save transaction while another batch is executing.".to_string(),
            ));
        }
        self.begin_command();
        let transaction = TransactionManagementRequest::new(
            TransactionManagementType::Save(name),
            &self.execution_context,
        );
        let mut packet_writer =
            transaction.create_packet_writer(self.transport.as_writer(), None, None);
        transaction.serialize(&mut packet_writer).await?;

        self.consume_transaction_response().await?;

        Ok(())
    }

    /// Commit the current transaction.
    ///
    /// If `create_txn_params` is provided, a new transaction begins immediately
    /// after the commit (atomic commit-and-begin).
    #[instrument(skip(self), level = "info")]
    pub async fn commit_transaction(
        &mut self,
        name: Option<String>,
        create_txn_params: Option<CreateTxnParams>,
    ) -> TdsResult<()> {
        if self.command_is_busy() {
            return Err(UsageError(
                "Cannot commit transaction while another batch is executing.".to_string(),
            ));
        }
        self.begin_command();
        let transaction = TransactionManagementRequest::new(
            TransactionManagementType::Commit {
                name,
                create_txn_params,
            },
            &self.execution_context,
        );
        let mut packet_writer =
            transaction.create_packet_writer(self.transport.as_writer(), None, None);
        transaction.serialize(&mut packet_writer).await?;

        self.consume_transaction_response().await?;

        Ok(())
    }

    /// Roll back the current transaction, or roll back to a named savepoint.
    ///
    /// If `create_txn_params` is provided, a new transaction begins immediately
    /// after the rollback.
    #[instrument(skip(self), level = "info")]
    pub async fn rollback_transaction(
        &mut self,
        name: Option<String>,
        create_txn_params: Option<CreateTxnParams>,
    ) -> TdsResult<()> {
        if self.command_is_busy() {
            return Err(UsageError(
                "Cannot rollback transaction while another batch is executing.".to_string(),
            ));
        }
        self.begin_command();
        let transaction = TransactionManagementRequest::new(
            TransactionManagementType::Rollback {
                name,
                create_txn_params,
            },
            &self.execution_context,
        );
        let mut packet_writer =
            transaction.create_packet_writer(self.transport.as_writer(), None, None);
        transaction.serialize(&mut packet_writer).await?;

        self.consume_transaction_response().await?;

        Ok(())
    }

    /// Retrieve the DTC (Distributed Transaction Coordinator) network address from the server.
    ///
    /// Returns a result set that can be iterated with the normal row-reading API.
    #[instrument(skip(self), level = "info")]
    pub async fn get_dtc_address(&mut self) -> TdsResult<()> {
        if self.command_is_busy() {
            return Err(UsageError(
                "Cannot get DTC address while another batch is executing.".to_string(),
            ));
        }
        self.begin_command();
        let transaction = TransactionManagementRequest::new(
            TransactionManagementType::GetDtcAddress,
            &self.execution_context,
        );
        let mut packet_writer =
            transaction.create_packet_writer(self.transport.as_writer(), None, None);
        transaction.serialize(&mut packet_writer).await?;

        // GetDtcAddress returns a result set, unlike other transaction commands
        // Set up execution state for result iteration (similar to execute())
        let metadata = self.next_rowset().await?;
        if metadata.is_none() {
            self.execution_context.set_has_open_batch(false);
            self.current_metadata = None;
        } else {
            self.current_metadata = metadata;
            self.execution_context.set_has_open_batch(true);
        }

        Ok(())
    }

    #[instrument(skip(self), level = "info")]
    pub(crate) async fn consume_transaction_response(&mut self) -> TdsResult<()> {
        let mut collected_errors: Vec<SqlErrorInfo> = Vec::new();
        loop {
            let token = self.next_response_token(&ParserContext::None(())).await?;

            match token {
                Tokens::DoneInProc(done) | Tokens::DoneProc(done) | Tokens::Done(done) => {
                    info!("done while consume_transaction_response: {:?}", done);

                    if done.has_error() && collected_errors.is_empty() {
                        return Err(crate::error::Error::ProtocolError(
                            "Server reported error in DONE token without preceding ERROR token"
                                .to_string(),
                        ));
                    }

                    let count = self.count_map.entry(done.cur_cmd).or_insert(0);
                    // Use saturating_add to prevent integer overflow from malicious/corrupted TDS responses
                    *count = count.saturating_add(done.row_count);

                    if !done.has_more() {
                        info!("No more rows for current command: {:?}", done.cur_cmd);
                        if !collected_errors.is_empty() {
                            return Err(crate::error::Error::from_sql_errors(collected_errors));
                        }
                    }
                    break;
                }
                Tokens::Error(error_token) => {
                    info!(?error_token);
                    collected_errors.push(self.record_error_token(&error_token));
                    continue;
                }
                Tokens::Info(info_token) => {
                    info!(?info_token);
                    self.capture_info_message(&info_token);
                    continue;
                }
                Tokens::EnvChange(env_change) => {
                    info!(?env_change);
                    if env_change.sub_type == EnvChangeTokenSubType::ResetConnection {
                        self.on_reset_connection_ack();
                    }
                    self.execution_context
                        .capture_change_property(&env_change, &mut self.negotiated_settings)?;
                    continue;
                }
                Tokens::SessionState(session_state) => {
                    self.recovery_context
                        .process_session_state(&session_state)?;
                    continue;
                }
                _ => {
                    return Err(crate::error::Error::ProtocolError(format!(
                        "Unexpected token while reading transaction request response: {token:?}"
                    )));
                }
            }
        }

        Ok(())
    }
}

impl ResultSet for TdsClient {
    fn get_metadata(&self) -> &Vec<ColumnMetadata> {
        // If no metadata is available, return an empty vector
        // This can happen if get_metadata is called before executing a query
        // or if the query didn't return any result sets
        self.current_metadata
            .as_ref()
            .map(|m| &m.columns)
            .unwrap_or(&self.empty_metadata)
    }

    fn next_row(&mut self) -> impl Future<Output = TdsResult<Option<Vec<ColumnValues>>>> + Send {
        self.get_next_row()
    }

    fn next_row_into(
        &mut self,
        writer: &mut (dyn RowWriter + Send),
    ) -> impl Future<Output = TdsResult<bool>> + Send {
        TdsClient::next_row_into(self, writer)
    }

    fn maybe_has_unread_rows(&self) -> bool {
        !self.current_result_set_has_been_read_till_end
    }

    fn close(&mut self) -> impl Future<Output = TdsResult<()>> + Send {
        self.close_query()
    }
}

/// Opaque identity for a managed prepared statement.
///
/// Issued by [`TdsClient::execute_prepared`] the first time a statement is
/// materialized, and used to key the issuing client's private server-handle
/// map. Ids are unique and never reused within the lifetime of the client that
/// issued them.
///
/// They are **not** globally unique across clients yet (AB#47098): the counter
/// restarts from the same value on each client, so a statement must only be
/// executed or unprepared with the [`TdsClient`] that materialized it. Using it
/// with a different client can alias that client's unrelated handle instead of
/// re-preparing. ODBC upholds this because an `HSTMT` is bound to one
/// connection; direct `mssql-tds` consumers must not share a statement across
/// clients.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StatementId(u64);

#[cfg(any(test, feature = "test-util"))]
impl StatementId {
    /// Builds a `StatementId` from a raw value, for tests that need to seed a
    /// statement's identity without a live server.
    #[doc(hidden)]
    pub fn from_raw_for_test(raw: u64) -> Self {
        Self(raw)
    }
}

/// A logical prepared statement: the SQL to (re)prepare plus its client-issued
/// identity once materialized.
///
/// The server handle is an implementation detail the [`TdsClient`] owns and
/// resolves from [`id`](Self::id) — callers never touch raw handle ids or
/// epochs. If the connection reconnects, the next
/// [`execute_prepared`](TdsClient::execute_prepared) transparently re-prepares
/// against the new session.
///
// Not `Clone`: clones would share one id, so unpreparing either would silently
// unmaterialize the other.
#[derive(Debug)]
pub struct PreparedStatement {
    sql: String,
    id: Option<StatementId>,
}

impl PreparedStatement {
    /// Creates an unmaterialized prepared statement for `sql`. The server handle
    /// is created lazily on the first [`TdsClient::execute_prepared`].
    pub fn new(sql: impl Into<String>) -> Self {
        Self {
            sql: sql.into(),
            id: None,
        }
    }

    /// The client-issued identity, once the statement has been materialized by
    /// [`TdsClient::execute_prepared`]. `None` before the first execute.
    pub fn id(&self) -> Option<StatementId> {
        self.id
    }

    /// Removes and returns the statement's identity, leaving it unmaterialized
    /// with its SQL intact. The caller owns releasing the associated server
    /// handle via [`TdsClient::unprepare`].
    pub fn take_id(&mut self) -> Option<StatementId> {
        self.id.take()
    }

    /// The SQL text this statement prepares.
    pub fn sql(&self) -> &str {
        &self.sql
    }
}

#[cfg(any(test, feature = "test-util"))]
impl PreparedStatement {
    /// Builds a statement already carrying an identity, for tests that need to
    /// exercise handle-lifecycle transitions without a live server.
    #[doc(hidden)]
    pub fn materialized_for_test(sql: impl Into<String>, id: StatementId) -> Self {
        Self {
            sql: sql.into(),
            id: Some(id),
        }
    }
}

/// Per-execution options shared by every `execute*` entry point on
/// [`TdsClient`].
///
/// All fields default to "inherit the connection's behavior", so
/// [`ExecuteOptions::default()`] (or passing `()`, which converts via
/// [`From`]) reproduces the implicit defaults. New per-command capabilities are
/// added here as new defaulted fields — never as new methods or changed
/// signatures — keeping the `execute*` surface forward-compatible.
#[derive(Default, Clone)]
pub struct ExecuteOptions<'a> {
    /// Per-request timeout in seconds. Both `None` and `Some(0)` mean no
    /// client-side timeout (unlimited); a positive value bounds the command,
    /// with connection-recovery time charged against it.
    pub timeout: Option<u32>,
    /// Optional [`CancelHandle`] for cooperative cancellation. A child token is
    /// derived so cancelling aborts the request without tearing down the
    /// connection.
    pub cancel: Option<&'a CancelHandle>,
    /// Per-command Always Encrypted override. Defaults to
    /// [`ExecutionColumnEncryptionSetting::UseConnectionSetting`] (inherit the
    /// connection). Only has effect when the server acknowledged the Column
    /// Encryption feature during login.
    pub column_encryption: ExecutionColumnEncryptionSetting,
}

impl<'a> ExecuteOptions<'a> {
    /// Creates default options (inherit all connection behavior).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a per-request timeout, in seconds. `0` means unlimited (no
    /// deadline), the same as the `None` default — including on the managed
    /// [`execute_prepared`](TdsClient::execute_prepared) /
    /// [`unprepare`](TdsClient::unprepare) paths, where `timeout_secs(0)` now
    /// runs unbounded instead of returning a timeout error.
    pub fn timeout_secs(mut self, seconds: u32) -> Self {
        self.timeout = Some(seconds);
        self
    }

    /// Attaches a cancellation handle.
    pub fn cancel(mut self, handle: &'a CancelHandle) -> Self {
        self.cancel = Some(handle);
        self
    }

    /// Overrides the Always Encrypted behavior for this command only.
    pub fn column_encryption(mut self, setting: ExecutionColumnEncryptionSetting) -> Self {
        self.column_encryption = setting;
        self
    }
}

impl From<()> for ExecuteOptions<'_> {
    fn from(_: ()) -> Self {
        Self::default()
    }
}

/// The result the client is positioned on after an `execute*` call or an
/// [`advance()`](TdsClient::advance).
///
/// This is the lossless, statement-wise view of a batch: every statement that
/// returns rows, carries an update count, or produced a message is surfaced as its
/// own result (matching msodbcsql's `SQLMoreResults` and JDBC's
/// `getMoreResults`/`getUpdateCount`). Consumers that only care about
/// row-returning result sets can collapse no-row statements with
/// [`advance_to_rows()`](TdsClient::advance_to_rows). A pure no-op statement
/// with neither a count nor a message (e.g. a bare `CREATE TABLE`) is collapsed
/// and never surfaces as [`NoRows`](Self::NoRows).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StatementResult {
    /// A row-returning result set (e.g. `SELECT`). Column metadata is available
    /// via [`TdsClient::get_metadata`] and rows via the [`ResultSet`] API.
    Rows,
    /// A statement that produced no result set but is still individually
    /// navigable. `rows_affected` is `Some(n)` when the statement's DONE token
    /// carried an update count (DML), or `None` for a message-only statement
    /// (`PRINT` / low-severity `RAISERROR`) or plain DDL. Messages are drained
    /// separately via [`take_info_messages`](TdsClient::take_info_messages).
    NoRows {
        /// Rows affected, when the DONE token carried a COUNT that was not
        /// tagged `SQLSELECT` — see
        /// [`TdsClient::last_rows_affected`] for why assignment counts are
        /// excluded. `None` otherwise, including for a `SQLSELECT` count that
        /// only surfaces because the statement also raised a message.
        rows_affected: Option<u64>,
    },
    /// No more statements remain in the batch; the connection is idle.
    End,
}

/// Internal boundary kind produced by
/// [`advance_to_result_boundary`](TdsClient::advance_to_result_boundary),
/// before it is mapped to the public [`StatementResult`].
#[derive(Debug)]
enum ResultBoundaryKind {
    /// A row-returning result set; carries its column metadata.
    RowSet(Arc<ColMetadataToken>),
    /// A no-row statement (DML count, message-only, or DDL).
    NoRows { rows_affected: Option<u64> },
    /// End of batch.
    End,
}

/// Async result set iteration through statically dispatched futures.
///
/// The returned futures are native, unboxed futures with an explicit [`Send`]
/// guarantee.
///
/// # Dyn compatibility
///
/// This trait is intentionally not dyn-compatible and cannot be used through
/// `dyn ResultSet`. This is a breaking change for trait-object consumers and for
/// implementations written with `#[async_trait]`; concrete call sites can keep
/// awaiting the methods unchanged, while implementations must return native
/// `Send` futures.
pub trait ResultSet {
    /// Returns the metadata of the result set.
    /// This metadata includes information about the columns in the result set.
    fn get_metadata(&self) -> &Vec<ColumnMetadata>;

    /// Returns the next row of data as a vector of column values.
    /// If there is no more data, it returns None.
    fn next_row(&mut self) -> impl Future<Output = TdsResult<Option<Vec<ColumnValues>>>> + Send;

    /// Decodes the next row directly into a [`RowWriter`], returning `true` if
    /// a row was written or `false` when the result set is exhausted.
    ///
    /// This is the bulk push path: it decodes a full row into `writer` and does
    /// not pause. The ODBC column-at-a-time pull path uses the client cursor
    /// (`next_row_cursor` / `read_row_column`) instead.
    /// Concrete [`TdsClient`] receivers use [`TdsClient::next_row_into`] to keep
    /// the writer statically dispatched. Calls through this trait remain
    /// statically dispatched because [`ResultSet`] is not dyn-compatible.
    ///
    /// # Errors
    ///
    /// Returns a usage error if called while a pull-cursor row is still
    /// partially read. Draining that row here would silently discard it and
    /// return the *next* one, so callers must first finish the row with
    /// `next_row_cursor`. A fully-consumed or absent row is fine.
    fn next_row_into(
        &mut self,
        writer: &mut (dyn RowWriter + Send),
    ) -> impl Future<Output = TdsResult<bool>> + Send;

    /// Returns `true` if the result set may still contain unread rows.
    fn maybe_has_unread_rows(&self) -> bool;

    /// Iterates over the result set, and marks it as closed. After calling close, the next_row method,
    /// will always return None.
    fn close(&mut self) -> impl Future<Output = TdsResult<()>> + Send;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::connection::client_context::ClientContext;
    use crate::connection::cursor_ops::CursorClient;
    use crate::connection::transport::network_transport::TransportSslHandler;
    use crate::connection::transport::tds_transport::TdsTransport;
    use crate::core::{CancelHandle, TdsResult};
    use crate::datatypes::row_writer::RowWriter;
    use crate::io::packet_reader::TdsPacketReader;
    use crate::io::reader_writer::{NetworkReader, NetworkWriter};
    use crate::io::token_stream::{
        ColumnPolicy, ParserContext, RowHeader, RowPauseState, RowReadResult, TdsTokenStreamReader,
    };
    use crate::message::parameters::rpc_parameters::StreamedSqlType;
    use crate::test_client_support::byte_stream::tds_client_over_raw_bytes as client_over_bytes;
    use crate::test_client_support::byte_stream::tds_client_over_raw_bytes_with_column_encryption as client_over_bytes_with_ae;
    use crate::test_packet_support::{
        TestPacketBuilder, create_network_transport_with_data,
        create_network_transport_with_live_peer,
        create_network_transport_with_live_peer_capturing_writes,
    };
    use crate::token::tokens::{
        ColMetadataToken, CurrentCommand, DoneStatus, DoneToken, InfoToken, ReturnStatusToken,
        TokenType, Tokens,
    };
    use async_trait::async_trait;
    use std::collections::VecDeque;

    // ── Minimal mock transport for reconnect() unit tests ──

    #[derive(Debug)]
    struct TestTransport {
        closed: bool,
        pending_tokens: VecDeque<Tokens>,
        reset_mode: ResetConnectionMode,
        /// Mirrors the production writer's dispatch record so client tests can
        /// drive acknowledgement verification without a real socket.
        reset_dispatched: bool,
        /// Every byte handed to `send` (request framing + payload), so tests can
        /// assert what was actually written to the wire.
        sent: Arc<std::sync::Mutex<Vec<u8>>>,
        packet_data: Vec<u8>,
        packet_pos: usize,
        /// Results the mock replays from `resume_row_into`, so tests can drive
        /// `read_row_column` down a specific arm (e.g. a `PlpPaused` result that
        /// makes the cursor emit `CursorColumn::PlpStreaming`).
        resume_results: VecDeque<RowReadResult>,
        /// When set, the next (and every subsequent) `send` fails, simulating a
        /// mid-message wire failure. Shared so a test can flip it after setup.
        send_should_fail: Arc<std::sync::atomic::AtomicBool>,
        /// When set, `send` never returns, so a test can drive a write deadline
        /// without a real stalled peer.
        send_should_hang: Arc<std::sync::atomic::AtomicBool>,
        /// Fires after the first successful send, allowing a multi-packet
        /// request to be cancelled while the server holds its first packet.
        cancel_after_send: Option<tokio_util::sync::CancellationToken>,
        /// Attentions requested, so a test can tell the cancel-a-sent-request
        /// path from the withdraw-a-partial-one path.
        attentions: Arc<std::sync::atomic::AtomicUsize>,
        /// Cached liveness flag toggled by `mark_known_dead`, surfaced through
        /// `connection_known_dead` so tests can assert the fatal-error path.
        known_dead: bool,
        receive_error: Option<crate::error::Error>,
        sync_header_available: bool,
        sync_columns: VecDeque<ColumnValues>,
        encryption_setting: NegotiatedEncryptionSetting,
        /// The `remaining_request_timeout` handed to each `receive_token`, so a
        /// test can assert which budget a read ran under without waiting for one
        /// to elapse.
        receive_timeouts: Arc<std::sync::Mutex<Vec<Option<Duration>>>>,
    }

    impl TestTransport {
        fn new() -> Self {
            Self {
                closed: false,
                pending_tokens: VecDeque::new(),
                reset_mode: ResetConnectionMode::None,
                reset_dispatched: false,
                sent: Arc::new(std::sync::Mutex::new(Vec::new())),
                packet_data: Vec::new(),
                packet_pos: 0,
                resume_results: VecDeque::new(),
                send_should_fail: Arc::new(std::sync::atomic::AtomicBool::new(false)),
                send_should_hang: Arc::new(std::sync::atomic::AtomicBool::new(false)),
                cancel_after_send: None,
                attentions: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
                known_dead: false,
                receive_error: None,
                sync_header_available: false,
                sync_columns: VecDeque::new(),
                encryption_setting: NegotiatedEncryptionSetting::NoEncryption,
                receive_timeouts: Arc::new(std::sync::Mutex::new(Vec::new())),
            }
        }

        fn with_tokens(tokens: Vec<Tokens>) -> Self {
            Self {
                pending_tokens: VecDeque::from(tokens),
                ..Self::new()
            }
        }

        fn with_tokens_then_error(tokens: Vec<Tokens>, error: crate::error::Error) -> Self {
            Self {
                receive_error: Some(error),
                ..Self::with_tokens(tokens)
            }
        }

        fn with_packet_data(packet_data: Vec<u8>) -> Self {
            Self {
                packet_data,
                ..Self::new()
            }
        }

        fn take_packet_bytes(&mut self, count: usize) -> TdsResult<&[u8]> {
            if self.packet_pos + count > self.packet_data.len() {
                return Err(crate::error::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "End of data",
                )));
            }
            let slice = &self.packet_data[self.packet_pos..self.packet_pos + count];
            self.packet_pos += count;
            Ok(slice)
        }
    }

    #[async_trait]
    impl TdsTokenStreamReader for TestTransport {
        fn try_receive_row_header(
            &mut self,
            context: &ParserContext,
        ) -> TdsResult<Option<RowPauseState>> {
            if !self.sync_header_available {
                return Ok(None);
            }
            self.sync_header_available = false;
            let ParserContext::ColumnMetadata(metadata, decryptor) = context else {
                return Ok(None);
            };
            Ok(Some(RowPauseState {
                next_column_index: 0,
                metadata: Arc::clone(metadata),
                nbc_null_bitmap: None,
                decryptor: decryptor.clone(),
            }))
        }

        fn try_read_buffered_column(
            &mut self,
            _pause_state: &RowPauseState,
            _target: usize,
        ) -> TdsResult<Option<ColumnValues>> {
            Ok(self.sync_columns.pop_front())
        }

        async fn receive_token(
            &mut self,
            _context: &ParserContext,
            remaining_request_timeout: Option<Duration>,
            cancel_handle: Option<&CancelHandle>,
        ) -> TdsResult<Tokens> {
            self.receive_timeouts
                .lock()
                .unwrap()
                .push(remaining_request_timeout);
            // Mirrors the production readers, which run every read under the
            // handle. Without this a cancelled read looks identical to a healthy
            // one and tests cannot tell the two apart.
            if let Some(handle) = cancel_handle
                && handle.cancel_token.is_cancelled()
            {
                return Err(crate::error::Error::OperationCancelledError(
                    "Request was cancelled".to_string(),
                ));
            }
            if let Some(tok) = self.pending_tokens.pop_front() {
                return Ok(tok);
            }
            if let Some(error) = self.receive_error.take() {
                return Err(error);
            }
            Err(crate::error::Error::ConnectionClosed("test".to_string()))
        }

        async fn receive_row_into(
            &mut self,
            _context: &ParserContext,
            _remaining_request_timeout: Option<Duration>,
            _cancel_handle: Option<&CancelHandle>,
            _plan: ColumnPolicy,
            _writer: &mut (dyn RowWriter + Send),
        ) -> TdsResult<RowReadResult> {
            // The mock has no row bytes to materialize, so it replays the queued
            // tokens as control tokens (e.g. a terminal DONE). This lets drain
            // paths — which read rows until the result set's DONE — be exercised
            // without a live server. Running dry is a protocol error, mirroring a
            // closed connection.
            if let Some(tok) = self.pending_tokens.pop_front() {
                return Ok(RowReadResult::Token(tok));
            }
            Err(crate::error::Error::ConnectionClosed("test".to_string()))
        }

        async fn receive_row_header(
            &mut self,
            _context: &ParserContext,
            _remaining_request_timeout: Option<Duration>,
            _cancel_handle: Option<&CancelHandle>,
        ) -> TdsResult<RowHeader> {
            // Mirrors `receive_row_into`: the mock replays queued control tokens
            // and has no row bytes, so a row header is only ever a `Token`.
            if let Some(tok) = self.pending_tokens.pop_front() {
                return Ok(RowHeader::Token(tok));
            }
            Err(crate::error::Error::ConnectionClosed("test".to_string()))
        }

        async fn resume_row_into(
            &mut self,
            _pause_state: RowPauseState,
            _remaining_request_timeout: Option<Duration>,
            _cancel_handle: Option<&CancelHandle>,
            _plan: ColumnPolicy,
            _writer: &mut (dyn RowWriter + Send),
        ) -> TdsResult<RowReadResult> {
            if let Some(result) = self.resume_results.pop_front() {
                return Ok(result);
            }
            Err(crate::error::Error::ConnectionClosed("test".to_string()))
        }

        async fn read_active_plp_bytes(
            &mut self,
            _plp_state: &mut PlpPauseState,
            _remaining_request_timeout: Option<Duration>,
            _cancel_handle: Option<&CancelHandle>,
            _out: &mut [u8],
        ) -> TdsResult<usize> {
            Err(crate::error::Error::ConnectionClosed("test".to_string()))
        }
    }

    #[async_trait]
    impl TransportSslHandler for TestTransport {
        async fn enable_ssl(&mut self) -> TdsResult<()> {
            Ok(())
        }
        async fn disable_ssl(&mut self) -> TdsResult<()> {
            Ok(())
        }
    }

    #[async_trait]
    impl NetworkWriter for TestTransport {
        async fn send(&mut self, data: &[u8]) -> TdsResult<()> {
            if self.closed {
                return Err(crate::error::Error::ConnectionClosed(
                    "test transport is closed".to_string(),
                ));
            }
            if self
                .send_should_fail
                .load(std::sync::atomic::Ordering::SeqCst)
            {
                // `NetworkTransport::send` retires the transport on a write
                // failure; a mock that did not would let tests treat a broken
                // socket as reusable.
                self.known_dead = true;
                return Err(crate::error::Error::ConnectionClosed(
                    "injected send failure".to_string(),
                ));
            }
            if self
                .send_should_hang
                .load(std::sync::atomic::Ordering::SeqCst)
            {
                std::future::pending::<()>().await;
            }
            self.sent.lock().unwrap().extend_from_slice(data);
            if let Some(cancel) = self.cancel_after_send.take() {
                cancel.cancel();
            }
            Ok(())
        }
        fn packet_size(&self) -> u32 {
            4096
        }
        fn get_encryption_setting(&self) -> crate::core::NegotiatedEncryptionSetting {
            self.encryption_setting
        }
        fn set_reset_mode(&mut self, mode: ResetConnectionMode) {
            self.reset_mode = mode;
            self.reset_dispatched = false;
        }
        fn take_reset_mode(&mut self) -> ResetConnectionMode {
            std::mem::replace(&mut self.reset_mode, ResetConnectionMode::None)
        }
        fn note_reset_dispatched(&mut self) {
            self.reset_dispatched = true;
        }
        fn take_reset_dispatched(&mut self) -> bool {
            std::mem::replace(&mut self.reset_dispatched, false)
        }
    }

    #[async_trait]
    impl NetworkReader for TestTransport {
        fn packet_size(&self) -> u32 {
            4096
        }
    }

    #[async_trait]
    impl TdsTransport for TestTransport {
        fn as_writer_ref(&self) -> &dyn NetworkWriter {
            self
        }

        fn as_writer(&mut self) -> &mut dyn NetworkWriter {
            self
        }
        fn reset_reader(&mut self) {}
        fn packet_size(&self) -> u32 {
            4096
        }
        async fn close_transport(&mut self) -> TdsResult<()> {
            self.closed = true;
            Ok(())
        }
        async fn send_attention_with_timeout(
            &mut self,
            _context: &ParserContext,
            _timeout: Duration,
        ) -> TdsResult<bool> {
            self.attentions
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            // Acknowledged. `Ok(false)` would mean the ACK never came, and
            // `send_attention_and_wait` retires the transport on every such
            // outcome - a mock that returned it without doing so would let a test
            // read a dead connection as a surviving one.
            Ok(true)
        }
        fn is_connection_dead(&self) -> bool {
            self.closed
        }
        fn connection_known_dead(&self) -> bool {
            self.known_dead
        }
        fn mark_known_dead(&mut self) {
            self.known_dead = true;
        }
    }

    impl crate::io::packet_reader::TdsPacketReader for TestTransport {
        async fn read_byte(&mut self) -> TdsResult<u8> {
            Ok(self.take_packet_bytes(1)?[0])
        }
        async fn read_int16_big_endian(&mut self) -> TdsResult<i16> {
            unimplemented!("TestTransport")
        }
        async fn read_int32_big_endian(&mut self) -> TdsResult<i32> {
            unimplemented!("TestTransport")
        }
        async fn read_uint40(&mut self) -> TdsResult<u64> {
            unimplemented!("TestTransport")
        }
        async fn read_float32(&mut self) -> TdsResult<f32> {
            unimplemented!("TestTransport")
        }
        async fn read_float64(&mut self) -> TdsResult<f64> {
            unimplemented!("TestTransport")
        }
        async fn read_int16(&mut self) -> TdsResult<i16> {
            unimplemented!("TestTransport")
        }
        async fn read_uint16(&mut self) -> TdsResult<u16> {
            unimplemented!("TestTransport")
        }
        async fn read_uint24(&mut self) -> TdsResult<u32> {
            unimplemented!("TestTransport")
        }
        async fn read_int32(&mut self) -> TdsResult<i32> {
            unimplemented!("TestTransport")
        }
        async fn read_uint32(&mut self) -> TdsResult<u32> {
            unimplemented!("TestTransport")
        }
        async fn read_int64(&mut self) -> TdsResult<i64> {
            Ok(i64::from_le_bytes(
                self.take_packet_bytes(8)?.try_into().unwrap(),
            ))
        }
        async fn read_uint64(&mut self) -> TdsResult<u64> {
            unimplemented!("TestTransport")
        }
        async fn read_bytes(&mut self, _buf: &mut [u8]) -> TdsResult<usize> {
            unimplemented!("TestTransport")
        }
        async fn read_u8_varbyte(&mut self) -> TdsResult<Vec<u8>> {
            unimplemented!("TestTransport")
        }
        async fn read_u16_varbyte(&mut self) -> TdsResult<Vec<u8>> {
            unimplemented!("TestTransport")
        }
        async fn read_varchar_u16_length(&mut self) -> TdsResult<Option<String>> {
            unimplemented!("TestTransport")
        }
        async fn read_varchar_u8_length(&mut self) -> TdsResult<String> {
            unimplemented!("TestTransport")
        }
        async fn read_unicode(&mut self, _len: usize) -> TdsResult<String> {
            unimplemented!("TestTransport")
        }
        async fn read_unicode_with_byte_length(&mut self, _len: usize) -> TdsResult<String> {
            unimplemented!("TestTransport")
        }
        async fn skip_bytes(&mut self, _count: usize) -> TdsResult<()> {
            unimplemented!("TestTransport")
        }
        async fn cancel_read_stream(&mut self) -> TdsResult<()> {
            unimplemented!("TestTransport")
        }
        fn reset_reader(&mut self) {
            self.packet_pos = 0;
        }
    }

    fn create_test_client() -> TdsClient {
        create_test_client_with_transport(TestTransport::new())
    }

    fn create_test_client_with_transport(transport: TestTransport) -> TdsClient {
        create_test_client_with_any_transport(AnyTransport::dynamic(transport))
    }

    fn create_test_client_with_any_transport(transport: AnyTransport) -> TdsClient {
        let negotiated_settings =
            crate::handler::handler_factory::create_test_negotiated_settings_internal();
        let execution_context = crate::connection::execution_context::ExecutionContext::new();
        let client_context = ClientContext::with_data_source("tcp:localhost,1433");
        TdsClient::new(
            transport,
            negotiated_settings,
            execution_context,
            client_context,
            Vec::new(),
        )
    }

    #[test]
    fn encrypted_state_excludes_login_only_tls() {
        for (setting, expected) in [
            (NegotiatedEncryptionSetting::NoEncryption, false),
            (NegotiatedEncryptionSetting::LoginOnly, false),
            (NegotiatedEncryptionSetting::Mandatory, true),
            (NegotiatedEncryptionSetting::Strict, true),
        ] {
            let mut transport = TestTransport::new();
            transport.encryption_setting = setting;
            assert_eq!(
                create_test_client_with_transport(transport).is_encrypted(),
                expected,
                "{setting:?}"
            );
        }
    }

    #[test]
    fn session_recovery_wiring_from_negotiated_settings() {
        use crate::message::features::session_recovery::SessionRecoveryFeature;
        use crate::message::login::Feature;

        let transport = AnyTransport::dynamic(TestTransport::new());
        let mut negotiated_settings =
            crate::handler::handler_factory::create_test_negotiated_settings_internal();
        let mut feature = SessionRecoveryFeature::new(1);
        feature.set_acknowledged(true);
        feature.deserialize(&[0x07, 0x02, 0x01, 0x02]).unwrap();
        negotiated_settings
            .session_settings
            .supported_features
            .push(Box::new(feature));

        let client = TdsClient::new(
            transport,
            negotiated_settings,
            crate::connection::execution_context::ExecutionContext::new(),
            ClientContext::with_data_source("tcp:localhost,1433"),
            Vec::new(),
        );

        // The ack turns session_recovery_negotiated on (previously only ever set
        // in tests) and seeds the baseline state for replay on reconnect.
        assert!(client.recovery_context.session_recovery_negotiated);
        assert_eq!(
            client.recovery_context.session_state_table.initial_state[7]
                .as_ref()
                .unwrap()
                .data,
            vec![0x01, 0x02]
        );
    }

    /// Guards the fix for #225: a large local held across an `.await` in
    /// `drain_active_plp` is stored inline in that future and propagates into
    /// every caller in the await chain, costing a memcpy per row on the hot path.
    ///
    /// Under `cfg(test)`, `AnyTransport` includes its dynamic fallback, so these
    /// sizes conservatively include the larger `Either` representation. A
    /// regression can therefore originate in the test-only arm even when the
    /// production future remains smaller.
    #[test]
    fn row_fetch_futures_stay_small() {
        const MAX: usize = 4096;

        let mut client = create_test_client();
        let mut sink = DiscardRowWriter;
        let mut plp_out = [0u8; 64];

        // Constructing an async fn's future runs none of its body, so these are
        // free to build and drop unpolled. Each borrow ends with its statement.
        let next_row_cursor = std::mem::size_of_val(&client.next_row_cursor());
        let read_row_column = std::mem::size_of_val(&client.read_row_column(0));
        let drain_rows = std::mem::size_of_val(&client.drain_rows());
        let next_row_into = std::mem::size_of_val(&client.next_row_into(&mut sink));
        let next_row_into_dyn =
            std::mem::size_of_val(&client.next_row_into(&mut sink as &mut (dyn RowWriter + Send)));
        let read_active_plp_chunk =
            std::mem::size_of_val(&client.read_active_plp_chunk(&mut plp_out));

        for (name, size) in [
            ("next_row_cursor", next_row_cursor),
            ("read_row_column", read_row_column),
            ("drain_rows", drain_rows),
            ("next_row_into", next_row_into),
            ("next_row_into (dyn writer)", next_row_into_dyn),
            ("read_active_plp_chunk", read_active_plp_chunk),
        ] {
            assert!(
                size <= MAX,
                "{name} future is {size} B, expected <= {MAX} B"
            );
        }

        let native_next_row = std::mem::size_of_val(&client.get_next_row());
        let result_set_next_row = std::mem::size_of_val(&ResultSet::next_row(&mut client));
        let native_next_row_into =
            std::mem::size_of_val(&client.next_row_into(&mut sink as &mut (dyn RowWriter + Send)));
        let result_set_next_row_into =
            std::mem::size_of_val(&ResultSet::next_row_into(&mut client, &mut sink));

        assert_eq!(
            result_set_next_row, native_next_row,
            "ResultSet::next_row must forward the native future without boxing"
        );
        assert_eq!(
            result_set_next_row_into, native_next_row_into,
            "ResultSet::next_row_into must forward the native future without boxing"
        );

        // `close` is not checked against the per-row budget because it runs only
        // once per result set; its larger future does not affect row iteration.
        for (name, size) in [
            ("ResultSet::next_row", result_set_next_row),
            ("ResultSet::next_row_into", result_set_next_row_into),
        ] {
            assert!(
                size <= MAX,
                "{name} future is {size} B, expected <= {MAX} B"
            );
        }
    }

    #[test]
    fn prepare_reset_connection_routes_mode_to_transport() {
        let mut client = create_test_client();

        // Default: no reset pending.
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::None
        );

        // Plain reset.
        client.prepare_reset_connection(false);
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::Reset
        );
        // take_reset_mode is one-shot.
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::None
        );

        // Preserve transaction => SKIPTRAN.
        client.prepare_reset_connection(true);
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::ResetSkipTran
        );
    }

    fn create_test_client_with_tokens(tokens: Vec<Tokens>) -> TdsClient {
        let transport = AnyTransport::dynamic(TestTransport::with_tokens(tokens));
        let negotiated_settings =
            crate::handler::handler_factory::create_test_negotiated_settings_internal();
        let execution_context = crate::connection::execution_context::ExecutionContext::new();
        let client_context = ClientContext::with_data_source("tcp:localhost,1433");
        TdsClient::new(
            transport,
            negotiated_settings,
            execution_context,
            client_context,
            Vec::new(),
        )
    }

    /// Builds a client whose transport replays `tokens` and captures every byte
    /// written to the wire, returning the shared capture buffer alongside it.
    fn create_capturing_client(tokens: Vec<Tokens>) -> (TdsClient, Arc<std::sync::Mutex<Vec<u8>>>) {
        let transport = TestTransport::with_tokens(tokens);
        let sent = Arc::clone(&transport.sent);
        let transport = AnyTransport::dynamic(transport);
        let negotiated_settings =
            crate::handler::handler_factory::create_test_negotiated_settings_internal();
        let execution_context = crate::connection::execution_context::ExecutionContext::new();
        let client_context = ClientContext::with_data_source("tcp:localhost,1433");
        let client = TdsClient::new(
            transport,
            negotiated_settings,
            execution_context,
            client_context,
            Vec::new(),
        );
        (client, sent)
    }

    /// Like [`create_capturing_client`], but shares the timeout each
    /// `receive_token` was given instead of the bytes written.
    fn create_timeout_observing_client(
        tokens: Vec<Tokens>,
    ) -> (TdsClient, Arc<std::sync::Mutex<Vec<Option<Duration>>>>) {
        let transport = TestTransport::with_tokens(tokens);
        let observed = Arc::clone(&transport.receive_timeouts);
        let transport = AnyTransport::dynamic(transport);
        let negotiated_settings =
            crate::handler::handler_factory::create_test_negotiated_settings_internal();
        let execution_context = crate::connection::execution_context::ExecutionContext::new();
        let client_context = ClientContext::with_data_source("tcp:localhost,1433");
        let client = TdsClient::new(
            transport,
            negotiated_settings,
            execution_context,
            client_context,
            Vec::new(),
        );
        (client, observed)
    }

    /// Like [`create_capturing_client`], but also returns a shared flag that,
    /// when set, makes the transport's next `send` fail — used to exercise the
    /// mid-stream abort path of the streamed PLP write.
    fn create_failing_capturing_client(
        tokens: Vec<Tokens>,
    ) -> (TdsClient, std::sync::Arc<std::sync::atomic::AtomicBool>) {
        let transport = TestTransport::with_tokens(tokens);
        let fail = std::sync::Arc::clone(&transport.send_should_fail);
        let transport = AnyTransport::dynamic(transport);
        let negotiated_settings =
            crate::handler::handler_factory::create_test_negotiated_settings_internal();
        let execution_context = crate::connection::execution_context::ExecutionContext::new();
        let client_context = ClientContext::with_data_source("tcp:localhost,1433");
        let client = TdsClient::new(
            transport,
            negotiated_settings,
            execution_context,
            client_context,
            Vec::new(),
        );
        (client, fail)
    }

    fn done_no_more() -> Tokens {
        Tokens::Done(DoneToken {
            status: DoneStatus::FINAL,
            cur_cmd: CurrentCommand::Insert,
            row_count: 0,
        })
    }

    /// A DONE token carrying the `DONE_COUNT` flag (a DML row count). `more`
    /// sets `DONE_MORE` so it is treated as a non-terminal result in a batch.
    fn done_count(cmd: CurrentCommand, rows: u64, more: bool) -> Tokens {
        let status = if more {
            DoneStatus::COUNT | DoneStatus::MORE
        } else {
            DoneStatus::COUNT
        };
        Tokens::Done(DoneToken {
            status,
            cur_cmd: cmd,
            row_count: rows,
        })
    }

    fn info_token(number: u32, severity: u8, message: &str) -> Tokens {
        Tokens::Info(InfoToken {
            number,
            state: 1,
            severity,
            message: message.to_string(),
            server_name: "test-server".to_string(),
            proc_name: String::new(),
            line_number: 7,
        })
    }

    fn empty_col_metadata() -> Tokens {
        Tokens::ColMetadata(ColMetadataToken::default())
    }

    /// A COLMETADATA token for `n` nullable `int` columns, so tests can assert
    /// the client is positioned on a real row set rather than a 0-column one.
    fn int_col_metadata(n: usize) -> Tokens {
        let columns = crate::test_client_support::int_columns(n);
        Tokens::ColMetadata(ColMetadataToken {
            column_count: u16::try_from(columns.len()).unwrap_or(u16::MAX),
            columns,
            cek_table: Vec::new(),
        })
    }

    fn stale_metadata() -> Arc<ColMetadataToken> {
        Arc::new(ColMetadataToken::default())
    }

    fn int_column_metadata(column_count: usize) -> Arc<ColMetadataToken> {
        let columns = (0..column_count)
            .map(|index| crate::query::metadata::ColumnMetadata {
                user_type: 0,
                flags: 0,
                type_info: crate::datatypes::sqldatatypes::TypeInfo::fixed_len(
                    crate::datatypes::sqldatatypes::TdsDataType::Int4,
                )
                .unwrap(),
                data_type: crate::datatypes::sqldatatypes::TdsDataType::Int4,
                column_name: format!("c{index}"),
                multi_part_name: None,
                crypto_metadata: None,
            })
            .collect();
        Arc::new(ColMetadataToken {
            column_count: u16::try_from(column_count).unwrap(),
            columns,
            cek_table: vec![],
        })
    }

    fn mixed_lob_metadata(prefix_columns: usize) -> Arc<ColMetadataToken> {
        let mut columns = int_column_metadata(prefix_columns).columns.clone();
        columns.push(crate::query::metadata::ColumnMetadata {
            user_type: 0,
            flags: 0,
            type_info: crate::datatypes::sqldatatypes::TypeInfo::partial_len(
                crate::datatypes::sqldatatypes::TdsDataType::NVarChar,
                usize::from(u16::MAX),
                None,
            )
            .unwrap(),
            data_type: crate::datatypes::sqldatatypes::TdsDataType::NVarChar,
            column_name: "lob".to_string(),
            multi_part_name: None,
            crypto_metadata: None,
        });
        Arc::new(ColMetadataToken {
            column_count: u16::try_from(columns.len()).unwrap(),
            columns,
            cek_table: vec![],
        })
    }

    /// Like [`mixed_lob_metadata`], but with `suffix_columns` plain int
    /// columns after the PLP column instead of the PLP column being last.
    fn mixed_lob_metadata_with_int_suffix(
        prefix_columns: usize,
        suffix_columns: usize,
    ) -> Arc<ColMetadataToken> {
        let mut columns = mixed_lob_metadata(prefix_columns).columns.clone();
        columns.extend(int_column_metadata(suffix_columns).columns.iter().cloned());
        Arc::new(ColMetadataToken {
            column_count: u16::try_from(columns.len()).unwrap(),
            columns,
            cek_table: vec![],
        })
    }

    fn done_more() -> Tokens {
        Tokens::Done(DoneToken {
            status: DoneStatus::MORE,
            cur_cmd: CurrentCommand::Insert,
            row_count: 0,
        })
    }

    fn done_in_proc_more() -> Tokens {
        Tokens::DoneInProc(DoneToken {
            status: DoneStatus::MORE,
            cur_cmd: CurrentCommand::Select,
            row_count: 0,
        })
    }

    fn done_proc_no_more() -> Tokens {
        Tokens::DoneProc(DoneToken {
            status: DoneStatus::FINAL,
            cur_cmd: CurrentCommand::Select,
            row_count: 0,
        })
    }

    fn done_more_with_count(row_count: u64) -> Tokens {
        Tokens::Done(DoneToken {
            status: DoneStatus::MORE | DoneStatus::COUNT,
            cur_cmd: CurrentCommand::Insert,
            row_count,
        })
    }

    /// Statement-wise navigation exposes each no-row statement (PRINT /
    /// RAISERROR) as its own result, matching msodbcsql, instead of collapsing
    /// them the way `advance_to_rows()` does.
    #[tokio::test]
    async fn execute_exposes_each_norow_statement() {
        // Batch: PRINT N'one'; RAISERROR(N'two', 10, 1);
        let mut client = create_test_client_with_tokens(vec![
            info_token(0, 0, "print one"),
            done_more(),
            info_token(50000, 10, "raiserror two"),
            done_no_more(),
        ]);

        // First statement surfaces as its own no-row result.
        let r1 = client
            .execute(
                "PRINT N'one'; RAISERROR(N'two', 10, 1) WITH NOWAIT;".to_string(),
                (),
            )
            .await
            .unwrap();
        assert_eq!(
            r1,
            StatementResult::NoRows {
                rows_affected: None
            }
        );
        // Only the first statement's INFO is present when it is drained.
        let info1 = client.take_info_messages();
        assert!(
            info1.iter().any(|m| m.message == "print one"),
            "first statement's PRINT should be captured: {info1:?}"
        );
        assert!(
            !info1.iter().any(|m| m.message == "raiserror two"),
            "second statement's INFO must not leak into the first: {info1:?}"
        );

        // Second statement is a separate no-row result.
        let r2 = client.advance().await.unwrap();
        assert_eq!(
            r2,
            StatementResult::NoRows {
                rows_affected: None
            }
        );
        let info2 = client.take_info_messages();
        assert!(
            info2.iter().any(|m| m.message == "raiserror two"),
            "second statement's RAISERROR should surface on its own step: {info2:?}"
        );

        // No more statements.
        let r3 = client.advance().await.unwrap();
        assert_eq!(r3, StatementResult::End);
    }

    /// A single no-row statement is exposed once, then the batch ends.
    #[tokio::test]
    async fn execute_single_norow_then_end() {
        let mut client =
            create_test_client_with_tokens(vec![info_token(0, 0, "just a print"), done_no_more()]);

        let r1 = client
            .execute("PRINT N'just a print';".to_string(), ())
            .await
            .unwrap();
        assert_eq!(
            r1,
            StatementResult::NoRows {
                rows_affected: None
            }
        );

        let r2 = client.advance().await.unwrap();
        assert_eq!(r2, StatementResult::End);
    }

    /// Statement-wise navigation collapses pure no-op statements (no row count,
    /// no messages — e.g. `CREATE TABLE`) but surfaces a DML statement's row
    /// count, matching msodbcsql (`CREATE; INSERT; SELECT` exposes the INSERT
    /// count and the SELECT, not the bare CREATE).
    #[tokio::test]
    async fn execute_collapses_noop_surfaces_rowcount() {
        let mut client = create_test_client_with_tokens(vec![
            done_more(),             // pure no-op (CREATE) - collapsed
            done_more_with_count(5), // DML with a row count - surfaced
            done_no_more(),          // trailing no-op - collapsed -> End
        ]);

        let r1 = client
            .execute(
                "CREATE TABLE #t(i int); INSERT INTO #t VALUES(1);".to_string(),
                (),
            )
            .await
            .unwrap();
        assert_eq!(
            r1,
            StatementResult::NoRows {
                rows_affected: Some(5)
            }
        );

        let r2 = client.advance().await.unwrap();
        assert_eq!(r2, StatementResult::End);
    }

    /// SQL Server compiles variable assignment as a SQLSELECT command and still
    /// sets DONE_COUNT. Such a DONE must collapse into the following row set
    /// rather than surface as a leading update-count result.
    /// Observed token sequence for `DECLARE @out int = 1; EXEC dbo.p;`.
    #[tokio::test]
    async fn execute_skips_select_count_before_rowset() {
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Select, 1, true),
            int_col_metadata(1),
        ]);

        let result = client
            .execute("DECLARE @out int = 1; EXEC dbo.p;".to_string(), ())
            .await
            .unwrap();

        assert_eq!(result, StatementResult::Rows);
        assert_eq!(
            client
                .get_current_metadata()
                .map(|m| m.columns.len())
                .unwrap_or(0),
            1,
            "must be positioned on the procedure's row set"
        );
        assert_eq!(client.last_rows_affected(), -1);
        assert!(client.take_dml_result_counts().is_empty());
    }

    /// `DECLARE @x int = 1;` on its own must not report a phantom result.
    #[tokio::test]
    async fn execute_select_count_only_batch_ends_immediately() {
        let mut client =
            create_test_client_with_tokens(vec![done_count(CurrentCommand::Select, 1, false)]);

        let result = client
            .execute("DECLARE @x int = 1;".to_string(), ())
            .await
            .unwrap();

        assert_eq!(result, StatementResult::End);
        assert_eq!(client.last_rows_affected(), -1);
        assert!(client.take_dml_result_counts().is_empty());
    }

    /// Several assignments in a row all collapse.
    #[tokio::test]
    async fn execute_skips_consecutive_select_counts() {
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Select, 1, true),
            done_count(CurrentCommand::Select, 1, true),
            done_count(CurrentCommand::Select, 2, true),
            int_col_metadata(1),
        ]);

        let result = client
            .execute(
                "DECLARE @a int = 1; SET @a = 2; SELECT @a = v FROM t; SELECT * FROM t;"
                    .to_string(),
                (),
            )
            .await
            .unwrap();

        assert_eq!(result, StatementResult::Rows);
        assert_eq!(
            client
                .get_current_metadata()
                .map(|m| m.columns.len())
                .unwrap_or(0),
            1
        );
        assert_eq!(client.last_rows_affected(), -1);
    }

    /// AB#47535: a PRINT reached only *after* variable assignments. The
    /// assignments' SQLSELECT-tagged DONE_COUNTs must collapse so the very first
    /// result the caller sees is the PRINT's message-only result. Treating them
    /// as update counts stops the batch on the DECLARE, so `execute` returns
    /// `NoRows { rows_affected: Some(1) }` with no message and the ODBC layer
    /// reports plain `SQL_SUCCESS` — the shape that hid PRINT output from
    /// `mssql-python`'s `cursor.messages`.
    ///
    /// Observed token sequence for
    /// `DECLARE @msg VARCHAR(MAX); SET @msg = REPLICATE(CAST('a' AS VARCHAR(MAX)), 2047); PRINT @msg;`.
    #[tokio::test]
    async fn execute_surfaces_print_after_assignment_counts() {
        let printed = "a".repeat(2047);
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Select, 1, true),
            done_count(CurrentCommand::Select, 1, true),
            info_token(0, 0, &printed),
            done_no_more(),
        ]);

        let result = client
            .execute(
                "DECLARE @msg VARCHAR(MAX);\
                 SET @msg = REPLICATE(CAST('a' AS VARCHAR(MAX)), 2047);\
                 PRINT @msg;"
                    .to_string(),
                (),
            )
            .await
            .unwrap();

        assert_eq!(
            result,
            StatementResult::NoRows {
                rows_affected: None
            }
        );
        assert_eq!(client.last_rows_affected(), -1);
        assert!(client.take_dml_result_counts().is_empty());

        let messages = client.take_info_messages();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].message, printed);
        assert_eq!(messages[0].number, 0);
    }

    /// A PRINT on its own statement surfaces as a message-only result (its DONE
    /// carries no count); the following assignment's count is still suppressed.
    #[tokio::test]
    async fn execute_surfaces_message_but_skips_select_count() {
        let mut client = create_test_client_with_tokens(vec![
            info_token(0, 0, "hi"),
            done_more(),
            done_count(CurrentCommand::Select, 1, true),
            int_col_metadata(1),
        ]);

        let first = client
            .execute("PRINT 'hi'; DECLARE @x int = 1; SELECT 1;".to_string(), ())
            .await
            .unwrap();
        assert_eq!(
            first,
            StatementResult::NoRows {
                rows_affected: None
            }
        );
        assert_eq!(client.last_rows_affected(), -1);
        assert!(client.take_dml_result_counts().is_empty());

        let second = client.advance().await.unwrap();
        assert_eq!(second, StatementResult::Rows);
        assert_eq!(
            client
                .get_current_metadata()
                .map(|m| m.columns.len())
                .unwrap_or(0),
            1
        );
    }

    /// Divergence pin: msodbcsql excludes `SQLFETCHCURSOR` (0x21) and `SQLDBCC`
    /// (0xe6) alongside `SQLSELECT`; this driver excludes only `SQLSELECT`,
    /// matching .NET SqlClient. Neither value is modelled, so a `DONE_COUNT`
    /// carrying one parses as `None` and *is* reported as an update count.
    /// Fails the moment someone adopts the msodbcsql-only exclusions, forcing
    /// that `SQLRowCount` change to be deliberate rather than incidental.
    #[tokio::test]
    async fn done_count_for_msodbcsql_only_exclusions_is_an_update_count() {
        for raw in [0x21u16, 0xe6] {
            let cmd = CurrentCommand::try_from(raw).unwrap();
            let mut client = create_test_client_with_tokens(vec![done_count(cmd, 3, false)]);

            let result = client
                .execute("EXEC sp_cursorfetch @handle".to_string(), ())
                .await
                .unwrap();

            assert_eq!(
                result,
                StatementResult::NoRows {
                    rows_affected: Some(3)
                },
                "raw cur_cmd {raw:#x}"
            );
            assert_eq!(client.last_rows_affected(), 3, "raw cur_cmd {raw:#x}");
            assert_eq!(
                client.take_dml_result_counts(),
                vec![3],
                "raw cur_cmd {raw:#x}"
            );
        }
    }

    /// The only path where `saw_message` and `has_count` land on the *same* DONE:
    /// a warning raised by the assignment itself. The result must still surface
    /// so the message is visible, but must carry no row count — this PR changed
    /// `rows_affected` here from `Some(1)` to `None`.
    ///
    /// A genuine `UPDATE` precedes the assignment so the assertion is real: with
    /// a bare assignment `last_rows_affected` is still `-1` from `begin_command`
    /// and would pass even if the message-only branch leaked a prior count.
    ///
    /// Live capture for
    /// `UPDATE #t SET v = v; DECLARE @x int; SELECT @x = MAX(v) FROM #t; SELECT 5 AS a;`
    /// where `#t.v` contains a NULL:
    /// ```text
    /// DONE status=MORE|COUNT cur_cmd=Update row_count=2
    /// INFO 8153 "Warning: Null value is eliminated by an aggregate or other SET operation."
    /// DONE status=MORE|COUNT cur_cmd=Select row_count=1
    /// COLMETADATA(1) + row
    /// ```
    /// msodbcsql reports `rowcount=2`, then `rowcount=-1`, then `rowcount=-1`.
    #[tokio::test]
    async fn execute_surfaces_assignment_warning_without_rowcount() {
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Update, 2, true),
            info_token(
                8153,
                0,
                "Warning: Null value is eliminated by an aggregate or other SET operation.",
            ),
            done_count(CurrentCommand::Select, 1, true),
            int_col_metadata(1),
        ]);

        let first = client
            .execute(
                "UPDATE #t SET v = v; DECLARE @x int; SELECT @x = MAX(v) FROM #t; SELECT 5 AS a;"
                    .to_string(),
                (),
            )
            .await
            .unwrap();
        assert_eq!(
            first,
            StatementResult::NoRows {
                rows_affected: Some(2)
            }
        );
        assert_eq!(client.last_rows_affected(), 2);

        let second = client.advance().await.unwrap();
        assert_eq!(
            second,
            StatementResult::NoRows {
                rows_affected: None
            }
        );
        assert_eq!(
            client.last_rows_affected(),
            -1,
            "the UPDATE's count must not leak into the message-only result"
        );

        let third = client.advance().await.unwrap();
        assert_eq!(third, StatementResult::Rows);
        assert_eq!(
            client
                .get_current_metadata()
                .map(|m| m.columns.len())
                .unwrap_or(0),
            1
        );
    }

    /// A genuine DML count following an assignment is still reported.
    #[tokio::test]
    async fn execute_keeps_update_count_after_select_count() {
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Select, 1, true),
            done_count(CurrentCommand::Update, 2, true),
            int_col_metadata(1),
        ]);

        let first = client
            .execute(
                "DECLARE @x int = 1; UPDATE t SET v = v; SELECT * FROM t;".to_string(),
                (),
            )
            .await
            .unwrap();
        assert_eq!(
            first,
            StatementResult::NoRows {
                rows_affected: Some(2)
            }
        );
        assert_eq!(client.last_rows_affected(), 2);
        assert_eq!(client.take_dml_result_counts(), vec![2]);

        let second = client.advance().await.unwrap();
        assert_eq!(second, StatementResult::Rows);
    }

    /// `SELECT ... INTO` reports DONE_COUNT with no CurCmd, which is a genuine
    /// update count and must survive the SQLSELECT filter.
    #[tokio::test]
    async fn execute_keeps_select_into_count() {
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::None, 1, true),
            int_col_metadata(1),
        ]);

        let first = client
            .execute("SELECT 1 AS a INTO #t; SELECT * FROM #t;".to_string(), ())
            .await
            .unwrap();
        assert_eq!(
            first,
            StatementResult::NoRows {
                rows_affected: Some(1)
            }
        );
        assert_eq!(client.last_rows_affected(), 1);
        assert_eq!(client.take_dml_result_counts(), vec![1]);
    }

    #[tokio::test]
    async fn advance_end_when_no_open_batch() {
        let mut client = create_test_client();
        assert_eq!(client.advance().await.unwrap(), StatementResult::End);
    }

    /// Regression test for a hang: after positioning on the batch's final row
    /// set, calling `advance` without reading its rows must drain
    /// them, observe the terminal DONE (which closes the batch), and return
    /// `End` — instead of issuing another token read that would block forever on
    /// an already-finished batch. The whole exchange is bounded by a timeout so a
    /// regression surfaces as a test failure rather than a hung suite.
    #[tokio::test]
    async fn move_to_next_statement_end_after_draining_final_rowset() {
        // A single row-returning statement: COLMETADATA then a terminal DONE.
        let mut client = create_test_client_with_tokens(vec![empty_col_metadata(), done_no_more()]);

        let first = tokio::time::timeout(
            Duration::from_secs(5),
            client.execute("SELECT 1;".to_string(), ()),
        )
        .await
        .expect("execute should not hang")
        .unwrap();
        assert_eq!(first, StatementResult::Rows);

        // Advance without fetching any rows: the drain consumes the terminal
        // DONE and the call must report end-of-batch rather than block.
        let next = tokio::time::timeout(Duration::from_secs(5), client.advance())
            .await
            .expect("advance must not hang after draining the final row set")
            .unwrap();
        assert_eq!(next, StatementResult::End);
    }

    #[test]
    fn caller_zero_timeout_becomes_explicit_infinite_budget() {
        let budget = TdsClient::deduct_timeout(Some(0), Duration::ZERO);
        assert_eq!(budget, CommandTimeoutBudget::None);
        let resolved = budget.into_timeout().unwrap();
        assert_eq!(resolved.seconds(), None);
        assert_eq!(resolved.duration(), None);
    }

    #[test]
    fn cursor_poll_resolves_ready_without_fallback() {
        let mut calls = 0;
        let value = CursorPoll::Ready(7).resolve::<()>(|| {
            calls += 1;
            Ok(9)
        });

        assert_eq!(value, Ok(7));
        assert_eq!(calls, 0);
    }

    #[test]
    fn cursor_poll_resolves_pending_with_one_fallback() {
        let mut calls = 0;
        let value = CursorPoll::Pending.resolve::<()>(|| {
            calls += 1;
            Ok(9)
        });

        assert_eq!(value, Ok(9));
        assert_eq!(calls, 1);
    }

    #[test]
    fn sync_cursor_attempt_reads_buffered_header_and_columns_in_order() {
        let metadata = int_column_metadata(2);
        let mut transport = TestTransport::new();
        transport.sync_header_available = true;
        transport.sync_columns = VecDeque::from([ColumnValues::Int(10), ColumnValues::Int(20)]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;

        assert_eq!(
            client.try_next_row_cursor().unwrap(),
            CursorPoll::Ready(true)
        );
        assert_eq!(
            client.try_read_row_column(0).unwrap(),
            CursorPoll::Ready(CursorColumn::Value {
                value: ColumnValues::Int(10),
                variant_base: None,
            })
        );
        assert_eq!(
            client.try_read_row_column(1).unwrap(),
            CursorPoll::Ready(CursorColumn::Value {
                value: ColumnValues::Int(20),
                variant_base: None,
            })
        );
        assert_eq!(
            client.try_read_row_column(1).unwrap(),
            CursorPoll::Ready(CursorColumn::RowEnded)
        );
    }

    #[tokio::test]
    async fn sync_peek_parks_the_buffered_row_for_the_next_cursor_call() {
        let metadata = int_column_metadata(1);
        let mut transport = TestTransport::new();
        transport.sync_header_available = true;
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;

        assert_eq!(
            client.try_peek_past_current_row().unwrap(),
            CursorPoll::Ready(true)
        );
        assert!(client.row_already_positioned);

        assert!(client.next_row_cursor().await.unwrap());
        assert!(!client.row_already_positioned);
    }

    #[tokio::test]
    async fn sync_cursor_decodes_buffered_sql_variant_with_base_type() {
        let column = crate::query::metadata::ColumnMetadata {
            user_type: 0,
            flags: 0,
            type_info: crate::datatypes::sqldatatypes::TypeInfo::var_len(
                TdsDataType::SsVariant,
                8009,
            )
            .unwrap(),
            data_type: TdsDataType::SsVariant,
            column_name: "variant".to_string(),
            multi_part_name: None,
            crypto_metadata: None,
        };
        let metadata = Arc::new(ColMetadataToken {
            column_count: 1,
            columns: vec![column],
            cek_table: Vec::new(),
        });
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend_from_slice(&6_u32.to_le_bytes());
        payload.extend_from_slice(&[TdsDataType::Int4 as u8, 0]);
        payload.extend_from_slice(&42_i32.to_le_bytes());
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;

        assert_eq!(
            client.try_next_row_cursor().unwrap(),
            CursorPoll::Ready(true)
        );
        assert_eq!(
            client.try_read_row_column(0).unwrap(),
            CursorPoll::Ready(CursorColumn::Value {
                value: ColumnValues::Int(42),
                variant_base: Some(TdsDataType::Int4),
            })
        );
    }

    #[tokio::test]
    async fn buffered_row_poll_completes_without_parking_cursor_state() {
        let expected = [0x1234_5678_i32, -42_i32];
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend(expected.iter().flat_map(|value| value.to_le_bytes()));
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(int_column_metadata(expected.len()));
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(expected.len());

        assert_eq!(
            client.try_next_buffered_row_into(&mut writer).unwrap(),
            BufferedRowPoll::Complete
        );
        assert_eq!(
            writer.take_row(),
            expected
                .into_iter()
                .map(ColumnValues::Int)
                .collect::<Vec<_>>()
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));
    }

    #[tokio::test]
    async fn buffered_prefix_capture_leaves_and_consumes_complete_plp() {
        let metadata = mixed_lob_metadata(2);
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend_from_slice(&10_i32.to_le_bytes());
        payload.extend_from_slice(&20_i32.to_le_bytes());
        payload.extend_from_slice(&4_i64.to_le_bytes());
        payload.extend_from_slice(&4_u32.to_le_bytes());
        payload.extend_from_slice(&[b'o', 0, b'k', 0]);
        payload.extend_from_slice(&0_u32.to_le_bytes());
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        assert_eq!(client.current_result_bufferable_prefix_len(), Some(2));
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(2);

        assert_eq!(
            client
                .try_next_buffered_row_prefix_into(2, &mut writer)
                .unwrap(),
            BufferedRowPoll::Complete
        );
        assert_eq!(
            writer.take_row(),
            vec![ColumnValues::Int(10), ColumnValues::Int(20)]
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 2
        ));

        let mut bytes = [0_u8; 4];
        let CursorPoll::Ready(Some(chunk)) =
            client.try_read_row_plp_complete(2, &mut bytes).unwrap()
        else {
            panic!("complete buffered PLP should not require async continuation");
        };
        assert_eq!(bytes, [b'o', 0, b'k', 0]);
        assert_eq!(chunk.read, 4);
        assert!(chunk.reached_end);
    }

    #[tokio::test]
    async fn buffered_prefix_capture_updates_the_remaining_timeout() {
        // Needs a trailing PLP column so `prefix_len` (the PLP column's
        // index) is a valid buffered-prefix boundary; the prefix itself
        // only touches the leading int column.
        let metadata = mixed_lob_metadata(1);
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend_from_slice(&42_i32.to_le_bytes());
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        client.remaining_request_timeout = Some(Duration::from_secs(30));
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(1);

        assert_eq!(
            client
                .try_next_buffered_row_prefix_into(1, &mut writer)
                .unwrap(),
            BufferedRowPoll::Complete
        );
        assert!(client.remaining_request_timeout.unwrap() < Duration::from_secs(30));
    }

    #[tokio::test]
    async fn buffered_prefix_capture_propagates_a_column_decode_error() {
        // An invalid `IntN` length byte makes the underlying buffered decoder
        // return a `ProtocolError`, which must propagate out of
        // `try_next_buffered_row_prefix_into` instead of being swallowed. A
        // trailing PLP column makes column 0's index a valid prefix boundary.
        let mut columns = vec![crate::query::metadata::ColumnMetadata {
            user_type: 0,
            flags: 0,
            type_info: crate::datatypes::sqldatatypes::TypeInfo::var_len(
                crate::datatypes::sqldatatypes::TdsDataType::IntN,
                4,
            )
            .unwrap(),
            data_type: crate::datatypes::sqldatatypes::TdsDataType::IntN,
            column_name: "c0".to_string(),
            multi_part_name: None,
            crypto_metadata: None,
        }];
        columns.extend(mixed_lob_metadata(0).columns.iter().cloned());
        let metadata = Arc::new(ColMetadataToken {
            column_count: u16::try_from(columns.len()).unwrap(),
            columns,
            cek_table: vec![],
        });
        let payload = vec![0xff, TokenType::Row as u8, 3];
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(1);

        let error = client
            .try_next_buffered_row_prefix_into(1, &mut writer)
            .unwrap_err();
        assert!(matches!(error, crate::error::Error::ProtocolError(_)));
    }

    #[tokio::test]
    async fn buffered_prefix_capture_continues_across_packets() {
        let metadata = mixed_lob_metadata(2);
        let second_value = 20_i32.to_le_bytes();
        let mut first_payload = vec![0xff, TokenType::Row as u8];
        first_payload.extend_from_slice(&10_i32.to_le_bytes());
        first_payload.extend_from_slice(&second_value[..2]);
        let mut first = TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut second =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut stream = first.continuation().append_bytes(&first_payload).build();
        stream.extend_from_slice(
            &second
                .append_bytes(&second_value[2..])
                .append_bytes(&(-1_i64).to_le_bytes())
                .build(),
        );
        let mut transport = create_network_transport_with_data(&stream);
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(2);

        assert_eq!(
            client
                .try_next_buffered_row_prefix_into(2, &mut writer)
                .unwrap(),
            BufferedRowPoll::Partial
        );
        client.finish_row_prefix_into(2, &mut writer).await.unwrap();
        assert_eq!(
            writer.take_row(),
            vec![ColumnValues::Int(10), ColumnValues::Int(20)]
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 2
        ));
    }

    /// Sets up `client` positioned at a buffered `[int, int, PLP]` row with
    /// `client.try_next_buffered_row_prefix_into(2, writer)` already run, so
    /// `active_row_read_state` is `RowPaused` right before the PLP column.
    async fn positioned_before_buffered_plp_column(
        plp_payload: &[u8],
    ) -> (TdsClient, crate::datatypes::row_writer::DefaultRowWriter) {
        let metadata = mixed_lob_metadata(2);
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend_from_slice(&10_i32.to_le_bytes());
        payload.extend_from_slice(&20_i32.to_le_bytes());
        payload.extend_from_slice(plp_payload);
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(2);
        assert_eq!(
            client
                .try_next_buffered_row_prefix_into(2, &mut writer)
                .unwrap(),
            BufferedRowPoll::Complete
        );
        (client, writer)
    }

    #[tokio::test]
    async fn cursor_column_begins_a_buffered_plp_stream_when_length_is_known() {
        // Known-length header (4) + a complete chunk + terminator, all already
        // buffered: `try_read_row_column` must open a real `PlpStreaming`
        // cursor from bytes alone, without waiting on async I/O.
        let mut plp_payload = Vec::new();
        plp_payload.extend_from_slice(&4_i64.to_le_bytes());
        plp_payload.extend_from_slice(&4_u32.to_le_bytes());
        plp_payload.extend_from_slice(&[b'o', 0, b'k', 0]);
        plp_payload.extend_from_slice(&0_u32.to_le_bytes());
        let (mut client, _writer) = positioned_before_buffered_plp_column(&plp_payload).await;

        let result = client.try_read_row_column(2).unwrap();
        assert!(matches!(
            result,
            CursorPoll::Ready(CursorColumn::PlpStreaming { .. })
        ));
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::PlpPaused(_)
        ));
    }

    #[tokio::test]
    async fn cursor_column_reports_null_for_a_buffered_plp_sentinel() {
        // `SQL_PLP_NULL` (all bits set) means the PLP column itself is NULL on
        // the wire; `try_read_row_column` must report it as a plain NULL value
        // without ever entering the `PlpPaused` streaming state.
        let plp_payload = (-1_i64).to_le_bytes();
        let (mut client, _writer) = positioned_before_buffered_plp_column(&plp_payload).await;

        let result = client.try_read_row_column(2).unwrap();
        assert!(matches!(
            result,
            CursorPoll::Ready(CursorColumn::Value {
                value: ColumnValues::Null,
                variant_base: None,
            })
        ));
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));
    }

    #[tokio::test]
    async fn try_read_active_plp_chunk_reads_a_buffered_chunk_and_updates_the_timeout() {
        let mut plp_payload = Vec::new();
        plp_payload.extend_from_slice(&4_i64.to_le_bytes());
        plp_payload.extend_from_slice(&4_u32.to_le_bytes());
        plp_payload.extend_from_slice(&[b'o', 0, b'k', 0]);
        plp_payload.extend_from_slice(&0_u32.to_le_bytes());
        let (mut client, _writer) = positioned_before_buffered_plp_column(&plp_payload).await;
        assert!(matches!(
            client.try_read_row_column(2).unwrap(),
            CursorPoll::Ready(CursorColumn::PlpStreaming { .. })
        ));
        client.remaining_request_timeout = Some(Duration::from_secs(30));

        let mut out = [0_u8; 4];
        let CursorPoll::Ready(chunk) = client.try_read_active_plp_chunk(&mut out).unwrap() else {
            panic!("the whole chunk was already buffered");
        };
        assert_eq!(out, [b'o', 0, b'k', 0]);
        assert_eq!(chunk.read, 4);
        assert!(chunk.reached_end);
        assert!(client.remaining_request_timeout.unwrap() < Duration::from_secs(30));
    }

    #[tokio::test]
    async fn try_read_active_plp_chunk_defers_when_the_socket_has_no_more_data_yet() {
        // The chunk header is only partially buffered and the peer stays
        // connected without sending more, so `try_read_buffered_plp` must fall
        // through its "no more data yet" branch and report `Pending` rather
        // than blocking or erroring.
        let metadata = mixed_lob_metadata(2);
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend_from_slice(&10_i32.to_le_bytes());
        payload.extend_from_slice(&20_i32.to_le_bytes());
        payload.extend_from_slice(&4_i64.to_le_bytes()); // known-length PLP header
        payload.extend_from_slice(&[0, 0]); // partial chunk-length header only
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_live_peer(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(2);
        assert_eq!(
            client
                .try_next_buffered_row_prefix_into(2, &mut writer)
                .unwrap(),
            BufferedRowPoll::Complete
        );
        assert!(matches!(
            client.try_read_row_column(2).unwrap(),
            CursorPoll::Ready(CursorColumn::PlpStreaming { .. })
        ));

        let mut out = [0_u8; 4];
        assert_eq!(
            client.try_read_active_plp_chunk(&mut out).unwrap(),
            CursorPoll::Pending
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::PlpPaused(_)
        ));
    }

    #[tokio::test]
    async fn try_read_row_plp_complete_reports_a_buffered_null_column() {
        // The PLP header itself carries `SQL_PLP_NULL`, distinct from the
        // NBCROW null-bitmap null path exercised elsewhere.
        let plp_payload = (-1_i64).to_le_bytes();
        let (mut client, _writer) = positioned_before_buffered_plp_column(&plp_payload).await;

        let mut out = [0_u8; 4];
        assert_eq!(
            client.try_read_row_plp_complete(2, &mut out).unwrap(),
            CursorPoll::Ready(None)
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));
    }

    #[tokio::test]
    async fn try_read_row_plp_complete_is_pending_without_the_full_chunk() {
        // Only the 8-byte known-length header is buffered; the chunk header
        // and payload haven't arrived yet, so the client must defer instead
        // of erroring or fabricating a result.
        let plp_payload = 4_i64.to_le_bytes();
        let (mut client, _writer) = positioned_before_buffered_plp_column(&plp_payload).await;

        let mut out = [0_u8; 4];
        assert_eq!(
            client.try_read_row_plp_complete(2, &mut out).unwrap(),
            CursorPoll::Pending
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 2
        ));
    }

    #[tokio::test]
    async fn try_read_row_plp_complete_leaves_row_paused_when_more_columns_remain() {
        // With a plain int column after the PLP column, completing the PLP
        // value from buffered bytes must keep the row parked instead of
        // dropping to `Idle`.
        let metadata = mixed_lob_metadata_with_int_suffix(2, 1);
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend_from_slice(&10_i32.to_le_bytes());
        payload.extend_from_slice(&20_i32.to_le_bytes());
        payload.extend_from_slice(&4_i64.to_le_bytes());
        payload.extend_from_slice(&4_u32.to_le_bytes());
        payload.extend_from_slice(&[b'o', 0, b'k', 0]);
        payload.extend_from_slice(&0_u32.to_le_bytes());
        payload.extend_from_slice(&30_i32.to_le_bytes());
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(4);
        assert_eq!(
            client
                .try_next_buffered_row_prefix_into(2, &mut writer)
                .unwrap(),
            BufferedRowPoll::Complete
        );

        let mut out = [0_u8; 4];
        let CursorPoll::Ready(Some(chunk)) = client.try_read_row_plp_complete(2, &mut out).unwrap()
        else {
            panic!("complete buffered PLP should not require async continuation");
        };
        assert_eq!(out, [b'o', 0, b'k', 0]);
        assert_eq!(chunk.read, 4);
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 3
        ));
    }

    #[tokio::test]
    async fn try_finish_row_into_completes_a_fully_buffered_row() {
        let expected = [11_i32, 22_i32];
        let mut payload = vec![0xff];
        payload.extend(expected.iter().flat_map(|value| value.to_le_bytes()));
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        // Force a packet read so the int columns are already buffered before
        // `try_finish_row_into` runs its synchronous, buffer-only pass.
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 0,
            metadata: int_column_metadata(expected.len()),
            nbc_null_bitmap: None,
            decryptor: None,
        }));
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(expected.len());

        assert!(client.try_finish_row_into(&mut writer).unwrap());
        assert_eq!(
            writer.take_row(),
            expected
                .into_iter()
                .map(ColumnValues::Int)
                .collect::<Vec<_>>()
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));
    }

    #[tokio::test]
    async fn next_row_into_uses_buffered_dispatch() {
        let expected = [0x1234_5678_i32, -42_i32];
        let mut payload = vec![0xff, TokenType::Row as u8];
        payload.extend(expected.iter().flat_map(|value| value.to_le_bytes()));
        let mut packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut transport =
            create_network_transport_with_data(&packet.append_bytes(&payload).build());
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(int_column_metadata(expected.len()));
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(expected.len());

        assert!(client.next_row_into(&mut writer).await.unwrap());
        assert_eq!(
            writer.take_row(),
            expected
                .into_iter()
                .map(ColumnValues::Int)
                .collect::<Vec<_>>()
        );
    }

    #[tokio::test]
    async fn next_row_into_continues_a_partial_buffered_row() {
        let expected = [0x1234_5678_i32, -42_i32];
        let second = expected[1].to_le_bytes();
        let mut first_payload = vec![0xff, TokenType::Row as u8];
        first_payload.extend_from_slice(&expected[0].to_le_bytes());
        first_payload.extend_from_slice(&second[..2]);
        let mut first = TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut second_packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut stream = first.continuation().append_bytes(&first_payload).build();
        stream.extend_from_slice(&second_packet.append_bytes(&second[2..]).build());
        let mut transport = create_network_transport_with_data(&stream);
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(int_column_metadata(expected.len()));
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(expected.len());

        assert!(client.next_row_into(&mut writer).await.unwrap());
        assert_eq!(
            writer.take_row(),
            expected
                .into_iter()
                .map(ColumnValues::Int)
                .collect::<Vec<_>>()
        );
    }

    #[tokio::test]
    async fn buffered_row_poll_parks_only_an_incomplete_row() {
        let expected = [0x1234_5678_i32, -42_i32];
        let second = expected[1].to_le_bytes();
        let mut first_payload = vec![0xff, TokenType::Row as u8];
        first_payload.extend_from_slice(&expected[0].to_le_bytes());
        first_payload.extend_from_slice(&second[..2]);
        let mut first = TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut second_packet =
            TestPacketBuilder::new(crate::message::messages::PacketType::TabularResult);
        let mut stream = first.continuation().append_bytes(&first_payload).build();
        stream.extend_from_slice(&second_packet.append_bytes(&second[2..]).build());
        let mut transport = create_network_transport_with_data(&stream);
        assert_eq!(transport.read_byte().await.unwrap(), 0xff);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(int_column_metadata(expected.len()));
        client.current_result_set_has_been_read_till_end = false;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(expected.len());

        assert_eq!(
            client.try_next_buffered_row_into(&mut writer).unwrap(),
            BufferedRowPoll::Partial
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 1
        ));
        client.finish_row_into(&mut writer).await.unwrap();
        assert_eq!(
            writer.take_row(),
            expected
                .into_iter()
                .map(ColumnValues::Int)
                .collect::<Vec<_>>()
        );
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));
    }

    #[test]
    fn sync_cursor_pending_leaves_cursor_state_untouched() {
        let mut client = create_test_client();
        client.current_metadata = Some(int_column_metadata(1));
        client.current_result_set_has_been_read_till_end = false;

        assert_eq!(client.try_next_row_cursor().unwrap(), CursorPoll::Pending);
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));

        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 0,
            metadata: int_column_metadata(1),
            nbc_null_bitmap: None,
            decryptor: None,
        }));
        assert_eq!(client.try_read_row_column(0).unwrap(), CursorPoll::Pending);
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 0
        ));
    }

    #[test]
    fn sync_cursor_ready_preserves_explicit_zero_timeout() {
        let metadata = int_column_metadata(1);
        let mut transport = TestTransport::new();
        transport.sync_header_available = true;
        transport.sync_columns.push_back(ColumnValues::Int(42));
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(metadata);
        client.current_result_set_has_been_read_till_end = false;
        client.remaining_request_timeout = Some(Duration::ZERO);

        assert_eq!(
            client.try_next_row_cursor().unwrap(),
            CursorPoll::Ready(true)
        );
        assert_eq!(
            client.try_read_row_column(0).unwrap(),
            CursorPoll::Ready(CursorColumn::Value {
                value: ColumnValues::Int(42),
                variant_base: None,
            })
        );
        assert_eq!(client.remaining_request_timeout, Some(Duration::ZERO));
    }

    #[test]
    fn sync_cursor_defers_cancelled_operations_without_consuming_state() {
        let metadata = int_column_metadata(1);
        let mut transport = TestTransport::new();
        transport.sync_header_available = true;
        transport.sync_columns.push_back(ColumnValues::Int(42));
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(Arc::clone(&metadata));
        client.current_result_set_has_been_read_till_end = false;
        let cancellation = CancelHandle::new();
        client.cancel_handle = Some(cancellation.child_handle());
        cancellation.cancel();

        assert_eq!(client.try_next_row_cursor().unwrap(), CursorPoll::Pending);
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));

        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 0,
            metadata,
            nbc_null_bitmap: None,
            decryptor: None,
        }));
        assert_eq!(client.try_read_row_column(0).unwrap(), CursorPoll::Pending);
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 0
        ));
    }

    #[test]
    fn try_read_active_plp_chunk_defers_when_cancelled() {
        let mut client = create_test_client();
        let cancellation = CancelHandle::new();
        client.cancel_handle = Some(cancellation.child_handle());
        cancellation.cancel();

        let mut out = [0_u8; 4];
        assert_eq!(
            client.try_read_active_plp_chunk(&mut out).unwrap(),
            CursorPoll::Pending
        );
    }

    #[test]
    fn try_read_active_plp_chunk_errors_without_an_active_stream() {
        let mut client = create_test_client();
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));

        let mut out = [0_u8; 4];
        let error = client.try_read_active_plp_chunk(&mut out).unwrap_err();
        assert!(matches!(error, UsageError(_)));
    }

    #[test]
    fn row_writer_finish_is_limited_to_non_plp_results() {
        let mut client = create_test_client();
        assert!(!client.current_result_supports_row_into());
        assert!(!client.buffered_row_support());
        assert_eq!(client.current_result_bufferable_prefix_len(), None);

        client.current_metadata = Some(int_column_metadata(1));
        assert!(client.current_result_supports_row_into());
        assert!(client.buffered_row_support());
        assert!(client.buffered_row_support());

        let column = crate::query::metadata::ColumnMetadata {
            user_type: 0,
            flags: 0,
            type_info: crate::datatypes::sqldatatypes::TypeInfo::partial_len(
                crate::datatypes::sqldatatypes::TdsDataType::BigVarBinary,
                usize::from(u16::MAX),
                None,
            )
            .unwrap(),
            data_type: crate::datatypes::sqldatatypes::TdsDataType::BigVarBinary,
            column_name: "payload".to_string(),
            multi_part_name: None,
            crypto_metadata: None,
        };
        client.current_metadata = Some(Arc::new(ColMetadataToken {
            column_count: 1,
            columns: vec![column],
            cek_table: vec![],
        }));
        assert!(!client.current_result_supports_row_into());
        assert!(!client.buffered_row_support());
        assert_eq!(client.current_result_bufferable_prefix_len(), None);
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(1);
        assert_eq!(
            client.try_next_buffered_row_into(&mut writer).unwrap(),
            BufferedRowPoll::Pending
        );
    }

    #[test]
    fn prefix_eligibility_requires_inline_columns_and_no_encryption() {
        let mut client = create_test_client();
        client.current_metadata = Some(mixed_lob_metadata(2));
        assert_eq!(client.current_result_bufferable_prefix_len(), Some(2));

        client.current_metadata = Some(mixed_lob_metadata(0));
        assert_eq!(client.current_result_bufferable_prefix_len(), None);

        let mut encrypted = mixed_lob_metadata(2).as_ref().clone();
        encrypted.columns[0].crypto_metadata = Some(ae_crypto_metadata());
        client.current_metadata = Some(Arc::new(encrypted));
        assert_eq!(client.current_result_bufferable_prefix_len(), None);
    }

    #[test]
    fn buffered_cursor_edge_states_preserve_the_async_fallback_contract() {
        let mut client = create_test_client();
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(2);

        assert!(client.try_next_row_cursor().is_err());
        assert!(client.try_next_buffered_row_into(&mut writer).is_err());

        let metadata = int_column_metadata(2);
        client.current_metadata = Some(Arc::clone(&metadata));
        client.current_result_set_has_been_read_till_end = true;
        assert_eq!(
            client.try_next_row_cursor().unwrap(),
            CursorPoll::Ready(false)
        );
        assert_eq!(
            client.try_next_buffered_row_into(&mut writer).unwrap(),
            BufferedRowPoll::Exhausted
        );

        client.current_result_set_has_been_read_till_end = false;
        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 1,
            metadata,
            nbc_null_bitmap: None,
            decryptor: None,
        }));
        assert_eq!(client.try_next_row_cursor().unwrap(), CursorPoll::Pending);
        assert_eq!(
            client.try_next_buffered_row_into(&mut writer).unwrap(),
            BufferedRowPoll::Pending
        );
        assert_eq!(
            client.try_read_row_column(0).unwrap(),
            CursorPoll::Ready(CursorColumn::AlreadyConsumed)
        );
        assert!(client.try_read_row_column(2).is_err());
        assert_eq!(client.try_read_row_column(1).unwrap(), CursorPoll::Pending);
        assert!(!client.try_finish_row_into(&mut writer).unwrap());

        let cancellation = CancelHandle::new();
        client.cancel_handle = Some(cancellation.child_handle());
        cancellation.cancel();
        assert!(!client.try_finish_row_into(&mut writer).unwrap());
        client.cancel_handle = None;

        client.active_row_read_state = ActiveRowReadState::Idle;
        assert!(client.try_finish_row_into(&mut writer).is_err());

        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 0,
            metadata: int_column_metadata(3),
            nbc_null_bitmap: None,
            decryptor: None,
        }));
        assert_eq!(client.try_read_row_column(1).unwrap(), CursorPoll::Pending);
    }

    #[tokio::test]
    async fn finish_row_into_rejects_non_resumable_state() {
        let mut client = create_test_client();
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(1);

        assert!(client.finish_row_into(&mut writer).await.is_err());
        assert!(matches!(
            client.active_row_read_state,
            ActiveRowReadState::Idle
        ));
    }

    #[tokio::test]
    async fn finish_row_into_handles_transport_outcomes() {
        fn paused() -> RowPauseState {
            RowPauseState {
                next_column_index: 0,
                metadata: int_column_metadata(1),
                nbc_null_bitmap: None,
                decryptor: None,
            }
        }

        let mut complete_transport = TestTransport::new();
        complete_transport
            .resume_results
            .push_back(RowReadResult::RowWritten);
        let mut complete = create_test_client_with_transport(complete_transport);
        complete.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused()));
        complete.remaining_request_timeout = Some(Duration::from_secs(1));
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(1);
        complete.finish_row_into(&mut writer).await.unwrap();
        assert!(matches!(
            complete.active_row_read_state,
            ActiveRowReadState::Idle
        ));

        let mut paused_transport = TestTransport::new();
        paused_transport
            .resume_results
            .push_back(RowReadResult::RowPaused(paused()));
        let mut still_paused = create_test_client_with_transport(paused_transport);
        still_paused.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused()));
        assert!(still_paused.finish_row_into(&mut writer).await.is_err());
        assert!(matches!(
            still_paused.active_row_read_state,
            ActiveRowReadState::RowPaused(_)
        ));

        let mut token_transport = TestTransport::new();
        token_transport
            .resume_results
            .push_back(RowReadResult::Token(done_no_more()));
        let mut token = create_test_client_with_transport(token_transport);
        token.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused()));
        assert!(token.finish_row_into(&mut writer).await.is_err());

        let mut failed = create_test_client();
        failed.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused()));
        assert!(failed.finish_row_into(&mut writer).await.is_err());
    }

    #[tokio::test]
    async fn finish_row_prefix_into_handles_transport_outcomes() {
        fn paused_at(next_column_index: usize) -> RowPauseState {
            RowPauseState {
                next_column_index,
                metadata: int_column_metadata(2),
                nbc_null_bitmap: None,
                decryptor: None,
            }
        }

        const PREFIX_LEN: usize = 1;
        let mut writer = crate::datatypes::row_writer::DefaultRowWriter::new(2);

        // `RowPaused` at the requested prefix boundary succeeds.
        let mut ok_transport = TestTransport::new();
        ok_transport
            .resume_results
            .push_back(RowReadResult::RowPaused(paused_at(PREFIX_LEN)));
        let mut ok = create_test_client_with_transport(ok_transport);
        ok.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused_at(0)));
        ok.finish_row_prefix_into(PREFIX_LEN, &mut writer)
            .await
            .unwrap();
        assert!(matches!(
            ok.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == PREFIX_LEN
        ));

        // `RowPaused` at a different column than requested is a protocol error.
        let mut wrong_column_transport = TestTransport::new();
        wrong_column_transport
            .resume_results
            .push_back(RowReadResult::RowPaused(paused_at(0)));
        let mut wrong_column = create_test_client_with_transport(wrong_column_transport);
        wrong_column.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused_at(0)));
        assert!(matches!(
            wrong_column
                .finish_row_prefix_into(PREFIX_LEN, &mut writer)
                .await,
            Err(crate::error::Error::ProtocolError(_))
        ));
        assert!(matches!(
            wrong_column.active_row_read_state,
            ActiveRowReadState::RowPaused(ref state) if state.next_column_index == 0
        ));

        // Decoding the whole row instead of stopping at the prefix is also an error.
        let mut whole_row_transport = TestTransport::new();
        whole_row_transport
            .resume_results
            .push_back(RowReadResult::RowWritten);
        let mut whole_row = create_test_client_with_transport(whole_row_transport);
        whole_row.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused_at(0)));
        assert!(matches!(
            whole_row
                .finish_row_prefix_into(PREFIX_LEN, &mut writer)
                .await,
            Err(crate::error::Error::ProtocolError(_))
        ));

        // Pausing at a PLP header before reaching the requested prefix is an error.
        let plp_metadata = mixed_lob_metadata(2);
        let Some((Some(plp_stream), _used)) =
            crate::datatypes::decoder::PlpColumnStream::try_begin_buffered(
                &plp_metadata.columns[2],
                &4_u64.to_le_bytes(),
            )
            .unwrap()
        else {
            panic!("a known-length PLP header must yield a started stream");
        };
        let plp_pause = PlpPauseState {
            row_pause_state: paused_at(2),
            plp_stream,
        };
        let mut plp_transport = TestTransport::new();
        plp_transport
            .resume_results
            .push_back(RowReadResult::PlpPaused(plp_pause));
        let mut plp = create_test_client_with_transport(plp_transport);
        plp.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused_at(0)));
        assert!(matches!(
            plp.finish_row_prefix_into(PREFIX_LEN, &mut writer).await,
            Err(crate::error::Error::ProtocolError(_))
        ));
        assert!(matches!(
            plp.active_row_read_state,
            ActiveRowReadState::PlpPaused(_)
        ));

        // A control token in place of a row is a protocol error.
        let mut token_transport = TestTransport::new();
        token_transport
            .resume_results
            .push_back(RowReadResult::Token(done_no_more()));
        let mut token = create_test_client_with_transport(token_transport);
        token.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused_at(0)));
        assert!(matches!(
            token.finish_row_prefix_into(PREFIX_LEN, &mut writer).await,
            Err(crate::error::Error::ProtocolError(_))
        ));

        // A transport failure propagates and aborts any pending prepare capture.
        let mut failed = create_test_client();
        failed.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(paused_at(0)));
        assert!(
            failed
                .finish_row_prefix_into(PREFIX_LEN, &mut writer)
                .await
                .is_err()
        );
    }

    // ── PLP streaming lifecycle contract tests ──

    #[tokio::test]
    async fn plp_read_bytes_no_active_stream_errors() {
        let mut client = create_test_client();
        let mut buf = [0u8; 4];

        // With no PLP stream positioned this is a sequencing error, not EOF:
        // an `Ok(0)` here would be indistinguishable from an exhausted stream.
        let err = client
            .read_active_plp_bytes(&mut buf)
            .await
            .expect_err("read with no active PLP stream must error");

        assert!(
            matches!(err, UsageError(_)),
            "expected UsageError, got {err:?}"
        );
    }

    #[test]
    fn plp_reached_end_returns_true_when_no_stream_active() {
        let client = create_test_client();

        assert!(client.active_plp_reached_end());
    }

    #[tokio::test]
    async fn read_row_column_carries_stream_collation_on_plp_variant() {
        // When resuming to a PLP column, the fixed stream collation must ride on
        // the `CursorColumn::PlpStreaming` variant so callers get it atomically
        // with the "this is a PLP column" signal, without a separate lookup.
        let collation = SqlCollation {
            info: 0x0409,
            lcid_language_id: 0x0409,
            col_flags: 0,
            sort_id: 52,
        };
        let metadata = crate::query::metadata::ColumnMetadata {
            user_type: 0,
            flags: 0,
            type_info: crate::datatypes::sqldatatypes::TypeInfo::partial_len(
                crate::datatypes::sqldatatypes::TdsDataType::BigVarChar,
                0xFFFF,
                Some(collation),
            )
            .unwrap(),
            data_type: crate::datatypes::sqldatatypes::TdsDataType::BigVarChar,
            column_name: "c1".to_string(),
            multi_part_name: None,
            crypto_metadata: None,
        };
        let mut reader = TestTransport::with_packet_data((-2_i64).to_le_bytes().to_vec());
        let plp_stream = crate::datatypes::decoder::PlpColumnStream::begin(&metadata, &mut reader)
            .await
            .unwrap()
            .unwrap();
        let row_metadata = Arc::new(ColMetadataToken {
            column_count: 1,
            columns: vec![metadata.clone()],
            cek_table: vec![],
        });
        let inner_pause_state = RowPauseState {
            next_column_index: 1,
            metadata: Arc::clone(&row_metadata),
            nbc_null_bitmap: None,
            decryptor: None,
        };

        // The mock replays this `PlpPaused` result from `resume_row_into`, so the
        // cursor takes the branch that builds `PlpStreaming { collation }`.
        let mut transport = TestTransport::new();
        transport
            .resume_results
            .push_back(RowReadResult::PlpPaused(PlpPauseState {
                row_pause_state: inner_pause_state,
                plp_stream,
            }));

        let mut client = create_test_client_with_transport(transport);
        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 0,
            metadata: row_metadata,
            nbc_null_bitmap: None,
            decryptor: None,
        }));

        let outcome = client.read_row_column(0).await.unwrap();
        assert_eq!(
            outcome,
            CursorColumn::PlpStreaming {
                collation: Some(collation)
            },
            "PLP stream collation must ride on the variant"
        );
    }

    #[test]
    fn plp_helpers_treat_non_plp_row_pause_as_no_active_stream() {
        let mut client = create_test_client();
        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 1,
            metadata: Arc::new(ColMetadataToken::default()),
            nbc_null_bitmap: None,
            decryptor: None,
        }));

        assert!(client.active_plp_reached_end());
    }

    #[tokio::test]
    async fn next_row_into_rejects_active_pull_cursor_row() {
        // A row parked by the pull cursor (`next_row_cursor`) must not be
        // silently drained by the push path. Mixing the two would discard the
        // parked row and hand back the *next* one, so the earlier
        // `next_row_cursor() == true` would map to a row the caller never sees.
        let mut client = create_test_client();
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = false;
        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 1,
            metadata: Arc::new(ColMetadataToken::default()),
            nbc_null_bitmap: None,
            decryptor: None,
        }));

        let mut sink = DiscardRowWriter;
        let err = client
            .next_row_into(&mut sink)
            .await
            .expect_err("push path must reject a parked pull-cursor row");
        assert!(
            matches!(err, UsageError(_)),
            "expected UsageError, got {err:?}"
        );

        // The guard must leave the parked row in place (not consume the wire),
        // so the caller can still finish it with `next_row_cursor`.
        assert!(
            matches!(
                client.active_row_read_state,
                ActiveRowReadState::RowPaused(_)
            ),
            "guard must not disturb the parked row state"
        );
    }

    #[tokio::test]
    async fn peek_past_current_row_reports_end_of_set_and_releases_batch() {
        // Every column of the current row has already been read (the caller's
        // obligation), so `active_row_read_state` is `Idle` and the wire's next
        // token is the terminating DONE — exactly what the ODBC busy gate uses
        // to release a connection early instead of waiting for an explicit
        // cursor close (AB#47508).
        let transport = TestTransport::with_tokens(vec![done_no_more()]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = false;
        client.execution_context.set_has_open_batch(true);

        let has_more = client.peek_past_current_row().await.unwrap();

        assert!(!has_more, "no more rows: the DONE carried no MORE flag");
        assert!(client.current_result_set_has_been_read_till_end);
        assert!(!client.has_open_batch());
        assert!(
            !client.row_already_positioned,
            "nothing was parked; the flag must stay clear"
        );
    }

    #[tokio::test]
    async fn complete_current_result_drains_rpc_tail_and_captures_prepared_handle() {
        let transport = TestTransport::with_tokens(vec![
            done_in_proc_more(),
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            Tokens::ReturnStatus(ReturnStatusToken { value: 0 }),
            done_proc_no_more(),
        ]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = false;
        client.execution_context.set_has_open_batch(true);
        client.pending_capture = Some(sid(1));

        assert!(!client.peek_past_current_row().await.unwrap());
        assert!(client.has_open_batch(), "DONE_MORE keeps the RPC open");
        assert!(client.complete_current_result().await.unwrap());

        assert!(!client.has_open_batch());
        assert_eq!(client.prepared_handles.get(&sid(1)).copied(), Some(9));
        assert!(matches!(
            client.last_return_status,
            ReturnStatus::Received(0)
        ));
    }

    #[tokio::test]
    async fn complete_current_result_retires_a_truncated_rpc_tail() {
        let transport = TestTransport::with_tokens(vec![done_in_proc_more()]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = false;
        client.execution_context.set_has_open_batch(true);

        assert!(!client.peek_past_current_row().await.unwrap());
        assert!(matches!(
            client.complete_current_result().await,
            Err(crate::error::Error::ConnectionClosed(_))
        ));
        assert!(!client.has_open_batch());
        assert!(client.is_connection_dead());
        assert!(client.current_result_set_has_been_read_till_end);
    }

    #[tokio::test]
    async fn advancing_to_a_no_row_result_clears_the_rpc_tail_gate() {
        let transport = TestTransport::with_tokens(vec![
            done_in_proc_more(),
            done_count(CurrentCommand::Update, 3, true),
        ]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.execution_context.set_has_open_batch(true);

        assert!(!client.peek_past_current_row().await.unwrap());
        assert!(!client.complete_current_result().await.unwrap());
        assert!(client.current_result_ended_with_done_in_proc);

        assert!(matches!(
            client.advance().await,
            Ok(StatementResult::NoRows {
                rows_affected: Some(3)
            })
        ));
        assert!(
            !client.current_result_ended_with_done_in_proc,
            "a plain batch DONE must not leave the previous RPC's tail gate armed"
        );
    }

    #[tokio::test]
    async fn complete_current_result_abandons_the_batch_when_a_tail_token_fails() {
        // The tail parses far enough to park the next result, then reports the
        // failed RETURNVALUE. Leaving that batch open would strand the ODBC
        // busy claim on a statement whose cursor is already finished.
        let transport = TestTransport::with_tokens(vec![
            done_in_proc_more(),
            Tokens::ReturnValue(ae_return_value_token(
                "@out",
                ColumnValues::Bytes(vec![1, 2, 3]),
                Some(ae_crypto_metadata()),
            )),
            empty_col_metadata(),
            done_no_more(),
        ]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Enabled;
        client.execution_context.set_has_open_batch(true);

        assert!(!client.peek_past_current_row().await.unwrap());
        assert!(matches!(
            client.complete_current_result().await,
            Err(crate::error::Error::ColumnEncryptionError(_))
        ));
        assert!(!client.has_open_batch());
        assert!(client.parked_token.is_none());
    }

    #[tokio::test]
    async fn advance_abandons_the_batch_when_a_tail_token_fails() {
        // The other `settle_rpc_terminator` call site. Propagating the failure
        // with the batch still open would mask it behind ALREADY_EXECUTING_ERROR
        // on every later command for the whole connection.
        let transport = TestTransport::with_tokens(vec![
            info_token(0, 0, "print"),
            done_in_proc_more(),
            Tokens::ReturnValue(ae_return_value_token(
                "@out",
                ColumnValues::Bytes(vec![1, 2, 3]),
                Some(ae_crypto_metadata()),
            )),
            empty_col_metadata(),
            done_no_more(),
        ]);
        let mut client = create_test_client_with_transport(transport);
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Enabled;
        client.current_result_set_has_been_read_till_end = true;
        client.execution_context.set_has_open_batch(true);

        assert!(matches!(
            client.advance().await,
            Err(crate::error::Error::ColumnEncryptionError(_))
        ));
        assert!(!client.command_is_busy());
        assert!(client.parked_token.is_none());
    }

    #[tokio::test]
    async fn complete_current_result_parks_a_following_rowset() {
        let transport = TestTransport::with_tokens(vec![
            done_in_proc_more(),
            empty_col_metadata(),
            done_no_more(),
        ]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = false;
        client.execution_context.set_has_open_batch(true);

        assert!(!client.peek_past_current_row().await.unwrap());
        assert!(!client.complete_current_result().await.unwrap());
        assert!(client.current_result_set_has_been_read_till_end);
        assert!(client.has_open_batch());

        assert!(matches!(client.advance().await, Ok(StatementResult::Rows)));
        assert!(!client.current_result_set_has_been_read_till_end);

        client.close_query().await.unwrap();
        assert!(client.parked_token.is_none());
        assert!(!client.has_open_batch());
    }

    #[tokio::test]
    async fn peek_past_current_row_already_exhausted_touches_nothing() {
        // Calling the peek when `next_row_cursor` would already short-circuit
        // (end of set previously observed) must stay free: the ODBC layer
        // calls this unconditionally after every fetch, so it must not cost an
        // extra wire round trip when the answer is already known. An empty
        // token queue makes any real transport read fail the test.
        let transport = TestTransport::with_tokens(vec![]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = true;

        let has_more = client.peek_past_current_row().await.unwrap();

        assert!(!has_more);
        assert!(!client.row_already_positioned);
    }

    #[tokio::test]
    async fn next_row_cursor_returns_a_parked_row_without_reading_the_wire() {
        // Simulates the outcome of a prior `peek_past_current_row` call that
        // found another row: `active_row_read_state` already holds it and
        // `row_already_positioned` marks it unclaimed. The very next
        // `next_row_cursor` call must hand it back directly — not drain it as
        // an abandoned row and not touch the transport — so an empty token
        // queue still succeeds.
        let transport = TestTransport::with_tokens(vec![]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = false;
        client.row_already_positioned = true;
        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 0,
            metadata: Arc::new(ColMetadataToken::default()),
            nbc_null_bitmap: None,
            decryptor: None,
        }));

        let has_row = client.next_row_cursor().await.unwrap();

        assert!(has_row);
        assert!(
            !client.row_already_positioned,
            "the parked row is claimed exactly once"
        );
        assert!(
            matches!(
                client.active_row_read_state,
                ActiveRowReadState::RowPaused(_)
            ),
            "the parked row itself must still be there for read_row_column"
        );
    }

    #[tokio::test]
    async fn next_row_cursor_drains_an_unclaimed_parked_row_as_abandoned() {
        // If the caller moves on without ever consuming a parked row (no
        // `read_row_column` call in between), a second `next_row_cursor` call
        // must treat it like any other abandoned row: drain it and read the
        // next thing on the wire, rather than returning it a second time.
        let mut transport = TestTransport::with_tokens(vec![done_no_more()]);
        // The drain resumes the parked row's remaining columns first; the mock
        // reports that skip completing cleanly (nothing revealed yet), so the
        // subsequent read genuinely comes from `receive_row_header` below —
        // matching the two-step shape a real skip-then-read-next-token would
        // have on the wire.
        transport
            .resume_results
            .push_back(RowReadResult::RowWritten);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.current_result_set_has_been_read_till_end = false;
        client.active_row_read_state = ActiveRowReadState::RowPaused(Box::new(RowPauseState {
            next_column_index: 0,
            metadata: Arc::new(ColMetadataToken::default()),
            nbc_null_bitmap: None,
            decryptor: None,
        }));
        // Deliberately NOT setting `row_already_positioned`: this row was
        // positioned by ordinary means (or a peek already claimed and it is
        // being abandoned unread), so the next call must drain it.

        let has_row = client.next_row_cursor().await.unwrap();

        assert!(!has_row, "the row was discarded; DONE was next on the wire");
        assert!(client.current_result_set_has_been_read_till_end);
    }

    #[test]
    fn normalize_param_name_strips_at_and_uppercases() {
        // A single leading '@' is stripped and the name is ASCII-uppercased, so a
        // describe parameter name, an RPC parameter name, and a RETURNVALUE name
        // for the same parameter all normalize to the same key.
        assert_eq!(TdsClient::normalize_param_name("@Out"), "OUT");
        assert_eq!(TdsClient::normalize_param_name("out"), "OUT");
        assert_eq!(TdsClient::normalize_param_name("@p1"), "P1");
        // Only one leading '@' is stripped.
        assert_eq!(TdsClient::normalize_param_name("@@version"), "@VERSION");
        assert_eq!(TdsClient::normalize_param_name(""), "");
    }

    #[tokio::test]
    async fn complete_current_result_does_not_probe_a_plain_batch() {
        let transport = TestTransport::with_tokens(vec![done_more(), empty_col_metadata()]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.execution_context.set_has_open_batch(true);

        assert!(!client.peek_past_current_row().await.unwrap());
        assert!(!client.complete_current_result().await.unwrap());
        assert!(client.parked_token.is_none());
        assert!(matches!(client.advance().await, Ok(StatementResult::Rows)));
    }

    #[tokio::test]
    async fn complete_current_result_requires_an_exhausted_rowset() {
        let mut client = create_test_client_with_tokens(vec![done_in_proc_more()]);
        client.execution_context.set_has_open_batch(true);

        assert!(!client.complete_current_result().await.unwrap());
        assert!(client.execution_context.has_open_batch());
    }

    #[tokio::test]
    async fn complete_current_result_disarms_recovery_when_attention_cleanup_fails() {
        let transport = TestTransport::with_tokens(vec![done_in_proc_more()]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.execution_context.set_has_open_batch(true);
        client.recovery_context.session_recovery_negotiated = true;

        assert!(!client.peek_past_current_row().await.unwrap());
        let cancellation = CancelHandle::new();
        client.cancel_handle = Some(cancellation.child_handle());
        cancellation.cancel();
        client.transport.mark_known_dead();

        assert!(matches!(
            client.complete_current_result().await,
            Err(crate::error::Error::OperationCancelledError(_))
        ));
        assert!(!client.recovery_context.session_recovery_negotiated);
        assert!(!client.has_open_batch());
    }

    #[tokio::test]
    async fn complete_current_result_preserves_recovery_when_cancel_leaves_transport_alive() {
        let transport = TestTransport::with_tokens(vec![done_in_proc_more()]);
        let mut client = create_test_client_with_transport(transport);
        client.current_metadata = Some(stale_metadata());
        client.execution_context.set_has_open_batch(true);
        client.recovery_context.session_recovery_negotiated = true;

        assert!(!client.peek_past_current_row().await.unwrap());
        let cancellation = CancelHandle::new();
        client.cancel_handle = Some(cancellation.child_handle());
        cancellation.cancel();

        assert!(matches!(
            client.complete_current_result().await,
            Err(crate::error::Error::OperationCancelledError(_))
        ));
        assert!(client.recovery_context.session_recovery_negotiated);
        assert!(!client.is_connection_dead());
        assert!(!client.has_open_batch());
    }

    #[tokio::test]
    async fn next_row_into_is_idempotent_after_end_without_metadata() {
        let mut client = create_test_client();
        client.current_metadata = None;
        client.current_result_set_has_been_read_till_end = true;
        let mut sink = DiscardRowWriter;

        assert!(
            !ResultSet::next_row_into(&mut client, &mut sink)
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn consume_done_token_captures_all_info_tokens() {
        let mut client = create_test_client_with_tokens(vec![
            info_token(5701, 10, "Changed database context to 'master'."),
            info_token(0, 0, "hello from PRINT"),
            done_no_more(),
        ]);

        let rows_affected = client.consume_done_token().await.unwrap();

        assert_eq!(rows_affected, 0);
        assert_eq!(client.info_messages().len(), 2);
        assert_eq!(client.info_messages()[0].number, 5701);
        assert_eq!(client.info_messages()[0].class, 10);
        assert_eq!(client.info_messages()[1].message, "hello from PRINT");

        let messages = client.take_info_messages();
        assert_eq!(messages.len(), 2);
        assert!(client.info_messages().is_empty());
    }

    #[tokio::test]
    async fn consume_done_token_takes_single_counted_done() {
        // A normal (non-distributed) engine reports the bulk-load row count in a
        // single DONE_COUNT token.
        let mut client =
            create_test_client_with_tokens(vec![done_count(CurrentCommand::Insert, 5000, false)]);

        let rows_affected = client.consume_done_token().await.unwrap();

        assert_eq!(rows_affected, 5000);
    }

    #[tokio::test]
    async fn consume_done_token_does_not_double_count_distributed_dones() {
        // Regression for #209: a distributed engine (Fabric Warehouse) acknowledges
        // one bulk load with two DONE_COUNT tokens, each carrying the full count.
        // Summing them would report 2x; the authoritative value is the count itself.
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Insert, 5000, true),
            done_count(CurrentCommand::Insert, 5000, false),
        ]);

        let rows_affected = client.consume_done_token().await.unwrap();

        assert_eq!(rows_affected, 5000);
    }

    #[tokio::test]
    async fn consume_done_token_ignores_uncounted_dones() {
        // A DONE without the COUNT flag carries a meaningless row_count that must
        // not contribute to the total. This uncounted token deliberately carries a
        // non-zero row_count (7) so the pre-fix summing behavior would report 3007;
        // reporting 3000 proves the has_count() guard, not an incidental zero.
        let mut client = create_test_client_with_tokens(vec![
            Tokens::Done(DoneToken {
                status: DoneStatus::MORE,
                cur_cmd: CurrentCommand::Insert,
                row_count: 7,
            }),
            done_count(CurrentCommand::Insert, 3000, false),
        ]);

        let rows_affected = client.consume_done_token().await.unwrap();

        assert_eq!(rows_affected, 3000);
    }

    /// A single-INT-column row used to drive the streaming bulk-load path.
    struct IntRow(i32);

    #[async_trait]
    impl BulkLoadRow for IntRow {
        async fn write_to_packet(
            &self,
            writer: &mut StreamingBulkLoadWriter<'_>,
            column_index: &mut usize,
        ) -> TdsResult<()> {
            use crate::datatypes::column_values::ColumnValues;
            writer
                .write_column_value(*column_index, &ColumnValues::Int(self.0))
                .await?;
            *column_index += 1;
            Ok(())
        }
    }

    #[tokio::test]
    async fn bulk_load_reports_client_rows_not_server_done_count() {
        // Regression for #209: the count reported to callers must be the number
        // of rows the client streamed to the wire — matching
        // `SqlBulkCopy.RowsCopied` and ODBC bcp (`llRowsCopiedInLastBCP`), both
        // of which count outgoing rows client-side — and must never be derived
        // from the server's DONE_COUNT. Distributed engines (Fabric Warehouse,
        // EngineEdition 11) acknowledge one bulk load with more than one
        // DONE_COUNT token, so trusting the server count double-counted.
        //
        // The mock server here returns a deliberately wrong count (999) in each
        // DONE_COUNT token; the client wrote 3 rows and must report exactly 3,
        // which is only possible if the reported value is the client-side count.
        use crate::datatypes::bulk_copy_metadata::{SqlDbType, TypeLength};
        use crate::datatypes::sqldatatypes::TdsDataType;

        let mut client = create_test_client_with_tokens(vec![
            // STEP 2: response to the INSERT BULK preamble command.
            done_no_more(),
            // STEP 5: distributed bulk-load acknowledgement — two DONE_COUNT
            // tokens, each carrying a bogus (non-client) count.
            done_count(CurrentCommand::Insert, 999, true),
            done_count(CurrentCommand::BulkInsert, 999, false),
        ]);

        let column_metadata = vec![
            BulkCopyColumnMetadata::new("id", SqlDbType::Int, TdsDataType::Int4 as u8)
                .with_length(4, TypeLength::Fixed(4)),
        ];

        let rows = vec![IntRow(10), IntRow(20), IntRow(30)];

        let reported = client
            .execute_bulk_load_streaming_zerocopy(
                "#t".to_string(),
                column_metadata,
                BulkCopyOptions::default(),
                None,
                None,
                rows.into_iter(),
                &[],
            )
            .await
            .expect("bulk load should succeed against the mock transport");

        assert_eq!(
            reported, 3,
            "must report the 3 client-written rows, not the server DONE_COUNT (999)"
        );
    }

    #[test]
    fn begin_command_clears_stale_info_messages() {
        // Simulates login/connect messages left on the client before a new
        // command starts. `begin_command` (called at the top of every execute*
        // entry point) must clear them so `info_messages()` reflects only the
        // current command.
        let mut client = create_test_client();
        client.extend_info_messages(vec![SqlInfoMessage::from(
            &crate::token::tokens::InfoToken {
                number: 5701,
                state: 1,
                severity: 10,
                message: "Changed database context to 'master'.".to_string(),
                server_name: "srv".to_string(),
                proc_name: String::new(),
                line_number: 1,
            },
        )]);
        assert_eq!(client.info_messages().len(), 1);

        client.begin_command();
        assert!(
            client.info_messages().is_empty(),
            "begin_command must clear stale info messages"
        );
    }

    #[tokio::test]
    async fn execute_sp_unprepare_clears_stale_info_messages() {
        // Regression: token-consuming commands beyond the execute*/query family
        // (here sp_unprepare, which drains via drain_stream) must also reset the
        // info buffer so a prior command's messages don't leak into this one.
        let mut client = create_test_client_with_tokens(vec![
            info_token(0, 0, "unprepare info"),
            done_no_more(),
        ]);

        // Stale message left over from an earlier command / login.
        client.extend_info_messages(vec![SqlInfoMessage {
            message: "stale from previous command".to_string(),
            state: 1,
            class: 10,
            number: 5701,
            server_name: None,
            proc_name: None,
            line_number: None,
        }]);

        let statement_id = client.register_prepared_handle_for_test(1);
        client
            .execute_sp_unprepare_for_test(statement_id, ())
            .await
            .unwrap();

        let msgs = client.info_messages();
        assert!(
            msgs.iter()
                .all(|m| m.message != "stale from previous command"),
            "stale info from a prior command must be cleared: {msgs:?}"
        );
        assert!(
            msgs.iter().any(|m| m.message == "unprepare info"),
            "the current command's info should be captured: {msgs:?}"
        );
    }

    // ── finalize_return_value (encrypted RETURNVALUE decryption) tests ──

    /// Builds a minimal `CryptoMetadata` describing an encrypted `int` output
    /// parameter (AEAD cipher, base type `IntN`).
    fn ae_crypto_metadata() -> crate::query::metadata::CryptoMetadata {
        use crate::datatypes::sqldatatypes::{
            FixedLengthTypes, TdsDataType, TypeInfo, TypeInfoVariant,
        };
        crate::query::metadata::CryptoMetadata {
            cek_table_ordinal: 0,
            base_data_type: TdsDataType::IntN,
            base_type_info: TypeInfo {
                tds_type: TdsDataType::IntN,
                length: 4,
                type_info_variant: TypeInfoVariant::FixedLen(FixedLengthTypes::Int4),
            },
            cipher_algorithm_id: 2,
            cipher_algorithm_name: None,
            encryption_type: 1,
            normalization_rule_version: 1,
        }
    }

    /// Builds a RETURNVALUE token named `name` carrying `value`, with the given
    /// optional crypto metadata (present = encrypted output parameter).
    fn ae_return_value_token(
        name: &str,
        value: ColumnValues,
        crypto: Option<crate::query::metadata::CryptoMetadata>,
    ) -> crate::token::tokens::ReturnValueToken {
        use crate::datatypes::sqldatatypes::{
            FixedLengthTypes, TdsDataType, TypeInfo, TypeInfoVariant,
        };
        let column_metadata = crate::query::metadata::ColumnMetadata {
            user_type: 0,
            flags: if crypto.is_some() { 0x0800 } else { 0 },
            data_type: TdsDataType::BigVarBinary,
            type_info: TypeInfo {
                tds_type: TdsDataType::BigVarBinary,
                length: 8000,
                type_info_variant: TypeInfoVariant::FixedLen(FixedLengthTypes::Int4),
            },
            column_name: name.to_string(),
            multi_part_name: None,
            crypto_metadata: crypto,
        };
        crate::token::tokens::ReturnValueToken {
            param_ordinal: 0,
            param_name: name.to_string(),
            value,
            column_metadata: Box::new(column_metadata),
            status: crate::token::tokenitems::ReturnValueStatus::from(0u8),
        }
    }

    fn insert_test_cek(client: &mut TdsClient, name: &str, cek: Vec<u8>) {
        client.output_param_ceks.insert(
            TdsClient::normalize_param_name(name),
            std::sync::Arc::new(zeroize::Zeroizing::new(cek)),
        );
    }

    #[test]
    fn finalize_return_value_passes_through_plaintext() {
        // No crypto metadata => a plaintext RETURNVALUE is returned unchanged.
        let client = create_test_client();
        let token = ae_return_value_token("@out", ColumnValues::Int(7), None);
        let rv = client.finalize_return_value(token).unwrap();
        assert_eq!(rv.value, ColumnValues::Int(7));
    }

    #[test]
    fn finalize_return_value_passes_through_ciphertext_when_disabled() {
        // Encrypted value but the command disabled AE => ciphertext is passed
        // through unchanged and no CEK is consulted.
        let mut client = create_test_client();
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Disabled;
        let token = ae_return_value_token(
            "@out",
            ColumnValues::Bytes(vec![1, 2, 3]),
            Some(ae_crypto_metadata()),
        );
        let rv = client.finalize_return_value(token).unwrap();
        assert_eq!(rv.value, ColumnValues::Bytes(vec![1, 2, 3]));
    }

    #[test]
    fn finalize_return_value_errors_without_cek() {
        // Encrypted value under an enabled command but no retained CEK => error
        // rather than surfacing ciphertext.
        let mut client = create_test_client();
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Enabled;
        let token = ae_return_value_token(
            "@out",
            ColumnValues::Bytes(vec![1, 2, 3]),
            Some(ae_crypto_metadata()),
        );
        let err = client.finalize_return_value(token).unwrap_err();
        assert!(matches!(err, crate::error::Error::ColumnEncryptionError(_)));
    }

    #[test]
    fn attention_settlement_discards_encrypted_return_value_without_finalizing() {
        let mut client = create_test_client();
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Enabled;
        let token = ae_return_value_token(
            "@out",
            ColumnValues::Bytes(vec![1, 2, 3]),
            Some(ae_crypto_metadata()),
        );

        client
            .apply_attention_side_effect(Tokens::ReturnValue(token))
            .unwrap();

        assert!(client.return_values.is_empty());
        assert!(!client.transport.connection_known_dead());
    }

    #[test]
    fn attention_settlement_captures_plain_prepexec_handle() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;

        let mut client = create_test_client();
        client.pending_capture = Some(sid(4));
        let describe = Arc::new(DescribeParameterEncryptionResult::new());
        client.pending_prepared_param_encryption = Some(Arc::clone(&describe));
        let token = ae_return_value_token("@handle", ColumnValues::Int(27), None);

        client
            .apply_attention_side_effect(Tokens::ReturnValue(token))
            .unwrap();
        client.normalize_after_attention();

        assert_eq!(client.prepared_handles.get(&sid(4)).copied(), Some(27));
        assert!(Arc::ptr_eq(
            client.prepared_param_encryption.get(&sid(4)).unwrap(),
            &describe
        ));
        assert!(client.pending_capture.is_none());
        assert!(client.pending_prepared_param_encryption.is_none());
        assert!(client.return_values.is_empty());
    }

    #[test]
    fn attention_settlement_replays_connection_level_side_effects() {
        use crate::connection::transport::network_transport::AttentionSettlement;
        use crate::token::tokens::{
            EnvChangeContainer, EnvChangeToken, EnvChangeTokenSubType, ErrorToken,
            SessionStateToken,
        };

        let mut client = create_test_client();
        client.prepared_handles.insert(sid(1), 27);
        let tokens = vec![
            Tokens::Error(ErrorToken {
                number: 21,
                state: 1,
                severity: FATAL_ERROR_SEVERITY,
                message: "fatal server error".to_string(),
                server_name: "test-server".to_string(),
                proc_name: String::new(),
                line_number: 1,
            }),
            info_token(50_000, 10, "attention warning"),
            Tokens::EnvChange(EnvChangeToken {
                sub_type: EnvChangeTokenSubType::ResetConnection,
                change_type: EnvChangeContainer::from((0u32, 0u32)),
            }),
            Tokens::SessionState(SessionStateToken {
                sequence_number: u32::MAX,
                status: 0,
                states: Vec::new(),
            }),
        ];

        assert!(client.apply_attention_settlement(AttentionSettlement {
            tokens,
            overflowed: false,
        }));

        assert!(client.transport.connection_known_dead());
        assert_eq!(client.info_messages()[0].message, "attention warning");
        assert!(client.prepared_handles.is_empty());
        assert!(
            client
                .recovery_context
                .session_state_table
                .master_recovery_disabled
        );
    }

    #[test]
    fn overflowing_attention_settlement_retires_the_connection() {
        use crate::connection::transport::network_transport::AttentionSettlement;

        let mut client = create_test_client();

        assert!(!client.apply_attention_settlement(AttentionSettlement {
            tokens: Vec::new(),
            overflowed: true,
        }));
        assert!(client.transport.connection_known_dead());
    }

    #[test]
    fn finalize_return_value_decrypts_null_output() {
        // A NULL encrypted output parameter decrypts to NULL without invoking the
        // cipher.
        let mut client = create_test_client();
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Enabled;
        insert_test_cek(&mut client, "@out", vec![0u8; 32]);
        let token = ae_return_value_token("@out", ColumnValues::Null, Some(ae_crypto_metadata()));
        let rv = client.finalize_return_value(token).unwrap();
        assert_eq!(rv.value, ColumnValues::Null);
    }

    #[test]
    fn finalize_return_value_errors_on_non_varbinary_ciphertext() {
        // An encrypted output parameter that did not arrive as varbinary cipher
        // bytes is a protocol violation.
        let mut client = create_test_client();
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Enabled;
        insert_test_cek(&mut client, "@out", vec![0u8; 32]);
        let token = ae_return_value_token("@out", ColumnValues::Int(5), Some(ae_crypto_metadata()));
        let err = client.finalize_return_value(token).unwrap_err();
        assert!(matches!(err, crate::error::Error::ColumnEncryptionError(_)));
    }

    #[test]
    fn finalize_return_value_decrypts_ciphertext() {
        // A ciphertext output parameter decrypts to the original value using the
        // retained CEK.
        use crate::security::encryption::{AeadAes256CbcHmacSha256, ColumnEncryptionType};
        let mut client = create_test_client();
        client.current_command_ce_setting = ExecutionColumnEncryptionSetting::Enabled;
        let cek = [0x2a_u8; 32];
        insert_test_cek(&mut client, "@out", cek.to_vec());

        // Normalized 8-byte little-endian form of an `int`, encrypted with the CEK.
        let normalized = 987_654_i64.to_le_bytes();
        let cipher = AeadAes256CbcHmacSha256::new(&cek)
            .unwrap()
            .encrypt(&normalized, ColumnEncryptionType::Randomized)
            .unwrap();
        let token = ae_return_value_token(
            "@out",
            ColumnValues::Bytes(cipher),
            Some(ae_crypto_metadata()),
        );
        let rv = client.finalize_return_value(token).unwrap();
        assert_eq!(rv.value, ColumnValues::Int(987_654));
    }

    // ── Reconnection orchestration tests ──

    #[tokio::test]
    async fn reconnect_fails_when_not_negotiated() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = false;

        let result = client.reconnect(Duration::from_secs(10), None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Session not recoverable"),
            "Expected SessionNotRecoverable, got: {err}"
        );
    }

    #[tokio::test]
    async fn reconnect_fails_when_no_client_context() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        client.recovery_context.client_context = None;

        let result = client.reconnect(Duration::from_secs(10), None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("No client context"),
            "Expected no client context error, got: {err}"
        );
    }

    #[tokio::test]
    async fn reconnect_fails_when_transaction_active() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        client.execution_context.set_transaction_descriptor(999);

        let result = client.reconnect(Duration::from_secs(10), None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Session not recoverable"),
            "Expected SessionNotRecoverable, got: {err}"
        );
    }

    #[tokio::test]
    async fn reconnect_fails_when_batch_open() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        client.execution_context.set_has_open_batch(true);

        let result = client.reconnect(Duration::from_secs(10), None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Session not recoverable"),
            "Expected SessionNotRecoverable, got: {err}"
        );
    }

    #[tokio::test]
    async fn reconnect_fails_with_zero_timeout() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;

        // Zero-duration timeout → deadline immediately exceeded
        let result = client.reconnect(Duration::ZERO, None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Session recovery failed"),
            "Expected SessionRecoveryFailed, got: {err}"
        );
    }

    /// Covers the elapsed branch of `attempt_within` directly, since nothing
    /// in `reconnect`'s own tests can provoke it: every failure a test can
    /// reach today (no server, bad recovery state, ...) returns well before
    /// any deadline. `start_paused` lets the timeout fire on a fake clock
    /// instead of a real, slow connect attempt.
    #[tokio::test(start_paused = true)]
    async fn attempt_within_times_out_when_the_future_never_completes() {
        let remaining = Duration::from_secs(5);
        let handle = tokio::spawn(attempt_within(
            remaining,
            std::future::pending::<TdsResult<()>>(),
        ));

        tokio::time::advance(remaining + Duration::from_millis(1)).await;

        let result = handle.await.expect("attempt_within task panicked");
        match result {
            Err(crate::error::Error::TimeoutError(_)) => {}
            other => panic!("expected a TimeoutError once the deadline elapses, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn reconnect_returns_session_recovery_failed_on_connection_failure() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        // Use a very short timeout — connect will fail (no server) and exhaust attempts
        // connect_retry_count defaults to 1, connect_retry_interval defaults to 10
        // With a 1-second timeout the first attempt fails and no time for retry
        let result = client.reconnect(Duration::from_secs(1), None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        // Should be SessionRecoveryFailed (not SessionNotRecoverable)
        assert!(
            err.to_string().contains("Session recovery failed")
                || err.to_string().contains("attempt"),
            "Expected SessionRecoveryFailed, got: {err}"
        );
    }

    #[tokio::test]
    async fn reconnect_increments_recovery_count_tracking() {
        // Verify initial state
        let client = create_test_client();
        assert_eq!(client.recovery_context.recovery_count, 0);
    }

    // ── Pre-execution dead connection check tests ──

    #[tokio::test]
    async fn check_and_reconnect_skips_when_not_negotiated() {
        let mut client = create_test_client();
        // session_recovery_negotiated is false by default
        assert!(!client.recovery_context.session_recovery_negotiated);

        // Should return Ok(Duration::ZERO) even though transport is "dead"
        let elapsed = client.check_and_reconnect(Some(5), None).await.unwrap();
        assert_eq!(elapsed, Duration::ZERO);
    }

    #[tokio::test]
    async fn check_and_reconnect_rejects_after_close_connection() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;

        client.close_connection().await.unwrap();
        assert!(!client.recovery_context.session_recovery_negotiated);

        // A dead transport must neither be resurrected nor reused once the
        // caller closed it.
        assert!(matches!(
            client.check_and_reconnect(Some(5), None).await,
            Err(crate::error::Error::ConnectionClosed(_))
        ));
    }

    #[tokio::test]
    async fn check_and_reconnect_skips_when_retry_count_zero() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        if let Some(ref mut ctx) = client.recovery_context.client_context {
            ctx.connect_retry_count = 0;
        }

        // Should skip even with dead transport because retry count is 0
        let elapsed = client.check_and_reconnect(Some(5), None).await.unwrap();
        assert_eq!(elapsed, Duration::ZERO);
    }

    #[tokio::test]
    async fn check_and_reconnect_returns_error_when_dead_and_not_recoverable() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        client.transport.close_transport().await.unwrap();
        // Make it not recoverable by starting a transaction
        client.execution_context.set_transaction_descriptor(42);

        let result = client.check_and_reconnect(Some(5), None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Connection is dead"),
            "Expected ConnectionClosed, got: {err}"
        );
    }

    #[tokio::test]
    async fn check_and_reconnect_attempts_reconnect_when_dead_and_recoverable() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        client.transport.close_transport().await.unwrap();
        // The closed TestTransport returns is_connection_dead() = true,
        // recovery is possible (no txn, no open batch, negotiated=true).
        // reconnect() will fail because TestTransport can't actually connect,
        // but it should be *attempted* — we'll get SessionRecoveryFailed.
        let result = client.check_and_reconnect(Some(1), None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Session recovery failed"),
            "Expected reconnect attempt resulting in SessionRecoveryFailed, got: {err}"
        );
    }

    #[tokio::test]
    async fn check_and_reconnect_recovers_a_retired_session_on_a_live_socket() {
        // A fatal ERROR token or a failed drain retires the session while the
        // socket still polls healthy. Trusting that poll would send the next
        // command over a connection the client already reports as dead.
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        client.transport.mark_known_dead();
        assert!(
            !client.transport.is_connection_dead(),
            "socket is still open"
        );

        let err = client.check_and_reconnect(Some(1), None).await.unwrap_err();
        assert!(
            err.to_string().contains("Session recovery failed"),
            "Expected a reconnect attempt, got: {err}"
        );
    }

    #[tokio::test]
    async fn check_and_reconnect_skips_when_no_client_context() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        client.recovery_context.client_context = None;

        // connect_retry_count defaults to 0 when no client context → skip
        let elapsed = client.check_and_reconnect(Some(5), None).await.unwrap();
        assert_eq!(elapsed, Duration::ZERO);
    }

    // ── deduct_timeout tests ──

    #[test]
    fn request_timeout_clock_is_skipped_without_budget() {
        let client = create_test_client();
        assert!(client.request_timeout_start().is_none());
    }

    #[test]
    fn request_timeout_clock_is_kept_for_exhausted_budget() {
        let mut client = create_test_client();
        client.remaining_request_timeout = Some(Duration::ZERO);

        let start = client
            .request_timeout_start()
            .expect("an explicit zero budget must still be measured");
        client.update_remaining_timeout(start);

        assert_eq!(client.remaining_request_timeout, Some(Duration::ZERO));
    }

    #[test]
    fn deduct_timeout_subtracts_elapsed() {
        let result = TdsClient::deduct_timeout(Some(30), Duration::from_secs(12));
        assert_eq!(
            result,
            CommandTimeoutBudget::Remaining(NonZeroU32::new(18).unwrap())
        );
        let resolved = result.into_timeout().unwrap();
        assert_eq!(resolved.seconds(), Some(18));
        assert_eq!(resolved.duration(), Some(Duration::from_secs(18)));
    }

    #[test]
    fn fully_consumed_positive_budget_errors_before_timeout_conversion() {
        let result = TdsClient::deduct_timeout(Some(5), Duration::from_secs(10));
        assert_eq!(result, CommandTimeoutBudget::Exhausted);
        assert!(matches!(
            result.into_timeout(),
            Err(crate::error::Error::TimeoutError(_))
        ));
    }

    #[test]
    fn exact_budget_boundary_is_exhausted_not_infinite() {
        // elapsed == timeout: remaining is exactly 0, which must be Exhausted,
        // never the `Some(0) == infinite` widening the old helper applied.
        let result = TdsClient::deduct_timeout(Some(10), Duration::from_secs(10));
        assert_eq!(result, CommandTimeoutBudget::Exhausted);
        assert!(matches!(
            result.into_timeout(),
            Err(crate::error::Error::TimeoutError(_))
        ));
    }

    #[test]
    fn deduct_timeout_passes_through_none() {
        let result = TdsClient::deduct_timeout(None, Duration::from_secs(10));
        assert_eq!(result, CommandTimeoutBudget::None);
    }

    #[test]
    fn deduct_timeout_zero_elapsed() {
        let result = TdsClient::deduct_timeout(Some(30), Duration::ZERO);
        assert_eq!(
            result,
            CommandTimeoutBudget::Remaining(NonZeroU32::new(30).unwrap())
        );
    }

    #[test]
    fn deduct_timeout_rounds_up_sub_second() {
        // 1.9 seconds elapsed should round up to 2 seconds deducted
        let result = TdsClient::deduct_timeout(Some(30), Duration::from_millis(1900));
        assert_eq!(
            result,
            CommandTimeoutBudget::Remaining(NonZeroU32::new(28).unwrap())
        );
    }

    /// A reconnect that consumes the whole command budget must fail the call
    /// before any bytes reach the wire — not fall through with an unbounded
    /// timeout. This exercises the real `execute` entry point, which the
    /// helper-only `deduct_timeout` tests do not.
    #[tokio::test]
    async fn execute_exhausted_reconnect_budget_writes_no_request() {
        let transport = TestTransport::new();
        let sent = Arc::clone(&transport.sent);
        let mut client = create_test_client_with_transport(transport);
        client.reconnect_elapsed_for_test = Some(Duration::from_secs(1));

        let error = client
            .execute(
                "SELECT 1".to_string(),
                ExecuteOptions::new().timeout_secs(1),
            )
            .await
            .expect_err("execute should fail before serialization");

        assert!(matches!(
            &error,
            crate::error::Error::TimeoutError(crate::error::TimeoutErrorType::String(message))
                if message == "command timeout exhausted"
        ));
        assert!(sent.lock().unwrap().is_empty());
    }

    /// Same guarantee for the cursor RPC family: one representative call-site
    /// covers the shared `into_timeout()?` gate across all cursor operations.
    #[tokio::test]
    async fn cursor_open_exhausted_reconnect_budget_writes_no_request() {
        use crate::connection::cursor_ops::CursorClient;

        let transport = TestTransport::new();
        let sent = Arc::clone(&transport.sent);
        let mut client = create_test_client_with_transport(transport);
        client.reconnect_elapsed_for_test = Some(Duration::from_secs(1));

        let error = client
            .cursor_open(
                "SELECT 1",
                crate::cursor::CursorScrollOption::FORWARD_ONLY,
                crate::cursor::CursorConcurrency::READONLY,
                0,
                Some(1),
                None,
            )
            .await
            .expect_err("cursor_open should fail before serialization");

        assert!(matches!(
            &error,
            crate::error::Error::TimeoutError(crate::error::TimeoutErrorType::String(message))
                if message == "command timeout exhausted"
        ));
        assert!(sent.lock().unwrap().is_empty());
    }

    // Public Recovery API ──────────────────────────────────────

    #[test]
    fn is_session_recovery_enabled_returns_false_by_default() {
        let client = create_test_client();
        assert!(!client.is_session_recovery_enabled());
    }

    #[test]
    fn is_session_recovery_enabled_returns_true_when_negotiated() {
        let mut client = create_test_client();
        client.recovery_context.session_recovery_negotiated = true;
        assert!(client.is_session_recovery_enabled());
    }

    #[test]
    fn connection_recovery_count_starts_at_zero() {
        let client = create_test_client();
        assert_eq!(client.connection_recovery_count(), 0);
    }

    #[test]
    fn connection_recovery_count_reflects_recovery_count() {
        let mut client = create_test_client();
        client.recovery_context.recovery_count = 3;
        assert_eq!(client.connection_recovery_count(), 3);
    }

    // ── execute_prepared / unprepare: StatementId-keyed handle map ──

    fn sid(raw: u64) -> StatementId {
        StatementId::from_raw_for_test(raw)
    }

    #[tokio::test]
    async fn execute_prepared_open_batch_guard_precedes_recovery_and_map_lookup() {
        let mut client = create_test_client();
        client.execution_context.set_has_open_batch(true);
        let mut statement = PreparedStatement::materialized_for_test("SELECT 1", sid(1));
        client.prepared_handles.insert(sid(1), 55);
        let mut orphaned = Some(sid(9));

        let result = client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await;

        // Re-entering with an open batch is a local usage error reported before
        // any recovery I/O or handle-map lookup, so nothing is consumed.
        assert!(matches!(result, Err(UsageError(_))));
        assert_eq!(orphaned, Some(sid(9)));
        assert_eq!(statement.id(), Some(sid(1)));
        assert_eq!(client.prepared_handles.get(&sid(1)), Some(&55));
        assert_eq!(client.connection_recovery_count(), 0);
    }

    // A piggyback needs a prepare to ride on, so an orphan handed in alongside a
    // still-live statement stays with the caller rather than being dropped.
    #[tokio::test]
    async fn execute_prepared_leaves_orphan_untouched_on_the_execute_path() {
        let mut client = create_test_client();
        let mut statement = PreparedStatement::materialized_for_test("SELECT 1", sid(1));
        client.prepared_handles.insert(sid(1), 55);
        client.prepared_handles.insert(sid(9), 77);
        let mut orphaned = Some(sid(9));

        let result = client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await;

        assert!(result.is_err(), "no server behind the test transport");
        assert_eq!(orphaned, Some(sid(9)));
        assert_eq!(
            client.prepared_handles.get(&sid(9)),
            Some(&77),
            "the orphan is still releasable via unprepare"
        );
    }

    // ── execute_prepared: reuse-vs-reprepare branch ──
    //
    // The RPC name serializes as PROC_ID_SWITCH (0xFFFF) followed by the proc id
    // as i16 LE, so sp_prepexec (13) is `FF FF 0D 00` and sp_execute (12) is
    // `FF FF 0C 00`. Asserting on those bytes pins which branch actually reached
    // the wire, which the returned `StatementResult` alone cannot show.

    #[tokio::test]
    async fn execute_prepared_materializes_an_unmaterialized_statement() {
        let (mut client, sent) = create_capturing_client(vec![
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ]);
        let mut statement = PreparedStatement::new("SELECT 1");
        let mut orphaned = None;

        client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await
            .expect("sp_prepexec should succeed against the queued tokens");

        let statement_id = statement
            .id()
            .expect("the first execute must materialize the statement");
        assert_eq!(client.prepared_handles.get(&statement_id).copied(), Some(9));
        assert!(
            sent.lock()
                .unwrap()
                .windows(4)
                .any(|w| w == [0xFF, 0xFF, 0x0D, 0x00]),
            "a statement with no identity must go out as sp_prepexec"
        );
    }

    #[tokio::test]
    async fn execute_prepared_reprepares_when_the_id_has_no_live_handle() {
        // The state a reconnect leaves behind: the caller's statement keeps its
        // id but the map that resolved it is gone. That id must not address the
        // new session's plan.
        let (mut client, sent) = create_capturing_client(vec![
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ]);
        let stale = sid(99);
        let mut statement = PreparedStatement::materialized_for_test("SELECT 1", stale);
        let mut orphaned = None;

        client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await
            .expect("sp_prepexec should succeed against the queued tokens");

        let statement_id = statement.id().expect("re-prepare must re-materialize");
        assert_ne!(
            statement_id, stale,
            "a re-prepare must issue a fresh identity, not revive the dead one"
        );
        assert_eq!(client.prepared_handles.get(&statement_id).copied(), Some(9));
        assert!(!client.prepared_handles.contains_key(&stale));
        assert!(
            sent.lock()
                .unwrap()
                .windows(4)
                .any(|w| w == [0xFF, 0xFF, 0x0D, 0x00]),
            "an id with no live handle must re-prepare via sp_prepexec"
        );
    }

    #[tokio::test]
    async fn execute_prepared_reuses_a_live_handle_via_sp_execute() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let statement_id = sid(1);
        let mut statement = PreparedStatement::materialized_for_test("SELECT 1", statement_id);
        client.prepared_handles.insert(statement_id, 55);
        let mut orphaned = None;

        client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await
            .expect("sp_execute should succeed against the queued DONE token");

        assert_eq!(
            statement.id(),
            Some(statement_id),
            "reuse must keep the statement's identity"
        );
        let bytes = sent.lock().unwrap().clone();
        assert!(
            bytes.windows(4).any(|w| w == [0xFF, 0xFF, 0x0C, 0x00]),
            "a live handle must be reused via sp_execute, not re-prepared"
        );
        // The @handle positional: name length 0x00, status 0x00 (NONE — a
        // re-prepare would send 0x01/BY_REF_VALUE here), INTN 0x26, max size
        // 0x04, value length 0x04, then the handle (55) little-endian.
        let expected = [0x00, 0x00, 0x26, 0x04, 0x04, 0x37, 0x00, 0x00, 0x00];
        assert!(
            bytes.windows(expected.len()).any(|w| w == expected),
            "sp_execute must address the cached handle on the wire"
        );
    }

    // The server can report an error and still return a `@handle` for the plan
    // it allocated. The drain records that handle, so the statement must carry
    // the id naming it or the entry — and the server-side plan — is unreachable.
    #[tokio::test]
    async fn execute_prepared_keeps_the_handle_reachable_when_the_batch_errors() {
        use crate::token::tokens::ErrorToken;

        let mut client = create_test_client_with_tokens(vec![
            Tokens::Error(ErrorToken {
                number: 50000,
                state: 1,
                severity: 16,
                message: "prepexec failed".to_string(),
                server_name: String::new(),
                proc_name: String::new(),
                line_number: 1,
            }),
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ]);
        let mut statement = PreparedStatement::new("SELECT 1");
        let mut orphaned = None;

        let result = client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await;

        assert!(result.is_err(), "the batch reported an error");
        let statement_id = statement
            .id()
            .expect("the statement must carry the id even though the execute failed");
        assert_eq!(
            client.prepared_handles.get(&statement_id).copied(),
            Some(9),
            "the captured handle must stay addressable so unprepare can release it"
        );

        client.close_query().await.ok();
        client.unprepare(statement_id, ()).await.ok();
        assert!(
            !client.prepared_handles.contains_key(&statement_id),
            "the caller can release the plan the failed prepare left behind"
        );
    }

    // A compile failure (bad syntax) returns no `@handle`, so nothing was
    // materialized and the statement must not claim an identity.
    #[tokio::test]
    async fn execute_prepared_leaves_the_statement_unmaterialized_when_no_handle_returns() {
        use crate::token::tokens::ErrorToken;

        let mut client = create_test_client_with_tokens(vec![
            Tokens::Error(ErrorToken {
                number: 102,
                state: 1,
                severity: 15,
                message: "Incorrect syntax near 'SELCT'".to_string(),
                server_name: String::new(),
                proc_name: String::new(),
                line_number: 1,
            }),
            done_no_more(),
        ]);
        let mut statement = PreparedStatement::new("SELCT 1");
        let mut orphaned = None;

        let result = client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await;

        assert!(result.is_err());
        assert_eq!(
            statement.id(),
            None,
            "no handle came back, so the statement was never materialized"
        );
        assert!(client.prepared_handles.is_empty());
    }

    // A multi-statement batch whose *later* statement fails: `execute_prepared`
    // returns Ok on the first result, and the error surfaces on a subsequent
    // drain. The `@handle` trails the whole batch, so capture must survive that
    // error — the drain reads on past it and only the terminal DONE aborts.
    #[tokio::test]
    async fn handle_is_captured_when_a_later_statement_in_the_batch_errors() {
        use crate::token::tokens::ErrorToken;

        let mut client = create_capturing_client(vec![
            done_count(CurrentCommand::Insert, 1, true),
            Tokens::Error(ErrorToken {
                number: 2627,
                state: 1,
                severity: 14,
                message: "Violation of PRIMARY KEY constraint".to_string(),
                server_name: String::new(),
                proc_name: String::new(),
                line_number: 2,
            }),
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ])
        .0;
        let mut statement = PreparedStatement::new("INSERT INTO a ...; INSERT INTO b ...;");
        let mut orphaned = None;

        client
            .execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await
            .expect("the first statement's result is reached before the error");
        let statement_id = statement.id().expect("materialized on the first result");

        // The error only surfaces here, after execute_prepared already returned.
        assert!(client.advance().await.is_err());

        assert_eq!(
            client.prepared_handles.get(&statement_id).copied(),
            Some(9),
            "the trailing @handle must be captured while draining past the error"
        );
    }

    // ── PreparedStatement lifecycle & the StatementId handle map ──

    #[test]
    fn take_id_clears_and_returns() {
        let mut stmt = PreparedStatement::materialized_for_test("SELECT 1", sid(7));
        assert_eq!(stmt.take_id(), Some(sid(7)));
        assert!(stmt.id().is_none());
        // Second take yields nothing — the identity is gone.
        assert!(stmt.take_id().is_none());
    }

    #[tokio::test]
    async fn unprepare_skips_absent_handle_without_rpc() {
        // The client holds no handle for this id (never materialized, or a
        // reconnect cleared the map): unprepare skips sp_unprepare. The transport
        // has no queued tokens, so a drain would error — reaching Ok proves no RPC
        // was sent.
        let mut client = create_test_client();

        client.unprepare(sid(5), ()).await.unwrap();
    }

    #[tokio::test]
    async fn unprepare_releases_live_handle() {
        // A handle the client still holds is released via sp_unprepare. Asserting
        // on the captured wire bytes proves the RPC was actually sent — a wrongly
        // skipped release would also return Ok, leaving the DONE unread.
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        client.prepared_handles.insert(sid(5), 5);

        client.unprepare(sid(5), ()).await.unwrap();

        // The sp_unprepare @handle positional parameter serializes as: name length
        // 0x00, status 0x00 (NONE), INTN type 0x26, max size 0x04, value length
        // 0x04, then the handle id (5) little-endian.
        let bytes = sent.lock().unwrap().clone();
        let expected = [0x00, 0x00, 0x26, 0x04, 0x04, 0x05, 0x00, 0x00, 0x00];
        assert!(
            bytes.windows(expected.len()).any(|w| w == expected),
            "a live handle must be released by sending sp_unprepare with its id on the wire"
        );
        // The map entry is evicted once the release is sent.
        assert!(!client.prepared_handles.contains_key(&sid(5)));
    }

    #[tokio::test]
    async fn unprepare_open_batch_returns_usage_error_before_io() {
        // Parity with execute_prepared: the open-batch guard is a local check
        // reported before any recovery I/O.
        let mut client = create_test_client();
        client.execution_context.set_has_open_batch(true);

        let result = client.unprepare(sid(5), ()).await;

        assert!(matches!(result, Err(UsageError(_))));
    }

    #[tokio::test]
    async fn unprepare_propagates_reconnect_error_when_unrecoverable() {
        // Recover-first parity with msodbcsql: a dead, unrecoverable connection
        // (open transaction) fails recovery, so unprepare surfaces that error
        // instead of sending sp_unprepare on a dead socket. The ODBC layer
        // swallows it best-effort.
        let mut client = create_test_client();
        client.prepared_handles.insert(sid(5), 5);
        client.recovery_context.session_recovery_negotiated = true;
        client.execution_context.set_transaction_descriptor(42);

        let result = client.unprepare(sid(5), ()).await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn unprepare_drops_both_map_entries_even_when_the_rpc_fails() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;

        // The transport has no queued tokens, so the sp_unprepare drain fails.
        // `unprepare` consumed the identity, so nothing can reach either entry
        // again — both must be gone rather than leaving the AE entry behind.
        let mut client = create_test_client();
        client.prepared_handles.insert(sid(5), 5);
        client
            .prepared_param_encryption
            .insert(sid(5), Arc::new(DescribeParameterEncryptionResult::new()));

        assert!(client.unprepare(sid(5), ()).await.is_err());

        assert!(!client.prepared_handles.contains_key(&sid(5)));
        assert!(!client.prepared_param_encryption.contains_key(&sid(5)));
    }

    #[test]
    fn push_return_value_routes_handle_into_map_under_pending_id() {
        let mut client = create_test_client();
        client.pending_capture = Some(sid(3));

        client.push_return_value(int_return_value(0, 9));

        assert_eq!(client.prepared_handles.get(&sid(3)).copied(), Some(9));
        // The capture is one-shot.
        assert!(client.pending_capture.is_none());
    }

    #[test]
    fn push_return_value_pins_pending_encryption_metadata() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;

        let mut client = create_test_client();
        client.pending_capture = Some(sid(1));
        let describe = Arc::new(DescribeParameterEncryptionResult::new());
        client.pending_prepared_param_encryption = Some(Arc::clone(&describe));

        client.push_return_value(int_return_value(0, 9));

        // Metadata pinning is protocol-owned and completes in the token funnel,
        // keyed by the same StatementId as the handle.
        assert!(Arc::ptr_eq(
            client.prepared_param_encryption.get(&sid(1)).unwrap(),
            &describe
        ));
        assert!(client.pending_prepared_param_encryption.is_none());
    }

    #[test]
    fn reused_server_handle_id_cannot_collide_across_statements() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;

        // The server may hand out the same integer handle again after a plan is
        // dropped. Keyed by StatementId, the replacement lands in its own slot
        // instead of overwriting (or being overwritten by) the prior statement's
        // metadata — the aliasing hazard an i32-keyed map required an ordered
        // evict-before-insert to avoid.
        let mut client = create_test_client();
        let dropped = Arc::new(DescribeParameterEncryptionResult::new());
        client.prepared_param_encryption.insert(sid(1), dropped);
        client.prepared_handles.insert(sid(1), 7);

        client.pending_capture = Some(sid(2));
        let replacement = Arc::new(DescribeParameterEncryptionResult::new());
        client.pending_prepared_param_encryption = Some(Arc::clone(&replacement));

        client.push_return_value(int_return_value(0, 7));

        assert!(Arc::ptr_eq(
            client.prepared_param_encryption.get(&sid(2)).unwrap(),
            &replacement
        ));
        assert_eq!(client.prepared_handles.get(&sid(2)).copied(), Some(7));
    }

    #[tokio::test]
    async fn drain_error_after_returned_handle_retains_prepared_metadata() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;
        use crate::token::tokens::ErrorToken;

        let mut client = create_test_client_with_tokens(vec![
            Tokens::Error(ErrorToken {
                number: 50000,
                state: 1,
                severity: 16,
                message: "prepexec failed".to_string(),
                server_name: String::new(),
                proc_name: String::new(),
                line_number: 1,
            }),
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ]);
        client.pending_capture = Some(sid(1));
        let replacement = Arc::new(DescribeParameterEncryptionResult::new());
        client.pending_prepared_param_encryption = Some(Arc::clone(&replacement));

        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;
        let result = client.advance().await;

        assert!(result.is_err());
        assert_eq!(client.prepared_handles.get(&sid(1)).copied(), Some(9));
        assert!(Arc::ptr_eq(
            client.prepared_param_encryption.get(&sid(1)).unwrap(),
            &replacement
        ));
        assert!(client.pending_prepared_param_encryption.is_none());
    }

    #[tokio::test]
    async fn returned_handle_is_available_after_terminal_done() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;

        let mut client = create_test_client_with_tokens(vec![
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ]);
        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;
        client.pending_capture = Some(sid(1));
        let replacement = Arc::new(DescribeParameterEncryptionResult::new());
        client.pending_prepared_param_encryption = Some(Arc::clone(&replacement));

        assert!(matches!(client.advance().await, Ok(StatementResult::End)));

        assert_eq!(client.prepared_handles.get(&sid(1)).copied(), Some(9));
        assert!(Arc::ptr_eq(
            client.prepared_param_encryption.get(&sid(1)).unwrap(),
            &replacement
        ));
    }

    #[tokio::test]
    async fn close_query_error_aborts_pending_prepare_capture() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;

        let mut client = create_test_client();
        client.execution_context.set_has_open_batch(true);
        client.pending_capture = Some(sid(1));
        client.pending_prepared_param_encryption =
            Some(Arc::new(DescribeParameterEncryptionResult::new()));

        assert!(client.close_query().await.is_err());
        assert!(client.pending_capture.is_none());
        assert!(client.pending_prepared_param_encryption.is_none());

        client.push_return_value(int_return_value(0, 9));
        assert!(!client.prepared_handles.contains_key(&sid(1)));
        assert!(!client.prepared_param_encryption.contains_key(&sid(1)));
    }

    #[tokio::test]
    async fn advance_error_aborts_pending_prepare_capture() {
        let mut client = create_test_client();
        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;
        client.pending_capture = Some(sid(1));

        assert!(client.advance().await.is_err());
        assert!(client.pending_capture.is_none());
    }

    #[tokio::test]
    async fn next_row_error_aborts_pending_prepare_capture() {
        let mut client = create_test_client();
        client.current_result_set_has_been_read_till_end = false;
        client.pending_capture = Some(sid(1));

        assert!(ResultSet::next_row(&mut client).await.is_err());
        assert!(client.pending_capture.is_none());
    }

    #[tokio::test]
    async fn next_row_into_error_aborts_pending_prepare_capture() {
        let mut client = create_test_client();
        client.current_result_set_has_been_read_till_end = false;
        client.pending_capture = Some(sid(1));
        let mut writer = DiscardRowWriter;

        assert!(
            ResultSet::next_row_into(&mut client, &mut writer)
                .await
                .is_err()
        );
        assert!(client.pending_capture.is_none());
    }

    #[test]
    fn push_return_value_without_pending_capture_leaves_map_untouched() {
        // A reuse (sp_execute) issues no handle and arms no pending capture, so a
        // stray Int return value is surfaced as an output param, not routed into
        // the handle map.
        let mut client = create_test_client();

        client.push_return_value(int_return_value(0, 9));

        assert!(client.prepared_handles.is_empty());
        assert_eq!(
            client.retrieve_output_params().unwrap().map(|v| v.len()),
            Some(1)
        );
    }

    // ── execute() / current_metadata invariants ──
    //
    // After an execute path returns, `current_metadata` must reflect the
    // current batch:
    //   - DDL/DML (no COLMETADATA from the server) → `current_metadata` is None
    //     and `has_open_batch` is false.
    //   - Result-bearing query (COLMETADATA received) → `current_metadata`
    //     points at the freshly received metadata and `has_open_batch` is true.
    // No state from a prior batch is observable via `get_metadata()`.

    /// Seeds a client with stale metadata + a single DONE token, runs `invoke`,
    /// and asserts the no-result-set post-conditions. Failure attribution comes
    /// from the calling test's name.
    async fn assert_no_result_set_clears_metadata<F, T>(invoke: F)
    where
        F: AsyncFnOnce(&mut TdsClient) -> TdsResult<T>,
    {
        let mut client = create_test_client_with_tokens(vec![done_no_more()]);
        client.current_metadata = Some(stale_metadata());

        invoke(&mut client)
            .await
            .expect("execute path should succeed against the queued DONE token");

        assert!(
            client.current_metadata.is_none(),
            "DDL/DML must clear cached metadata so get_metadata() doesn't return stale columns"
        );
        assert!(
            !client.execution_context.has_open_batch(),
            "no result set => has_open_batch must be false"
        );
        assert!(client.get_metadata().is_empty());
    }

    #[tokio::test]
    async fn execute_clears_stale_metadata_when_no_result_set() {
        assert_no_result_set_clears_metadata(async |c: &mut TdsClient| {
            c.execute("INSERT INTO t VALUES (1)".to_string(), ()).await
        })
        .await;
    }

    #[tokio::test]
    async fn execute_replaces_stale_metadata_when_result_set_returned() {
        let mut client = create_test_client_with_tokens(vec![empty_col_metadata(), done_no_more()]);
        let stale = stale_metadata();
        client.current_metadata = Some(Arc::clone(&stale));

        client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect("execute should consume COLMETADATA and return Ok");

        let new_metadata = client
            .current_metadata
            .as_ref()
            .expect("COLMETADATA branch must populate current_metadata");
        assert!(
            !Arc::ptr_eq(new_metadata, &stale),
            "current_metadata must point to the freshly received COLMETADATA, not the stale Arc"
        );
        assert!(
            client.execution_context.has_open_batch(),
            "result-set => has_open_batch must be true"
        );
    }

    // ── SQLRowCount plumbing: last_rows_affected capture / reset ──

    #[tokio::test]
    async fn execute_captures_dml_affected_row_count() {
        let mut client =
            create_test_client_with_tokens(vec![done_count(CurrentCommand::Update, 5, false)]);
        client
            .execute("UPDATE t SET x = 1".to_string(), ())
            .await
            .unwrap();
        assert_eq!(client.last_rows_affected(), 5);
    }

    #[tokio::test]
    async fn execute_reports_no_row_count_for_ddl() {
        // A DONE without the COUNT flag (DDL / SET NOCOUNT ON) leaves it at -1.
        let mut client = create_test_client_with_tokens(vec![done_no_more()]);
        client
            .execute("CREATE TABLE t(i int)".to_string(), ())
            .await
            .unwrap();
        assert_eq!(client.last_rows_affected(), -1);
    }

    #[tokio::test]
    async fn execute_reports_no_row_count_for_select() {
        // Landing on COLMETADATA (a forward-only result set) reports -1.
        let mut client = create_test_client_with_tokens(vec![empty_col_metadata(), done_no_more()]);
        client.execute("SELECT 1".to_string(), ()).await.unwrap();
        assert_eq!(client.last_rows_affected(), -1);
    }

    #[tokio::test]
    async fn dml_then_select_batch_reports_no_row_count_for_select() {
        // UPDATE (counted, has_more) then SELECT. Statement-wise, `execute`
        // lands on the UPDATE (count 7); advancing onto the SELECT's COLMETADATA
        // must clear that count so SQLRowCount reports -1 for the forward-only
        // SELECT, not the DML count. (Copilot review AB thread.)
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Update, 7, true),
            empty_col_metadata(),
            done_no_more(),
        ]);
        client
            .execute("UPDATE t SET x = 1; SELECT * FROM t".to_string(), ())
            .await
            .unwrap();
        assert_eq!(client.last_rows_affected(), 7);
        // Advance onto the SELECT: COLMETADATA clears the DML count.
        client.advance().await.unwrap();
        assert_eq!(client.last_rows_affected(), -1);
    }

    #[tokio::test]
    async fn row_count_resets_between_commands() {
        // A DML count from one command must not leak into the next command that
        // reports none. begin_command (on every execute* path) resets it.
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Delete, 4, false),
            done_no_more(),
        ]);
        client
            .execute("DELETE FROM t".to_string(), ())
            .await
            .unwrap();
        assert_eq!(client.last_rows_affected(), 4);
        // The second command is a DDL (no count) and must start fresh at -1.
        client
            .execute("CREATE TABLE u(i int)".to_string(), ())
            .await
            .unwrap();
        assert_eq!(client.last_rows_affected(), -1);
    }

    #[tokio::test]
    async fn multi_dml_batch_captures_each_statement_count() {
        // A pure-DML batch surfaces one count per statement, in order. Statement-
        // wise, each count is captured as `execute`/`advance` positions on the
        // next DML boundary.
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Update, 3, true),
            done_count(CurrentCommand::Delete, 2, true),
            done_count(CurrentCommand::Insert, 1, false),
        ]);
        client
            .execute(
                "UPDATE t SET x=1; DELETE FROM t; INSERT INTO t VALUES (1)".to_string(),
                (),
            )
            .await
            .unwrap();
        assert_eq!(client.last_rows_affected(), 3);
        client.advance().await.unwrap();
        assert_eq!(client.last_rows_affected(), 2);
        client.advance().await.unwrap();
        assert_eq!(client.last_rows_affected(), 1);
        assert_eq!(client.take_dml_result_counts(), vec![3, 2, 1]);
    }

    /// A `DONEINPROC` carrying a DML count. Every one of these sets `DONE_MORE`
    /// on the wire — the RPC's own `DONEPROC` still follows — which is exactly
    /// the ambiguity the terminator look-ahead resolves.
    fn done_in_proc_count(cmd: CurrentCommand, rows: u64) -> Tokens {
        Tokens::DoneInProc(DoneToken {
            status: DoneStatus::COUNT | DoneStatus::MORE,
            cur_cmd: cmd,
            row_count: rows,
        })
    }

    /// The terminal `DONEPROC` that closes an RPC response.
    fn done_proc_final() -> Tokens {
        Tokens::DoneProc(DoneToken {
            status: DoneStatus::FINAL,
            cur_cmd: CurrentCommand::Insert,
            row_count: 0,
        })
    }

    fn return_status(value: i32) -> Tokens {
        Tokens::ReturnStatus(crate::token::tokens::ReturnStatusToken { value })
    }

    /// A single-statement `sp_executesql` DML: its `DONEINPROC` claims MORE, but
    /// the only thing behind it is the RPC's `RETURNSTATUS`/`DONEPROC` trailer.
    /// The batch must be reported closed so the ODBC layer leaves the statement
    /// re-executable instead of parking a 0-column cursor on it (which surfaced
    /// as 24000 on the second parameterized INSERT — AB#47531).
    #[tokio::test]
    async fn sp_executesql_single_dml_closes_the_batch() {
        let mut client = create_test_client_with_tokens(vec![
            done_in_proc_count(CurrentCommand::Insert, 1),
            return_status(0),
            done_proc_final(),
        ]);
        let cancel_handle = CancelHandle::new();
        let result = client
            .execute_sp_executesql(
                "INSERT INTO t VALUES (@P1)".to_string(),
                Vec::new(),
                ExecuteOptions::new()
                    .timeout_secs(30)
                    .cancel(&cancel_handle),
            )
            .await
            .unwrap();
        assert!(matches!(result, StatementResult::NoRows { .. }));
        assert!(
            !client.has_open_batch(),
            "only the RPC trailer followed, so nothing is left to navigate to"
        );
        assert_eq!(client.last_rows_affected(), 1);
        assert!(client.remaining_request_timeout.is_none());
        assert!(client.cancel_handle.is_none());
    }

    /// Output parameters belong to the RPC trailer and must be finalized before
    /// the terminal `DONEPROC` closes the batch.
    #[tokio::test]
    async fn sp_executesql_output_parameters_close_the_batch() {
        let mut client = create_test_client_with_tokens(vec![
            done_in_proc_count(CurrentCommand::Insert, 1),
            return_status(0),
            Tokens::ReturnValue(ae_return_value_token("@out1", ColumnValues::Int(7), None)),
            Tokens::ReturnValue(ae_return_value_token("@out2", ColumnValues::Int(9), None)),
            done_proc_final(),
        ]);

        client
            .execute_sp_executesql("SET @out1 = 7; SET @out2 = 9".to_string(), Vec::new(), ())
            .await
            .unwrap();

        assert!(!client.has_open_batch());
        let values = client.retrieve_output_params().unwrap().unwrap();
        assert_eq!(values.len(), 2);
        assert_eq!(values[0].value, ColumnValues::Int(7));
        assert_eq!(values[1].value, ColumnValues::Int(9));
    }

    /// Session-state control tokens can appear in the RPC response tail and
    /// must be applied without keeping the batch open.
    #[tokio::test]
    async fn sp_executesql_session_state_trailer_closes_the_batch() {
        let mut client = create_test_client_with_tokens(vec![
            done_in_proc_count(CurrentCommand::Insert, 1),
            return_status(0),
            Tokens::SessionState(SessionStateToken {
                sequence_number: u32::MAX,
                status: 0,
                states: Vec::new(),
            }),
            done_proc_final(),
        ]);

        client
            .execute_sp_executesql("SET NOCOUNT ON".to_string(), Vec::new(), ())
            .await
            .unwrap();

        assert!(!client.has_open_batch());
        assert!(
            client
                .recovery_context
                .session_state_table
                .master_recovery_disabled
        );
    }

    /// Environment changes in the RPC response tail must update connection
    /// state without keeping the batch open.
    #[tokio::test]
    async fn sp_executesql_env_change_trailer_closes_the_batch() {
        use crate::token::tokens::{EnvChangeToken, EnvChangeTokenSubType};

        let mut client = create_test_client_with_tokens(vec![
            done_in_proc_count(CurrentCommand::Insert, 1),
            return_status(0),
            Tokens::EnvChange(EnvChangeToken {
                sub_type: EnvChangeTokenSubType::BeginTransaction,
                change_type: (0u64, 42u64).into(),
            }),
            done_proc_final(),
        ]);

        client
            .execute_sp_executesql("BEGIN TRANSACTION".to_string(), Vec::new(), ())
            .await
            .unwrap();

        assert!(!client.has_open_batch());
        assert_eq!(client.execution_context.get_transaction_descriptor(), 42);
    }

    /// A fully parsed output parameter that cannot be decrypted is a command
    /// error, not a transport or synchronization failure.
    #[tokio::test]
    async fn sp_executesql_output_decryption_error_does_not_retire_connection() {
        let mut client = create_test_client_with_tokens(vec![
            done_in_proc_count(CurrentCommand::Insert, 1),
            return_status(0),
            Tokens::ReturnValue(ae_return_value_token(
                "@out",
                ColumnValues::Bytes(vec![1, 2, 3]),
                Some(ae_crypto_metadata()),
            )),
            done_proc_final(),
        ]);
        client.recovery_context.session_recovery_negotiated = true;

        let result = client
            .execute_sp_executesql(
                "SET @out = 7".to_string(),
                Vec::new(),
                ExecuteOptions::new().column_encryption(ExecutionColumnEncryptionSetting::Enabled),
            )
            .await;

        assert!(matches!(
            result,
            Err(crate::error::Error::ColumnEncryptionError(_))
        ));
        assert!(!client.has_open_batch());
        assert!(!client.transport.connection_known_dead());
        assert!(client.recovery_context.session_recovery_negotiated);
    }

    /// Timeout and cancellation drain through the attention acknowledgement, so
    /// request state is cleared without retiring the synchronized connection.
    #[tokio::test]
    async fn sp_executesql_terminator_timeout_clears_request_state() {
        let errors = [
            crate::error::Error::TimeoutError(crate::error::TimeoutErrorType::String(
                "test timeout".to_string(),
            )),
            crate::error::Error::OperationCancelledError("test cancellation".to_string()),
        ];

        for error in errors {
            let transport = TestTransport::with_tokens_then_error(
                vec![done_in_proc_count(CurrentCommand::Insert, 1)],
                error,
            );
            let mut client = create_test_client_with_transport(transport);
            client.recovery_context.session_recovery_negotiated = true;
            let cancel_handle = CancelHandle::new();

            let result = client
                .execute_sp_executesql(
                    "INSERT INTO t VALUES (@P1)".to_string(),
                    Vec::new(),
                    ExecuteOptions::new()
                        .timeout_secs(30)
                        .cancel(&cancel_handle),
                )
                .await;

            assert!(result.is_err());
            assert!(!client.has_open_batch());
            assert!(client.remaining_request_timeout.is_none());
            assert!(client.cancel_handle.is_none());
            assert!(!client.transport.connection_known_dead());
            assert!(client.recovery_context.session_recovery_negotiated);
        }
    }

    /// Verifies that cancelling inside a ROW both preserves the connection and
    /// removes all state belonging to the cancelled result.
    #[tokio::test]
    async fn cancelled_row_read_normalizes_client_state_after_attention() {
        let mut response = TestPacketBuilder::new(PacketType::TabularResult)
            .append_byte(TokenType::Row as u8)
            .append_i32(42)
            .build();
        response.extend_from_slice(
            &TestPacketBuilder::new(PacketType::TabularResult)
                .append_bytes(&done_bytes(DoneStatus::ATTN.bits()))
                .build(),
        );
        let (transport, _written) =
            create_network_transport_with_live_peer_capturing_writes(&response);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(int_column_metadata(1));
        client.current_result_set_has_been_read_till_end = false;
        client.current_result_ended_with_done_in_proc = true;
        client.execution_context.set_has_open_batch(true);
        client.remaining_request_timeout = Some(Duration::from_secs(30));
        let cancellation = CancelHandle::new();
        client.cancel_handle = Some(cancellation.child_handle());
        cancellation.cancel();

        let mut writer = DefaultRowWriter::new(1);
        let result = client.next_row_into(&mut writer).await;

        assert!(matches!(
            result,
            Err(crate::error::Error::OperationCancelledError(_))
        ));
        assert!(client.current_metadata.is_none());
        assert!(client.current_result_set_has_been_read_till_end);
        assert!(!client.current_result_ended_with_done_in_proc);
        assert!(client.remaining_request_timeout.is_none());
        assert!(client.cancel_handle.is_none());
        assert!(!client.command_is_busy());
        assert!(!client.is_connection_dead());
    }

    /// A malicious or corrupt server cannot keep the trailer scanner alive
    /// indefinitely by streaming control tokens without a terminal `DONEPROC`.
    #[tokio::test]
    async fn sp_executesql_terminator_iteration_limit_retires_connection() {
        let mut tokens = vec![done_in_proc_count(CurrentCommand::Insert, 1)];
        tokens.extend((0..10000).map(|_| return_status(0)));
        let mut client = create_test_client_with_tokens(tokens);
        client.recovery_context.session_recovery_negotiated = true;

        let result = client
            .execute_sp_executesql("INSERT INTO t VALUES (@P1)".to_string(), Vec::new(), ())
            .await;

        assert!(matches!(
            result,
            Err(crate::error::Error::ProtocolError(message))
                if message == "Too many RPC trailer tokens without terminal DONEPROC"
        ));
        assert!(!client.has_open_batch());
        assert!(client.transport.connection_known_dead());
        assert!(!client.recovery_context.session_recovery_negotiated);
    }

    /// The same look-ahead must not swallow a real second statement: a
    /// two-statement parameterized DML batch keeps the batch open, and the
    /// parked token is replayed as the next result rather than re-read from the
    /// wire.
    #[tokio::test]
    async fn sp_executesql_second_dml_keeps_the_batch_open() {
        let mut client = create_test_client_with_tokens(vec![
            done_in_proc_count(CurrentCommand::Insert, 1),
            done_in_proc_count(CurrentCommand::Insert, 5),
            return_status(0),
            done_proc_final(),
        ]);
        client
            .execute_sp_executesql(
                "INSERT INTO t VALUES (@P1); INSERT INTO t VALUES (@P2)".to_string(),
                Vec::new(),
                (),
            )
            .await
            .unwrap();
        assert!(client.has_open_batch());
        assert_eq!(client.last_rows_affected(), 1);

        let next = client.advance().await.unwrap();
        assert!(matches!(next, StatementResult::NoRows { .. }));
        assert_eq!(client.last_rows_affected(), 5);
        assert!(!client.has_open_batch());
    }

    /// A row-returning statement behind the first result is likewise preserved:
    /// the parked COLMETADATA becomes the next navigable result set.
    #[tokio::test]
    async fn sp_executesql_dml_then_select_keeps_the_select_navigable() {
        let mut client = create_test_client_with_tokens(vec![
            done_in_proc_count(CurrentCommand::Insert, 1),
            int_col_metadata(1),
            done_proc_final(),
        ]);
        client
            .execute_sp_executesql(
                "INSERT INTO t VALUES (@P1); SELECT 42".to_string(),
                Vec::new(),
                (),
            )
            .await
            .unwrap();
        assert!(client.has_open_batch());
        assert!(matches!(
            client.advance().await.unwrap(),
            StatementResult::Rows
        ));
    }

    /// A message-only statement (PRINT) is surfaced the same way a counted one
    /// is, so it needs the same resolution — otherwise a parameterized PRINT
    /// also stranded a cursor.
    #[tokio::test]
    async fn sp_executesql_message_only_statement_closes_the_batch() {
        let mut client = create_test_client_with_tokens(vec![
            info_token(0, 0, "printed"),
            Tokens::DoneInProc(DoneToken {
                status: DoneStatus::MORE,
                cur_cmd: CurrentCommand::Select,
                row_count: 0,
            }),
            return_status(0),
            done_proc_final(),
        ]);
        client
            .execute_sp_executesql("PRINT CAST(@P1 AS VARCHAR(10))".to_string(), Vec::new(), ())
            .await
            .unwrap();
        assert!(!client.has_open_batch());
    }

    /// A plain SQL batch has no `DONEPROC` trailer, so its `DONE_MORE` is
    /// unambiguous and must be left alone: the second statement's count is still
    /// a separate result.
    #[tokio::test]
    async fn plain_batch_more_flag_is_not_second_guessed() {
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Insert, 1, true),
            done_count(CurrentCommand::Insert, 1, false),
        ]);
        client
            .execute(
                "INSERT INTO t VALUES (1); INSERT INTO t VALUES (2)".to_string(),
                (),
            )
            .await
            .unwrap();
        assert!(
            client.has_open_batch(),
            "a plain batch's DONE_MORE always means another statement result"
        );
        assert!(
            client.parked_token.is_none(),
            "a plain batch's DONE_MORE needs no look-ahead"
        );
    }

    /// `next_rowset` collapses no-row results, but a no-row result can also be
    /// the last thing in the response. Without a batch-open guard it reads on
    /// and blocks (here: the mock runs dry) on a token that never arrives.
    #[tokio::test]
    async fn next_rowset_stops_at_a_terminal_no_row_result() {
        let mut client =
            create_test_client_with_tokens(vec![done_count(CurrentCommand::Update, 3, false)]);
        assert!(client.next_rowset().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn select_clears_preceding_dml_counts() {
        // UPDATE (counted, has_more) then SELECT: advancing onto COLMETADATA
        // clears the buffered DML counts so they are not surfaced for the SELECT.
        let mut client = create_test_client_with_tokens(vec![
            done_count(CurrentCommand::Update, 7, true),
            empty_col_metadata(),
            done_no_more(),
        ]);
        client
            .execute("UPDATE t SET x=1; SELECT * FROM t".to_string(), ())
            .await
            .unwrap();
        // Statement-wise: execute stops on the UPDATE; advancing onto the
        // SELECT's COLMETADATA clears the buffered DML counts.
        client.advance().await.unwrap();
        assert!(client.take_dml_result_counts().is_empty());
    }

    #[tokio::test]
    async fn execute_stored_procedure_clears_stale_metadata_when_no_result_set() {
        assert_no_result_set_clears_metadata(async |c: &mut TdsClient| {
            c.execute_stored_procedure("dbo.do_work".to_string(), None, None, ())
                .await
        })
        .await;
    }

    #[tokio::test]
    async fn execute_sp_executesql_clears_stale_metadata_when_no_result_set() {
        assert_no_result_set_clears_metadata(async |c: &mut TdsClient| {
            c.execute_sp_executesql("UPDATE t SET v = 1".to_string(), Vec::new(), ())
                .await
        })
        .await;
    }

    #[tokio::test]
    async fn execute_sp_prepexec_clears_stale_metadata_when_no_result_set() {
        assert_no_result_set_clears_metadata(async |c: &mut TdsClient| {
            let mut orphan = None;
            c.execute_sp_prepexec_for_test(
                "UPDATE t SET v = 1".to_string(),
                Vec::new(),
                &mut orphan,
                (),
            )
            .await
            .map(|(_, result)| result)
        })
        .await;
    }

    // The `@handle` positional parameter of sp_prepexec serializes as:
    //   0x00  positional name length
    //   0x01  status flags = BY_REF_VALUE
    //   0x26  TYPE_INFO type byte = INTN
    //   0x04  TYPE_INFO max size = 4
    //   value: length byte then little-endian bytes (length 0x00 for NULL).
    // These tests pin the byte the current selection controls: the orphan's
    // live handle becomes the input value of that by-reference `@handle`.

    #[tokio::test]
    async fn execute_sp_prepexec_sends_orphan_handle_as_byref_handle_input() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let orphan_id = client.issue_statement_id();
        client.prepared_handles.insert(orphan_id, 0x5152_5354);
        let mut orphan = Some(orphan_id);
        client
            .execute_sp_prepexec_for_test(
                "UPDATE t SET v = 1".to_string(),
                Vec::new(),
                &mut orphan,
                (),
            )
            .await
            .expect("sp_prepexec should succeed against the queued DONE token");

        let bytes = sent.lock().unwrap().clone();
        let expected = [0x00, 0x01, 0x26, 0x04, 0x04, 0x54, 0x53, 0x52, 0x51];
        assert!(
            bytes.windows(expected.len()).any(|w| w == expected),
            "the orphan's handle must be sent as the by-reference @handle input so the server \
             drops the prior prepared statement"
        );
    }

    #[tokio::test]
    async fn execute_sp_prepexec_sends_null_handle_when_no_orphan() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let mut orphan = None;
        client
            .execute_sp_prepexec_for_test(
                "UPDATE t SET v = 1".to_string(),
                Vec::new(),
                &mut orphan,
                (),
            )
            .await
            .expect("sp_prepexec should succeed against the queued DONE token");

        let bytes = sent.lock().unwrap().clone();
        let expected_null = [0x00, 0x01, 0x26, 0x04, 0x00];
        assert!(
            bytes
                .windows(expected_null.len())
                .any(|w| w == expected_null),
            "None must send a NULL @handle input so the server prepares fresh"
        );
    }

    // A reconnect clears `prepared_handles`, so an orphan the caller still holds
    // may name a statement with no live handle. That drop is a no-op server-side.
    #[tokio::test]
    async fn execute_sp_prepexec_sends_null_handle_when_orphan_has_no_live_handle() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let mut orphan = Some(client.issue_statement_id());
        client
            .execute_sp_prepexec_for_test(
                "UPDATE t SET v = 1".to_string(),
                Vec::new(),
                &mut orphan,
                (),
            )
            .await
            .expect("sp_prepexec should succeed against the queued DONE token");

        let bytes = sent.lock().unwrap().clone();
        let expected_null = [0x00, 0x01, 0x26, 0x04, 0x00];
        assert!(
            bytes
                .windows(expected_null.len())
                .any(|w| w == expected_null),
            "an orphan with no live handle must send a NULL @handle input"
        );
        assert_eq!(orphan, None, "the orphan is released either way");
    }

    #[tokio::test]
    async fn execute_sp_prepexec_preserves_orphan_on_pre_send_error() {
        let mut client = create_test_client();
        let orphan_id = client.issue_statement_id();
        client.prepared_handles.insert(orphan_id, 7);
        client.execution_context.set_has_open_batch(true);
        let mut orphan = Some(orphan_id);

        let result = client
            .execute_sp_prepexec_for_test("SELECT 1".to_string(), Vec::new(), &mut orphan, ())
            .await;

        assert!(result.is_err());
        assert_eq!(orphan, Some(orphan_id));
        assert_eq!(
            client.prepared_handles.get(&orphan_id),
            Some(&7),
            "a pre-send failure must leave the orphan releasable"
        );
    }

    #[tokio::test]
    async fn execute_sp_prepexec_consumes_orphan_after_send_begins() {
        let mut client = create_test_client();
        let orphan_id = client.issue_statement_id();
        client.prepared_handles.insert(orphan_id, 7);
        let mut orphan = Some(orphan_id);

        let result = client
            .execute_sp_prepexec_for_test("SELECT 1".to_string(), Vec::new(), &mut orphan, ())
            .await;

        assert!(result.is_err());
        assert_eq!(orphan, None);
        assert!(
            !client.prepared_handles.contains_key(&orphan_id),
            "once the drop crosses the send boundary the orphan's entry is dead"
        );
    }

    /// Builds an `Int` RETURNVALUE for exercising `push_return_value` directly.
    /// The column metadata is irrelevant to the capture logic (which only
    /// inspects the value), so a minimal INT4 descriptor is used.
    fn int_return_value(ordinal: u16, value: i32) -> ReturnValue {
        use crate::datatypes::sqldatatypes::{
            FixedLengthTypes, TdsDataType, TypeInfo, TypeInfoVariant,
        };
        use crate::token::tokenitems::ReturnValueStatus;

        ReturnValue {
            param_ordinal: ordinal,
            param_name: String::new(),
            value: ColumnValues::Int(value),
            column_metadata: Box::new(ColumnMetadata {
                user_type: 0,
                flags: 0,
                data_type: TdsDataType::IntN,
                type_info: TypeInfo {
                    tds_type: TdsDataType::IntN,
                    length: 4,
                    type_info_variant: TypeInfoVariant::FixedLen(FixedLengthTypes::Int4),
                },
                column_name: String::new(),
                multi_part_name: None,
                crypto_metadata: None,
            }),
            status: ReturnValueStatus::OutputParam,
        }
    }

    #[test]
    fn push_return_value_captures_handle_then_surfaces_following_output_params() {
        let mut client = create_test_client();
        client.pending_capture = Some(sid(1));

        // First value = the sp_prepexec @handle: on the managed path it is
        // diverted into the handle map and NOT surfaced as a user output
        // parameter — mirroring msodbcsql, which routes it to hPrepCurrent.
        client.push_return_value(int_return_value(0, 0x0102_0304));

        assert_eq!(
            client.prepared_handles.get(&sid(1)).copied(),
            Some(0x0102_0304)
        );
        assert!(client.pending_capture.is_none(), "capture is one-shot");
        assert!(
            client.return_values.is_empty(),
            "the diverted handle must not appear in return_values"
        );
        assert!(client.get_return_values().is_empty());

        // Subsequent values are genuine output params and must be surfaced.
        client.push_return_value(int_return_value(1, 7));
        assert_eq!(client.return_values.len(), 1);
        assert!(matches!(
            client.return_values[0].value,
            ColumnValues::Int(7)
        ));
    }

    #[tokio::test]
    async fn execute_sp_execute_clears_stale_metadata_when_no_result_set() {
        assert_no_result_set_clears_metadata(async |c: &mut TdsClient| {
            let statement_id = c.register_prepared_handle_for_test(42);
            c.execute_sp_execute_for_test(statement_id, None, None, ())
                .await
        })
        .await;
    }

    #[tokio::test]
    async fn get_dtc_address_clears_stale_metadata_when_no_result_set() {
        assert_no_result_set_clears_metadata(async |c: &mut TdsClient| c.get_dtc_address().await)
            .await;
    }

    #[test]
    fn effective_ce_setting_resolves_against_connection() {
        use crate::connection::client_context::{
            ColumnEncryptionSetting, ExecutionColumnEncryptionSetting as S,
        };

        let mut client = create_test_client();

        // Connection is Disabled by default: UseConnectionSetting -> Disabled.
        client.current_command_ce_setting = S::UseConnectionSetting;
        assert_eq!(client.effective_command_ce_setting(), S::Disabled);

        // Explicit per-command settings pass through unchanged.
        for setting in [S::Enabled, S::ResultSetOnly, S::Disabled] {
            client.current_command_ce_setting = setting;
            assert_eq!(client.effective_command_ce_setting(), setting);
        }

        // With the connection enabled, UseConnectionSetting -> Enabled.
        if let Some(ctx) = client.recovery_context.client_context.as_mut() {
            ctx.column_encryption_setting = ColumnEncryptionSetting::Enabled;
        }
        client.current_command_ce_setting = S::UseConnectionSetting;
        assert_eq!(client.effective_command_ce_setting(), S::Enabled);
    }

    #[test]
    fn should_not_encrypt_when_feature_not_acknowledged() {
        use crate::connection::client_context::{
            ColumnEncryptionSetting, ExecutionColumnEncryptionSetting as S,
        };

        let mut client = create_test_client();
        if let Some(ctx) = client.recovery_context.client_context.as_mut() {
            ctx.column_encryption_setting = ColumnEncryptionSetting::Enabled;
        }
        // The test negotiated settings carry no acknowledged TCE feature, so
        // parameter encryption must not be attempted even when enabled.
        client.current_command_ce_setting = S::Enabled;
        assert!(!client.should_encrypt_parameters());
    }

    #[test]
    fn build_sp_describe_request_names_params_and_marks_output() {
        use crate::datatypes::sqltypes::SqlType;
        use crate::message::parameters::rpc_parameters::{RpcParameter, StatusFlags};

        let params = vec![
            RpcParameter::new(
                Some("@id".to_string()),
                StatusFlags::NONE,
                SqlType::Int(Some(1)),
            ),
            RpcParameter::new(
                Some("@count".to_string()),
                StatusFlags::BY_REF_VALUE,
                SqlType::BigInt(None),
            ),
        ];

        let (tsql, params_decl) =
            TdsClient::build_stored_procedure_describe_request("dbo.my_proc", &[], &params)
                .expect("building the describe request should succeed");

        assert_eq!(tsql, "EXEC dbo.my_proc @id=@id, @count=@count OUTPUT");
        assert_eq!(params_decl, "@id int, @count bigint OUTPUT");
    }

    #[test]
    fn build_sp_describe_request_positional_and_named() {
        use crate::datatypes::sqltypes::SqlType;
        use crate::message::parameters::rpc_parameters::{RpcParameter, StatusFlags};

        // Positional (unnamed) parameters get synthetic names bound by position
        // and precede the named parameters, which bind by name.
        let positional = vec![
            RpcParameter::new(None, StatusFlags::NONE, SqlType::Int(Some(1))),
            RpcParameter::new(None, StatusFlags::BY_REF_VALUE, SqlType::BigInt(None)),
        ];
        let named = vec![RpcParameter::new(
            Some("@b".to_string()),
            StatusFlags::NONE,
            SqlType::Int(Some(3)),
        )];

        let (tsql, params_decl) =
            TdsClient::build_stored_procedure_describe_request("proc", &positional, &named)
                .expect("building the describe request should succeed");

        assert_eq!(tsql, "EXEC proc @ce_pos_0, @ce_pos_1 OUTPUT, @b=@b");
        assert_eq!(
            params_decl,
            "@ce_pos_0 int, @ce_pos_1 bigint OUTPUT, @b int"
        );
    }

    #[test]
    fn build_sp_describe_request_rejects_synthetic_named_collision() {
        use crate::datatypes::sqltypes::SqlType;
        use crate::message::parameters::rpc_parameters::{RpcParameter, StatusFlags};

        let positional = vec![RpcParameter::new(
            None,
            StatusFlags::NONE,
            SqlType::Int(Some(1)),
        )];
        let named = vec![RpcParameter::new(
            Some("@CE_POS_0".to_string()),
            StatusFlags::NONE,
            SqlType::Int(Some(2)),
        )];

        let err = TdsClient::build_stored_procedure_describe_request("proc", &positional, &named)
            .expect_err("synthetic positional name collision should be rejected");

        assert!(matches!(err, UsageError(message) if message.contains("@CE_POS_0")));
    }

    /// A forced parameter whose row the server omits entirely from the describe
    /// result must be rejected — not silently sent as plaintext. This is the
    /// downgrade a describe-driven check (iterating only the server's rows) would
    /// miss, so the validation iterates the supplied forced parameters instead.
    #[tokio::test]
    async fn apply_parameter_encryption_rejects_forced_param_omitted_from_describe() {
        use crate::datatypes::sqltypes::SqlType;
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;
        use crate::security::keystore::{CekCache, ColumnEncryptionKeyStoreProviderRegistry};

        // Server returns an empty describe result: no row for the forced param.
        let describe = DescribeParameterEncryptionResult::new();
        let providers = ColumnEncryptionKeyStoreProviderRegistry::new();
        let cek_cache = CekCache::new();
        let mut output_param_ceks = HashMap::new();

        let mut forced = RpcParameter::new(
            Some("@p1".to_string()),
            StatusFlags::NONE,
            SqlType::Int(Some(42)),
        )
        .with_force_column_encryption(true);
        let mut params: Vec<&mut RpcParameter> = vec![&mut forced];

        let err = TdsClient::apply_parameter_encryption(
            &describe,
            &providers,
            &cek_cache,
            &mut params,
            &mut output_param_ceks,
            &[],
        )
        .await
        .expect_err("a forced parameter omitted from the describe result must be rejected");

        assert!(
            matches!(&err, crate::error::Error::ColumnEncryptionError(message) if message.contains("ForceColumnEncryption")),
            "expected a ForceColumnEncryption column-encryption error, got: {err}"
        );
    }

    // ── Raw TDS token byte builders (little-endian, matching the real parsers) ──

    fn message_token_bytes(
        token: crate::token::tokens::TokenType,
        number: u32,
        message: &str,
    ) -> Vec<u8> {
        use crate::token::parsers::common::test_utils::MockReader;
        let mut b = vec![token as u8];
        b.extend_from_slice(&0u16.to_le_bytes()); // token length (ignored by parser)
        b.extend_from_slice(&number.to_le_bytes());
        b.push(1); // state
        b.push(16); // severity
        let msg = MockReader::encode_utf16(message);
        b.extend_from_slice(&((msg.len() / 2) as u16).to_le_bytes()); // US_VARCHAR char count
        b.extend_from_slice(&msg);
        b.push(0); // server_name (B_VARCHAR, 0 chars)
        b.push(0); // proc_name (B_VARCHAR, 0 chars)
        b.extend_from_slice(&1u32.to_le_bytes()); // line number
        b
    }

    fn error_token_bytes(number: u32, _severity: u8, message: &str) -> Vec<u8> {
        message_token_bytes(crate::token::tokens::TokenType::Error, number, message)
    }

    fn info_token_bytes(number: u32, message: &str) -> Vec<u8> {
        message_token_bytes(crate::token::tokens::TokenType::Info, number, message)
    }

    fn done_bytes(status: u16) -> Vec<u8> {
        let mut b = vec![crate::token::tokens::TokenType::Done as u8];
        b.extend_from_slice(&status.to_le_bytes());
        b.extend_from_slice(&0u16.to_le_bytes()); // cur_cmd
        b.extend_from_slice(&0u64.to_le_bytes()); // row_count
        b
    }

    fn int_column_bytes(name: &str) -> Vec<u8> {
        use crate::token::parsers::common::test_utils::MockReader;
        let mut b = Vec::new();
        b.extend_from_slice(&0u32.to_le_bytes()); // user_type
        b.extend_from_slice(&0u16.to_le_bytes()); // flags (not nullable)
        b.push(crate::datatypes::sqldatatypes::TdsDataType::Int4 as u8);
        let name_bytes = MockReader::encode_utf16(name);
        b.push((name_bytes.len() / 2) as u8); // name length in chars
        b.extend_from_slice(&name_bytes);
        b
    }

    fn colmetadata_single_int_bytes(name: &str) -> Vec<u8> {
        let mut b = vec![crate::token::tokens::TokenType::ColMetadata as u8];
        b.extend_from_slice(&1u16.to_le_bytes()); // column count
        b.extend(int_column_bytes(name));
        b
    }

    /// A single-Int COLMETADATA as it appears on the wire when Always Encrypted
    /// is negotiated: an (empty) CEK table — a `u16` count of 0 — sits between
    /// the column count and the first column definition. The column itself is
    /// not encrypted (flags = 0), so it carries no per-column crypto metadata.
    /// Parsing these bytes without column-encryption awareness misreads the
    /// CEK-table prefix as column data and desynchronizes the stream.
    fn colmetadata_single_int_ae_bytes(name: &str) -> Vec<u8> {
        let mut b = vec![crate::token::tokens::TokenType::ColMetadata as u8];
        b.extend_from_slice(&1u16.to_le_bytes()); // column count
        b.extend_from_slice(&0u16.to_le_bytes()); // empty CEK table
        b.extend(int_column_bytes(name));
        b
    }

    /// A single COLMETADATA under Always Encrypted whose one column is
    /// `FLAG_ENCRYPTED` and carries `CryptoMetadata`, while the CEK table is
    /// empty. This server anomaly makes `resolve_cell_decryptor` fail fast
    /// (encrypted column, no keys to resolve). The outer (ciphertext) wire type
    /// is modeled as Int4 so the row payload is a fixed 4 bytes; on the drain
    /// path the column must be decoded as raw ciphertext without resolving any
    /// decryptor, so this failure is never triggered.
    fn colmetadata_single_encrypted_int_ae_bytes(name: &str) -> Vec<u8> {
        use crate::token::parsers::common::test_utils::MockReader;
        const FLAG_ENCRYPTED: u16 = 0x0800;
        let int4 = crate::datatypes::sqldatatypes::TdsDataType::Int4 as u8;

        let mut b = vec![crate::token::tokens::TokenType::ColMetadata as u8];
        b.extend_from_slice(&1u16.to_le_bytes()); // column count
        b.extend_from_slice(&0u16.to_le_bytes()); // empty CEK table

        // Encrypted column definition.
        b.extend_from_slice(&0u32.to_le_bytes()); // user_type
        b.extend_from_slice(&FLAG_ENCRYPTED.to_le_bytes()); // flags
        b.push(int4); // ciphertext wire type
        // CryptoMetadata (has_cek_table = true, since AE is negotiated).
        b.extend_from_slice(&0u16.to_le_bytes()); // cek_table_ordinal
        b.extend_from_slice(&0u32.to_le_bytes()); // base user_type
        b.push(int4); // base data type
        b.push(2); // cipher_algorithm_id (non-custom: AEAD_AES_256_CBC_HMAC_SHA256)
        b.push(1); // encryption_type (deterministic)
        b.push(1); // normalization_rule_version
        let name_bytes = MockReader::encode_utf16(name);
        b.push((name_bytes.len() / 2) as u8);
        b.extend_from_slice(&name_bytes);
        b
    }

    fn colmetadata_two_int_bytes(first: &str, second: &str) -> Vec<u8> {
        let mut b = vec![crate::token::tokens::TokenType::ColMetadata as u8];
        b.extend_from_slice(&2u16.to_le_bytes()); // column count
        b.extend(int_column_bytes(first));
        b.extend(int_column_bytes(second));
        b
    }

    fn row_int_bytes(value: i32) -> Vec<u8> {
        let mut b = vec![crate::token::tokens::TokenType::Row as u8];
        b.extend_from_slice(&value.to_le_bytes()); // non-nullable Int4: 4 raw LE bytes
        b
    }

    fn row_two_int_bytes(a: i32, b_val: i32) -> Vec<u8> {
        let mut b = vec![crate::token::tokens::TokenType::Row as u8];
        b.extend_from_slice(&a.to_le_bytes());
        b.extend_from_slice(&b_val.to_le_bytes());
        b
    }

    /// NBCROW (0xD2) for a single Int4 column whose only value is NULL. The
    /// 1-byte null bitmap has bit 0 set, so no value bytes follow.
    fn nbcrow_single_null_bytes() -> Vec<u8> {
        vec![crate::token::tokens::TokenType::NbcRow as u8, 0b0000_0001]
    }

    const DONE_MORE_ERROR: u16 = 0x0003; // DONE_MORE | DONE_ERROR
    const DONE_FINAL: u16 = 0x0000;
    const DONE_ERROR_FINAL: u16 = 0x0002; // DONE_ERROR, batch complete

    fn expect_sql_error(err: crate::error::Error) -> crate::error::SqlServerDiagnostics {
        match err {
            crate::error::Error::SqlServerError { diagnostics } => diagnostics,
            other => panic!("expected a SqlServerError, got: {other:?}"),
        }
    }

    /// Parity with go-mssqldb #410: a statement-scoped error (`RAISERROR`)
    /// followed by a row-returning statement (`SELECT ...`) in the same batch.
    /// On the ERROR token, `advance_to_result_boundary` drains the remainder of
    /// the batch via `drain_stream`. The drain must carry the trailing result
    /// set's COLMETADATA into the row-decoding path so the ROW tokens are fully
    /// consumed, letting the real SQL error surface instead of a parse failure.
    #[tokio::test]
    async fn drain_on_error_consumes_trailing_rowset_and_surfaces_sql_error() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom")); // RAISERROR('boom', 16, 1)
        stream.extend(done_bytes(DONE_MORE_ERROR)); // stmt 1 done, batch continues
        stream.extend(colmetadata_single_int_bytes("n")); // SELECT n ...
        stream.extend(row_int_bytes(1)); // one row
        stream.extend(done_bytes(DONE_FINAL)); // end of batch

        let mut client = client_over_bytes(stream);
        let err = client
            .advance_to_result_boundary()
            .await
            .expect_err("a statement error must surface as an error");

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors.len(), 1);
        assert_eq!(diagnostics.errors[0].number, 1222);
        assert_eq!(diagnostics.errors[0].message, "boom");
    }

    /// After the error path drains the batch to its terminal DONE, the client
    /// must be left idle: `advance_to_result_boundary`'s `Error` branch resets
    /// the result-set state so a caller that calls `next_row` after `execute`
    /// returned `Err` does not pass the `maybe_has_unread_rows` guard and read a
    /// stream that is already fully consumed.
    #[tokio::test]
    async fn drain_on_error_leaves_client_idle_for_next_row() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_int_bytes("n"));
        stream.extend(row_int_bytes(1));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes(stream);
        client
            .advance_to_result_boundary()
            .await
            .expect_err("a statement error must surface as an error");

        assert!(
            !client.maybe_has_unread_rows(),
            "drained error path must clear the unread-rows guard"
        );
        assert!(!client.on_rows(), "drained error path must clear metadata");
        assert!(
            !client.has_open_batch(),
            "drained error path must close the batch"
        );
    }

    /// When the trailing result set is truncated mid-drain (the stream ends
    /// before the terminal DONE), the drain fails — but the original SQL error
    /// must still surface as the primary error and the client must be left idle
    /// so the failed drain does not leave the batch marked open. Covers the
    /// `Err` arm of the drain in `advance_to_result_boundary`'s `Error` branch.
    #[tokio::test]
    async fn drain_on_error_truncated_stream_still_surfaces_sql_error() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_int_bytes("n"));
        // Stream ends here: no ROW, no terminal DONE — the drain read fails.

        let mut client = client_over_bytes(stream);
        let err = client
            .advance_to_result_boundary()
            .await
            .expect_err("a statement error must surface as an error");

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);
        assert_eq!(diagnostics.errors[0].message, "boom");
        assert!(
            !client.maybe_has_unread_rows(),
            "a failed drain must still clear the unread-rows guard"
        );
        assert!(
            !client.has_open_batch(),
            "a failed drain must still close the batch"
        );
    }

    /// A drain that stops partway leaves the reader at an unknown offset in the
    /// response. `close_query` must still reset its own state and retire the
    /// connection.
    ///
    /// Before this fix the `?` on the drain returned early, so
    /// `set_has_open_batch(false)` never ran. Every later call then failed with
    /// `ALREADY_EXECUTING_ERROR` instead of the real error — the connection
    /// looked permanently wedged, with no way to clear it.
    #[tokio::test]
    async fn close_query_drain_failure_closes_batch_and_retires_connection() {
        let mut stream = Vec::new();
        stream.extend(colmetadata_single_int_bytes("n"));
        stream.extend(row_int_bytes(1));
        // Stream ends here: no terminal DONE, so the drain read fails.

        let mut client = client_over_bytes(stream);
        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;

        client
            .close_query()
            .await
            .expect_err("a truncated drain must surface an error");

        assert!(
            !client.has_open_batch(),
            "a failed drain must still close the batch"
        );
        assert!(
            !client.command_is_busy(),
            "a failed drain must not leave the connection reporting ALREADY_EXECUTING_ERROR"
        );
        assert!(
            client.transport.connection_known_dead(),
            "a failed drain must retire the connection: a TDS stream cannot be \
             resynchronized from an unknown offset"
        );
        assert!(
            !client.recovery_context.session_recovery_negotiated,
            "a desynchronized session must not be silently recovered"
        );
    }

    /// A drain that gives up partway must retire the connection no matter which
    /// call site issued it. `drain_stream_or_retire` is the one place that rule
    /// lives, so pinning it here covers every site that routes through it
    /// (`execute_sp_prepare`, `execute_sp_unprepare`, and the five cursor
    /// operations) without duplicating this test seven times.
    ///
    /// Those sites previously used a bare `?`, which propagated the error while
    /// leaving the connection reusable *and* the batch open — the same
    /// `ALREADY_EXECUTING_ERROR` masking that made the original failure look
    /// like a permanent wedge.
    ///
    /// The stream here is truncated, i.e. the transport went away, so session
    /// recovery must stay armed: reconnecting is exactly the remedy for that.
    #[tokio::test]
    async fn drain_stream_or_retire_failure_closes_batch_and_retires_connection() {
        let mut stream = Vec::new();
        stream.extend(colmetadata_single_int_bytes("n"));
        stream.extend(row_int_bytes(1));
        // Stream ends here: no terminal DONE, so the drain read fails.

        let mut client = client_over_bytes(stream);
        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;
        client.recovery_context.session_recovery_negotiated = true;

        let error = client
            .drain_stream_or_retire()
            .await
            .expect_err("a truncated drain must surface an error");

        assert!(
            !client.has_open_batch(),
            "a failed drain must still close the batch"
        );
        assert!(
            !client.command_is_busy(),
            "a failed drain must not leave the connection reporting ALREADY_EXECUTING_ERROR"
        );
        assert!(
            client.transport.connection_known_dead(),
            "a failed drain must retire the connection regardless of call site"
        );
        assert!(
            TdsClient::drain_failure_lost_the_transport(&error),
            "a truncated stream must classify as transport loss, got {error:?}"
        );
        assert!(
            client.recovery_context.session_recovery_negotiated,
            "losing the transport mid-drain is what resiliency exists for; \
             disarming it turns a recoverable blip into a hard failure"
        );
    }

    fn cancelled_client_with_attention_ack() -> TdsClient {
        let response = TestPacketBuilder::new(PacketType::TabularResult)
            .append_bytes(&done_bytes(DoneStatus::ATTN.bits()))
            .build();
        let (transport, _written) =
            create_network_transport_with_live_peer_capturing_writes(&response);
        let mut client = create_test_client_with_any_transport(AnyTransport::network(transport));
        client.current_metadata = Some(int_column_metadata(1));
        client.current_result_set_has_been_read_till_end = false;
        client.execution_context.set_has_open_batch(true);
        client.remaining_request_timeout = Some(Duration::from_secs(30));
        client.recovery_context.session_recovery_negotiated = true;
        let cancellation = CancelHandle::new();
        client.cancel_handle = Some(cancellation.child_handle());
        cancellation.cancel();
        client
    }

    /// A drain that returned the original cancellation after reaching DONE_ATTN
    /// must leave the synchronized connection reusable.
    #[tokio::test]
    async fn drain_stream_or_retire_preserves_settled_cancellation() {
        let mut client = cancelled_client_with_attention_ack();

        let error = tokio::time::timeout(Duration::from_secs(5), client.drain_stream_or_retire())
            .await
            .expect("settled cancellation should not hang")
            .unwrap_err();

        assert!(matches!(
            error,
            crate::error::Error::OperationCancelledError(_)
        ));
        assert!(!client.has_open_batch());
        assert!(!client.transport.connection_known_dead());
        assert!(client.recovery_context.session_recovery_negotiated);
        assert!(!client.interrupted_read_settled);
    }

    /// Closing a query uses a separate outer drain wrapper and must apply the
    /// same DONE_ATTN distinction before deciding to retire the connection.
    #[tokio::test]
    async fn close_query_preserves_settled_cancellation() {
        let mut client = cancelled_client_with_attention_ack();

        let error = tokio::time::timeout(Duration::from_secs(5), client.close_query())
            .await
            .expect("settled cancellation should not hang")
            .unwrap_err();

        assert!(matches!(
            error,
            crate::error::Error::OperationCancelledError(_)
        ));
        assert!(!client.has_open_batch());
        assert!(!client.transport.connection_known_dead());
        assert!(client.recovery_context.session_recovery_negotiated);
        assert!(!client.interrupted_read_settled);
    }

    /// A timeout/cancellation without a transport settlement is still an
    /// unproven partial drain and must retire the connection.
    #[tokio::test]
    async fn drain_stream_or_retire_retires_unsettled_cancellation() {
        let mut client = create_test_client_with_transport(TestTransport::with_tokens_then_error(
            Vec::new(),
            crate::error::Error::OperationCancelledError("test cancellation".to_string()),
        ));
        client.execution_context.set_has_open_batch(true);
        client.recovery_context.session_recovery_negotiated = true;

        let error = client.drain_stream_or_retire().await.unwrap_err();

        assert!(matches!(
            error,
            crate::error::Error::OperationCancelledError(_)
        ));
        assert!(!client.has_open_batch());
        assert!(client.transport.connection_known_dead());
        assert!(!client.recovery_context.session_recovery_negotiated);
        assert!(!client.interrupted_read_settled);
    }

    /// The other half of the split: when the drain failed because the *token
    /// stream* lost sync, the socket may still be perfectly healthy. Recovery
    /// must be disarmed there, otherwise the next command silently reconnects
    /// and papers over a decoder bug instead of surfacing it.
    #[tokio::test]
    async fn retire_after_failed_drain_disarms_recovery_only_for_desync() {
        let desync = crate::error::Error::ProtocolError("unexpected token".to_string());
        assert!(!TdsClient::drain_failure_lost_the_transport(&desync));

        let mut client = client_over_bytes(Vec::new());
        client.recovery_context.session_recovery_negotiated = true;
        client.retire_after_failed_drain(&desync);

        assert!(
            client.transport.connection_known_dead(),
            "a desynchronized stream must not go back to a pool"
        );
        assert!(
            !client.recovery_context.session_recovery_negotiated,
            "a desynchronized stream cannot be fixed by reconnecting"
        );
    }

    /// Control: the helper must stay quiet on a healthy stream. The drain
    /// reaches the terminal DONE and merely reports a server-side error, so the
    /// connection is still synchronized and must remain reusable — otherwise
    /// every `RAISERROR` inside a prepare or cursor operation would poison a
    /// pooled connection.
    #[tokio::test]
    async fn drain_stream_or_retire_sql_error_leaves_connection_alive() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_ERROR_FINAL));

        let mut client = client_over_bytes(stream);

        let errors = client
            .drain_stream_or_retire()
            .await
            .expect("a drain reaching the terminal DONE must succeed");

        assert_eq!(errors.len(), 1, "the ERROR token must still be collected");
        assert_eq!(errors[0].number, 1222);
        assert!(
            !client.transport.connection_known_dead(),
            "a drain that reached the terminal DONE must not retire the connection"
        );
    }

    /// Control: the drain surfacing a *server-reported* error must not retire
    /// the connection. Here the drain reaches the terminal DONE, so the stream
    /// is fully consumed and still synchronized — nothing about it is unsafe to
    /// reuse. (The case where the drain itself fails is covered by
    /// `error_token_with_truncated_remainder_retires_connection`.)
    ///
    /// Without this distinction an ordinary batch like
    /// `SELECT 1; RAISERROR('boom', 16, 1)` where the caller stops early would
    /// poison a pooled connection every time.
    #[tokio::test]
    async fn close_query_drain_sql_error_leaves_connection_alive() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_ERROR_FINAL));

        let mut client = client_over_bytes(stream);
        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;

        let err = client
            .close_query()
            .await
            .expect_err("a server-reported error must still surface");

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);

        assert!(!client.has_open_batch(), "the batch is closed either way");
        assert!(
            !client.transport.connection_known_dead(),
            "a fully drained stream must stay usable: the error came from the \
             server, not from losing track of the stream"
        );
    }

    /// An ERROR token whose *drain* then fails still builds a `SqlServerError`,
    /// so the error type alone cannot tell a failed batch apart from a lost
    /// stream. The handler must retire the connection at the point it gives up.
    #[tokio::test]
    async fn error_token_with_truncated_remainder_retires_connection() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        // Stream ends here: that DONE said more was coming, so the drain fails.

        let mut client = client_over_bytes(stream);
        let err = client
            .advance_to_result_boundary()
            .await
            .expect_err("a statement error must surface as an error");

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);

        assert!(
            client.transport.connection_known_dead(),
            "a drain that gave up mid-stream must retire the connection even \
             though the error it returns is a SqlServerError"
        );
        assert!(
            !client.recovery_context.session_recovery_negotiated,
            "a desynchronized session must not be silently recovered"
        );
    }

    /// End-to-end version of the above through `close_query`, which exempts
    /// `SqlServerError` from retirement. This pins that the exemption cannot
    /// resurrect a connection whose stream was already abandoned.
    #[tokio::test]
    async fn close_query_sql_error_over_truncated_stream_still_retires_connection() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));

        let mut client = client_over_bytes(stream);
        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;

        let err = client
            .close_query()
            .await
            .expect_err("the server-reported error must still surface");

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);

        assert!(
            client.transport.connection_known_dead(),
            "the SqlServerError exemption must not hand back a connection whose \
             stream was abandoned mid-response"
        );
    }

    /// Control: a drain that completes must leave the connection usable.
    #[tokio::test]
    async fn close_query_success_leaves_connection_alive() {
        let mut client = client_over_bytes(done_bytes(DONE_FINAL));
        client.execution_context.set_has_open_batch(true);
        client.current_result_set_has_been_read_till_end = true;

        client
            .close_query()
            .await
            .expect("a complete drain must succeed");

        assert!(
            !client.has_open_batch(),
            "a complete drain closes the batch"
        );
        assert!(
            !client.transport.connection_known_dead(),
            "a complete drain must not retire the connection"
        );
    }

    /// Control: the same statement error followed by a *no-row* statement drains
    /// cleanly and surfaces the real SQL error.
    #[tokio::test]
    async fn drain_on_error_surfaces_sql_error_without_trailing_rowset() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes(stream);
        let err = client
            .advance_to_result_boundary()
            .await
            .expect_err("a statement error must surface as an error");

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);
    }

    /// The trailing result set can carry multiple multi-column rows; every ROW
    /// must be consumed before the terminal DONE is reached.
    #[tokio::test]
    async fn drain_on_error_consumes_multi_row_multi_column_rowset() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1205, 16, "deadlock"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_two_int_bytes("a", "b"));
        stream.extend(row_two_int_bytes(1, 2));
        stream.extend(row_two_int_bytes(3, 4));
        stream.extend(row_two_int_bytes(5, 6));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes(stream);
        let err = client.advance_to_result_boundary().await.unwrap_err();

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1205);
    }

    /// NBCROW rows (null-bitmap-compressed) in the trailing result set are
    /// consumed through the same row-decoding path.
    #[tokio::test]
    async fn drain_on_error_consumes_nbcrow_rows() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_int_bytes("n"));
        stream.extend(nbcrow_single_null_bytes());
        stream.extend(row_int_bytes(7));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes(stream);
        let err = client.advance_to_result_boundary().await.unwrap_err();

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);
    }

    /// Multiple trailing result sets after the error (each COLMETADATA / ROWs /
    /// DONE-with-more) are drained one after another until the final DONE.
    #[tokio::test]
    async fn drain_on_error_consumes_multiple_trailing_rowsets() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_int_bytes("a"));
        stream.extend(row_int_bytes(1));
        stream.extend(done_bytes(0x0001)); // DONE_MORE, result set 1 ends
        stream.extend(colmetadata_single_int_bytes("b"));
        stream.extend(row_int_bytes(2));
        stream.extend(row_int_bytes(3));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes(stream);
        let err = client.advance_to_result_boundary().await.unwrap_err();

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);
    }

    /// An ERROR token that appears *inside* the trailing result set (after its
    /// rows) is collected alongside the first error, and INFO tokens are
    /// captured as informational messages.
    #[tokio::test]
    async fn drain_collects_secondary_error_and_info_tokens() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "first"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_int_bytes("n"));
        stream.extend(row_int_bytes(1));
        stream.extend(info_token_bytes(50000, "just fyi"));
        stream.extend(error_token_bytes(50001, 16, "second"));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes(stream);
        let err = client.advance_to_result_boundary().await.unwrap_err();

        let diagnostics = expect_sql_error(err);
        let numbers: Vec<u32> = diagnostics.errors.iter().map(|e| e.number).collect();
        assert_eq!(numbers, vec![1222, 50001]);
    }

    /// A COLMETADATA arriving before the current result set's DONE is a protocol
    /// violation, so the drain aborts rather than silently mis-parsing it. The
    /// abort is *contained*: the original statement error stays primary and the
    /// client is left idle, so the caller sees the real SQL error (1222) instead
    /// of the internal protocol detail, and a failed drain never leaves the
    /// batch marked open.
    #[tokio::test]
    async fn drain_rejects_colmetadata_before_result_set_done() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "boom"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_int_bytes("a"));
        stream.extend(row_int_bytes(1));
        stream.extend(colmetadata_single_int_bytes("b")); // no DONE before new metadata
        stream.extend(row_int_bytes(2));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes(stream);
        let err = client.advance_to_result_boundary().await.unwrap_err();

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);
        assert!(
            !client.maybe_has_unread_rows(),
            "a contained drain failure must still clear the unread-rows guard"
        );
        assert!(
            !client.has_open_batch(),
            "a contained drain failure must still close the batch"
        );
    }

    /// Regression guard for the drain's Always Encrypted awareness: when column
    /// encryption is negotiated, a trailing result set's COLMETADATA carries a
    /// CEK-table prefix (empty here). The drain's top-level token read must use
    /// the same ColumnEncryption context as the normal read path, or those two
    /// prefix bytes are misread as column data and the stream desynchronizes —
    /// exactly the corruption this drain exists to prevent. Reading with
    /// `ParserContext::None` here surfaces a parse error instead of the SQL
    /// error, so this test fails without the fix.
    #[tokio::test]
    async fn drain_parses_trailing_rowset_metadata_under_column_encryption() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "lock timeout"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_int_ae_bytes("a"));
        stream.extend(row_int_bytes(7));
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes_with_ae(stream);
        let err = client.advance_to_result_boundary().await.unwrap_err();

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);
    }

    /// Blocking-review regression guard: the drain must not resolve a cell
    /// decryptor for a discarded result set. Here the trailing result set has a
    /// `FLAG_ENCRYPTED` column whose CEK table is empty — an anomaly that makes
    /// `resolve_cell_decryptor` fail fast. Resolving a decryptor on the drain
    /// path would surface that `Err` and mask the real SQL error. The fix
    /// decodes the encrypted column as raw ciphertext instead, so error 1222
    /// still surfaces and the batch is fully drained.
    #[tokio::test]
    async fn drain_does_not_resolve_decryptor_for_discarded_encrypted_rowset() {
        let mut stream = Vec::new();
        stream.extend(error_token_bytes(1222, 16, "lock timeout"));
        stream.extend(done_bytes(DONE_MORE_ERROR));
        stream.extend(colmetadata_single_encrypted_int_ae_bytes("secret"));
        stream.extend(row_int_bytes(0x1122_3344)); // 4 ciphertext bytes, discarded
        stream.extend(done_bytes(DONE_FINAL));

        let mut client = client_over_bytes_with_ae(stream);
        // Enable column encryption for this command so the pre-fix drain would
        // actually resolve a decryptor (and fail fast on the empty CEK table).
        // With the fix, the drain ignores this and decodes raw ciphertext.
        client.current_command_ce_setting =
            crate::connection::client_context::ExecutionColumnEncryptionSetting::Enabled;
        let err = client.advance_to_result_boundary().await.unwrap_err();

        let diagnostics = expect_sql_error(err);
        assert_eq!(diagnostics.errors[0].number, 1222);
    }

    /// The drain's top-level loop must apply the side effects of the control
    /// tokens it walks past — collecting ERROR diagnostics, recording INFO
    /// messages, applying ENVCHANGE, session-state and return-value/status
    /// tokens — before the terminal DONE ends the batch. This exercises the
    /// `apply_drain_side_effect` dispatch reached from `drain_stream` directly
    /// (no trailing row set), complementing the byte-level row-drain tests.
    #[tokio::test]
    async fn drain_applies_side_effects_of_control_tokens() {
        use crate::token::tokens::{
            EnvChangeContainer, EnvChangeToken, EnvChangeTokenSubType, ErrorToken, OrderToken,
            ReturnStatusToken, SessionStateToken,
        };

        let tokens = vec![
            Tokens::Error(ErrorToken {
                number: 1205,
                state: 51,
                severity: 13,
                message: "deadlock victim".to_string(),
                server_name: "test-server".to_string(),
                proc_name: String::new(),
                line_number: 1,
            }),
            info_token(50_000, 10, "printed message"),
            Tokens::EnvChange(EnvChangeToken {
                sub_type: EnvChangeTokenSubType::ResetConnection,
                change_type: EnvChangeContainer::from((0u32, 0u32)),
            }),
            Tokens::SessionState(SessionStateToken {
                sequence_number: u32::MAX,
                status: 0,
                states: Vec::new(),
            }),
            Tokens::ReturnValue(ae_return_value_token("@out", ColumnValues::Int(7), None)),
            Tokens::ReturnStatus(ReturnStatusToken { value: 3 }),
            // A token the drain neither steers on nor records: exercised only to
            // prove it is skipped without aborting the drain.
            Tokens::Order(OrderToken {
                _order_columns: Vec::new(),
            }),
            done_no_more(),
        ];

        let mut client = create_test_client_with_tokens(tokens);
        let errors = client.drain_stream().await.unwrap();

        assert_eq!(errors.len(), 1, "the ERROR token must be collected");
        assert_eq!(errors[0].number, 1205);
        assert!(matches!(
            client.last_return_status,
            ReturnStatus::Received(3)
        ));
        assert_eq!(
            client.return_values.len(),
            1,
            "the RETURNVALUE must be surfaced as an output parameter"
        );
    }

    // ── Batched prepared RPC execution ──

    fn batch_done_in_proc(rows: u64) -> Tokens {
        Tokens::DoneInProc(DoneToken {
            status: DoneStatus::MORE | DoneStatus::COUNT,
            cur_cmd: CurrentCommand::Insert,
            row_count: rows,
        })
    }

    fn batch_done_proc(more: bool, error: bool) -> Tokens {
        let mut status = if more {
            DoneStatus::RPC_IN_BATCH
        } else {
            DoneStatus::FINAL
        };
        if error {
            status |= DoneStatus::ERROR;
        }
        Tokens::DoneProc(DoneToken {
            status,
            cur_cmd: CurrentCommand::None,
            row_count: 0,
        })
    }

    #[tokio::test]
    async fn prepared_batch_serializes_two_rpc_commands_in_one_message() {
        let tokens = vec![
            batch_done_in_proc(1),
            batch_done_proc(true, false),
            batch_done_in_proc(1),
            batch_done_proc(false, false),
        ];
        let (mut client, sent) = create_capturing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);
        let rows = vec![
            Ok((
                3,
                vec![RpcParameter::new(
                    Some("@P1".to_string()),
                    StatusFlags::NONE,
                    SqlType::Int(Some(10)),
                )],
            )),
            Ok((
                7,
                vec![RpcParameter::new(
                    Some("@P1".to_string()),
                    StatusFlags::NONE,
                    SqlType::Int(Some(20)),
                )],
            )),
        ];

        let result = client
            .execute_sp_execute_batch_for_test(statement_id, rows)
            .await
            .expect("batched sp_execute should succeed");
        assert_eq!(result.rows.len(), 2);
        assert_eq!(result.rows[0].row_index, 3);
        assert_eq!(result.rows[0].rows_affected, Some(1));
        assert_eq!(result.rows[1].row_index, 7);
        assert_eq!(result.rows[1].rows_affected, Some(1));
        assert_eq!(result.total_rows_affected(), Some(2));

        let wire = sent.lock().unwrap();
        let packet_len = u16::from_be_bytes([wire[2], wire[3]]) as usize;
        assert_eq!(
            packet_len,
            wire.len(),
            "batch must be one logical TDS message"
        );
        assert_eq!(wire[0], PacketType::RpcRequest as u8);
        assert_ne!(
            wire[1] & crate::message::messages::PacketStatusFlags::Eom as u8,
            0
        );
        let payload = reassemble_sent(&wire);
        let proc_marker = [0xff, 0xff, RpcProcs::Execute as u8, 0, 0, 0];
        assert_eq!(
            payload
                .windows(proc_marker.len())
                .filter(|window| *window == proc_marker)
                .count(),
            2
        );
        let delimiter_and_proc = [0xff, 0xff, 0xff, RpcProcs::Execute as u8, 0, 0, 0];
        assert!(
            payload
                .windows(delimiter_and_proc.len())
                .any(|window| window == delimiter_and_proc)
        );
    }

    #[tokio::test]
    async fn prepared_batch_skips_a_row_that_fails_to_build() {
        let tokens = vec![
            batch_done_in_proc(1),
            batch_done_proc(true, false),
            batch_done_in_proc(1),
            batch_done_proc(false, false),
        ];
        let (mut client, sent) = create_capturing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);
        let int_row = |index: usize, value: i32| {
            Ok((
                index,
                vec![RpcParameter::new(
                    Some("@P1".to_string()),
                    StatusFlags::NONE,
                    SqlType::Int(Some(value)),
                )],
            ))
        };
        let rows = vec![
            int_row(3, 10),
            Err(UsageError("row 5 changed after validation".to_string())),
            int_row(7, 20),
        ];

        let result = client
            .execute_sp_execute_batch_for_test(statement_id, rows)
            .await
            .expect("a row that fails to build must not fail the batch");

        assert_eq!(result.rows.len(), 2);
        assert_eq!(result.rows[0].row_index, 3);
        assert_eq!(result.rows[1].row_index, 7);

        // The skipped row must leave no trace on the wire: two commands joined
        // by exactly one delimiter, in one complete message.
        let wire = sent.lock().unwrap();
        let packet_len = u16::from_be_bytes([wire[2], wire[3]]) as usize;
        assert_eq!(
            packet_len,
            wire.len(),
            "a skipped row must still leave one complete TDS message"
        );
        assert_ne!(
            wire[1] & crate::message::messages::PacketStatusFlags::Eom as u8,
            0
        );
        let payload = reassemble_sent(&wire);
        let proc_marker = [0xff, 0xff, RpcProcs::Execute as u8, 0, 0, 0];
        assert_eq!(
            payload
                .windows(proc_marker.len())
                .filter(|window| *window == proc_marker)
                .count(),
            2,
            "the failed row must not have contributed a command"
        );
    }

    #[tokio::test]
    async fn prepared_batch_correlates_a_server_error_to_its_row() {
        let tokens = vec![
            batch_done_in_proc(1),
            batch_done_proc(true, false),
            Tokens::Error(crate::token::tokens::ErrorToken {
                number: 2627,
                state: 1,
                severity: 14,
                message: "duplicate key".to_string(),
                server_name: "test-server".to_string(),
                proc_name: String::new(),
                line_number: 1,
            }),
            batch_done_proc(false, true),
        ];
        let (mut client, _) = create_capturing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);
        let rows = vec![Ok((0, Vec::new())), Ok((1, Vec::new()))];

        let result = client
            .execute_sp_execute_batch_for_test(statement_id, rows)
            .await
            .expect("row-scoped SQL errors should remain correlated results");
        assert!(result.rows[0].errors.is_empty());
        assert_eq!(result.rows[1].errors.len(), 1);
        assert_eq!(result.rows[1].errors[0].number, 2627);
        assert!(result.complete);
    }

    #[tokio::test]
    async fn prepared_batch_preserves_an_early_batch_aborting_error() {
        let tokens = vec![
            batch_done_in_proc(1),
            batch_done_proc(true, false),
            Tokens::Error(crate::token::tokens::ErrorToken {
                number: 8115,
                state: 1,
                severity: 16,
                message: "arithmetic overflow".to_string(),
                server_name: "test-server".to_string(),
                proc_name: String::new(),
                line_number: 1,
            }),
            batch_done_proc(false, true),
        ];
        let (mut client, _) = create_capturing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);
        let rows = vec![
            Ok((0, Vec::new())),
            Ok((1, Vec::new())),
            Ok((2, Vec::new())),
        ];

        let result = client
            .execute_sp_execute_batch_for_test(statement_id, rows)
            .await
            .expect("batch-aborting SQL errors remain row results");
        assert!(!result.complete);
        assert_eq!(result.rows.len(), 2);
        assert_eq!(result.rows[1].errors[0].number, 8115);
        assert_eq!(result.total_rows_affected(), Some(1));
        assert!(!client.is_connection_dead());
    }

    #[tokio::test]
    async fn prepared_batch_reports_a_short_reply_with_no_error_to_explain_it() {
        // Two commands sent, one reported, and the stream ends cleanly with no
        // server error. The shortfall is carried on `complete` so the ODBC
        // layer can report it while keeping the set the server did report.
        let tokens = vec![batch_done_in_proc(1), batch_done_proc(false, false)];
        let (mut client, _) = create_capturing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);
        let rows = vec![Ok((0, Vec::new())), Ok((1, Vec::new()))];

        let result = client
            .execute_sp_execute_batch_for_test(statement_id, rows)
            .await
            .expect("a short batch is reported, not rejected");
        assert!(!result.complete, "one of two commands reported");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(result.rows[0].row_index, 0);
        assert!(
            !client.is_connection_dead(),
            "the stream ended at a final DONE, so the socket is still usable"
        );
    }

    #[tokio::test]
    async fn prepared_batch_reports_instead_of_silently_discarding_result_sets() {
        let tokens = vec![
            empty_col_metadata(),
            Tokens::Done(DoneToken {
                status: DoneStatus::MORE,
                cur_cmd: CurrentCommand::Select,
                row_count: 0,
            }),
            batch_done_proc(false, false),
        ];
        let (mut client, _) = create_capturing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);

        let result = client
            .execute_sp_execute_batch_for_test(statement_id, vec![Ok((4, Vec::new()))])
            .await
            .expect("row-returning RPC should be drained and reported");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(result.rows[0].row_index, 4);
        assert!(result.rows[0].has_result_set);
    }

    #[tokio::test]
    async fn prepared_batch_rejects_forced_encryption_before_writing() {
        let (mut client, sent) = create_capturing_client(Vec::new());
        let statement_id = client.register_prepared_handle_for_test(42);
        let forced = RpcParameter::new(
            Some("@P1".to_string()),
            StatusFlags::NONE,
            SqlType::Int(Some(1)),
        )
        .with_force_column_encryption(true);

        let error = client
            .execute_sp_execute_batch_for_test(statement_id, vec![Ok((0, vec![forced]))])
            .await
            .expect_err("forced encryption is unsupported on the batch fast path");
        assert!(matches!(&error, UsageError(message) if message.contains("ForceColumnEncryption")));
        assert!(sent.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn prepared_batch_deducts_send_time_from_response_budget() {
        let tokens = vec![batch_done_in_proc(1), batch_done_proc(false, false)];
        let (mut client, observed) = create_timeout_observing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);
        let mut statement =
            PreparedStatement::materialized_for_test("INSERT INTO t VALUES (@P1)", statement_id);
        let mut orphaned = None;
        let row = Ok((
            0,
            vec![RpcParameter::new(
                Some("@P1".to_string()),
                StatusFlags::NONE,
                SqlType::Int(Some(1)),
            )],
        ));

        client
            .execute_prepared_batch(
                &mut statement,
                vec![row],
                &mut orphaned,
                ExecuteOptions::new().timeout_secs(1),
            )
            .await
            .expect("batch should complete against scripted response");
        let observed = observed.lock().unwrap();
        let response_budget = observed[0].expect("finite timeout should reach the reader");
        assert!(
            response_budget < Duration::from_secs(1),
            "serialization/send time must be charged before response reads"
        );
    }

    #[tokio::test]
    async fn prepared_batch_preserves_unavailable_row_count() {
        let tokens = vec![batch_done_proc(false, false)];
        let (mut client, _) = create_capturing_client(tokens);
        let statement_id = client.register_prepared_handle_for_test(42);

        let result = client
            .execute_sp_execute_batch_for_test(statement_id, vec![Ok((0, Vec::new()))])
            .await
            .expect("batch without DONE_COUNT should still succeed");
        assert_eq!(result.total_rows_affected(), None);
        assert_eq!(client.last_rows_affected(), -1);
    }

    // ── Streamed (data-at-execution) PLP parameter write ──

    /// Reassembles the TDS packet stream captured by the mock transport into the
    /// original contiguous request payload, stripping each 8-byte packet header.
    fn reassemble_sent(sent: &[u8]) -> Vec<u8> {
        let mut out = Vec::new();
        let mut off = 0;
        while off < sent.len() {
            let packet_len = u16::from_be_bytes([sent[off + 2], sent[off + 3]]) as usize;
            out.extend_from_slice(&sent[off + 8..off + packet_len]);
            off += packet_len;
        }
        out
    }

    /// The 8-byte little-endian `PLP_UNKNOWN_LEN` sentinel that opens every
    /// unknown-length PLP value on the wire.
    const PLP_UNKNOWN_LEN_BYTES: [u8; 8] = [0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
    /// The 4-byte PLP terminator (a zero-length chunk header) that closes a value.
    const PLP_TERMINATOR_BYTES: [u8; 4] = [0x00, 0x00, 0x00, 0x00];
    /// The 8-byte little-endian `PLP_NULL` sentinel: a MAX-type value that is SQL
    /// NULL. No chunks or terminator follow it.
    const PLP_NULL_BYTES: [u8; 8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];

    /// Index of the last occurrence of `needle` in `haystack`, if any.
    fn find_last(haystack: &[u8], needle: &[u8]) -> Option<usize> {
        if needle.is_empty() || haystack.len() < needle.len() {
            return None;
        }
        (0..=haystack.len() - needle.len())
            .rev()
            .find(|&i| &haystack[i..i + needle.len()] == needle)
    }

    /// A data-at-execution `varbinary(max)` parameter template named `name`.
    /// varbinary keeps chunk bytes raw (no encoding), so tests can assert the
    /// exact wire bytes they streamed.
    fn streamed_varbinary(name: &str) -> RpcParameter {
        RpcParameter::data_at_exec(
            Some(name.to_string()),
            StatusFlags::NONE,
            StreamedSqlType::VarBinaryMax,
        )
    }

    /// A single streamed chunk is framed as `[u32 len][bytes]` and the value is
    /// then closed with the PLP terminator.
    #[tokio::test]
    async fn streamed_write_single_chunk_frames_value_and_terminator() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let status = client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();
        assert!(
            matches!(&status, StreamedParamStatus::NeedData { param_name } if param_name == "@v")
        );

        let chunk = [0xAAu8; 6];
        client.write_streamed_chunk(&chunk).await.unwrap();
        let status = client.end_streamed_param().await.unwrap();
        assert!(matches!(
            status,
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));

        let payload = reassemble_sent(&sent.lock().unwrap());
        let pos = find_last(&payload, &PLP_UNKNOWN_LEN_BYTES).expect("value opener present");
        let after = &payload[pos + PLP_UNKNOWN_LEN_BYTES.len()..];

        let mut expected = Vec::new();
        expected.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
        expected.extend_from_slice(&chunk);
        expected.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert_eq!(after, expected.as_slice());

        // The lifecycle is complete: no streamed write remains parked.
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
    }

    /// A streamed parameter marked NULL (before any chunk) is closed with
    /// `PLP_NULL` — no unknown-length opener, no chunks, no terminator. Mirrors
    /// msodbcsql's `VARMAX_LENGTH_NULL` for a data-at-execution NULL.
    #[tokio::test]
    async fn streamed_write_null_frames_plp_null() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        client.write_streamed_null().unwrap();
        let status = client.end_streamed_param().await.unwrap();
        assert!(matches!(
            status,
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));

        let payload = reassemble_sent(&sent.lock().unwrap());
        // The streamed @v value's length field is PLP_NULL and nothing follows it
        // (no chunks, no terminator), so it is the final value on the wire. Note
        // the positional @statement/@params args are themselves nvarchar(max) and
        // legitimately use PLP_UNKNOWN_LEN openers, so we assert on @v's PLP_NULL
        // being last rather than the absence of any opener in the whole payload.
        assert!(
            payload.ends_with(&PLP_NULL_BYTES),
            "a NULL streamed value must end the message with PLP_NULL and no terminator"
        );
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
    }

    /// Writing a chunk after marking the parameter NULL is a usage error, and the
    /// stream stays usable (the message is not corrupted — nothing was written).
    #[tokio::test]
    async fn streamed_write_chunk_after_null_errors() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        client.write_streamed_null().unwrap();
        let err = client
            .write_streamed_chunk(&[0x01])
            .await
            .expect_err("cannot write data after NULL");
        assert!(matches!(err, UsageError(_)));
        // Still active: end can still close it as NULL.
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Active(_)
        ));
        assert!(matches!(
            client.end_streamed_param().await.unwrap(),
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));
    }

    /// An *empty* chunk after marking the parameter NULL must still be a usage
    /// error, not a silent no-op: the empty-chunk short-circuit runs only after
    /// the NULL-sequencing check, so it cannot mask this caller mistake.
    #[tokio::test]
    async fn streamed_write_empty_chunk_after_null_errors() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        client.write_streamed_null().unwrap();
        let err = client
            .write_streamed_chunk(&[])
            .await
            .expect_err("an empty chunk after NULL must still error");
        assert!(matches!(err, UsageError(_)));
        assert!(matches!(
            client.end_streamed_param().await.unwrap(),
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));
    }

    /// Marking a parameter NULL after chunks were already written is a usage
    /// error: a value that has begun streaming cannot become NULL.
    #[tokio::test]
    async fn streamed_null_after_chunk_errors() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        client.write_streamed_chunk(&[0x01, 0x02]).await.unwrap();
        let err = client
            .write_streamed_null()
            .expect_err("cannot mark NULL after chunks were written");
        assert!(matches!(err, UsageError(_)));
    }

    /// `write_streamed_null` with no active streamed parameter is a usage error.
    #[tokio::test]
    async fn streamed_null_without_active_stream_errors() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);
        let err = client
            .write_streamed_null()
            .expect_err("no active streamed parameter");
        assert!(matches!(err, UsageError(_)));
    }

    /// A NULL streamed parameter followed by a normal streamed parameter: the
    /// first closes with `PLP_NULL`, the second frames its value normally, and the
    /// lifecycle advances NeedData -> NeedData -> Done.
    #[tokio::test]
    async fn streamed_write_null_then_value_param() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(a, b) VALUES (@a, @b)".to_string(),
                vec![streamed_varbinary("@a"), streamed_varbinary("@b")],
                (),
            )
            .await
            .unwrap();

        // @a is NULL.
        client.write_streamed_null().unwrap();
        let status = client.end_streamed_param().await.unwrap();
        assert!(
            matches!(&status, StreamedParamStatus::NeedData { param_name } if param_name == "@b")
        );

        // @b carries a value.
        let value = [0x7Au8; 5];
        client.write_streamed_chunk(&value).await.unwrap();
        assert!(matches!(
            client.end_streamed_param().await.unwrap(),
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));

        let payload = reassemble_sent(&sent.lock().unwrap());
        // @b's value is framed after an unknown-length opener; @a contributed a
        // PLP_NULL and no opener.
        let b_pos = find_last(&payload, &PLP_UNKNOWN_LEN_BYTES).unwrap();
        let mut expected_b = Vec::new();
        expected_b.extend_from_slice(&(value.len() as u32).to_le_bytes());
        expected_b.extend_from_slice(&value);
        expected_b.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert_eq!(
            &payload[b_pos + PLP_UNKNOWN_LEN_BYTES.len()..],
            expected_b.as_slice()
        );
        assert!(
            find_last(&payload[..b_pos], &PLP_NULL_BYTES).is_some(),
            "@a must have emitted PLP_NULL before @b's value"
        );
    }

    /// Multiple chunks are each length-prefixed independently and the value is
    /// closed by exactly one terminator — the incremental multi-chunk case.
    #[tokio::test]
    async fn streamed_write_multiple_chunks_each_length_prefixed_single_terminator() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        let chunks: [&[u8]; 3] = [&[0x01, 0x02], &[0x03, 0x04, 0x05], &[0x06]];
        for c in chunks {
            client.write_streamed_chunk(c).await.unwrap();
        }
        client.end_streamed_param().await.unwrap();

        let payload = reassemble_sent(&sent.lock().unwrap());
        let pos = find_last(&payload, &PLP_UNKNOWN_LEN_BYTES).unwrap();
        let after = &payload[pos + PLP_UNKNOWN_LEN_BYTES.len()..];

        let mut expected = Vec::new();
        for c in chunks {
            expected.extend_from_slice(&(c.len() as u32).to_le_bytes());
            expected.extend_from_slice(c);
        }
        expected.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert_eq!(after, expected.as_slice());
    }

    /// An empty chunk must be ignored, not written: a zero-length chunk header
    /// IS the terminator, so emitting one mid-value would truncate the value on
    /// the server. Protocol-safety analogue of the read-side early-terminator
    /// test.
    #[tokio::test]
    async fn streamed_write_empty_chunk_is_skipped_not_terminator() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        client.write_streamed_chunk(&[0x11, 0x22]).await.unwrap();
        client.write_streamed_chunk(&[]).await.unwrap(); // must be a no-op
        client.end_streamed_param().await.unwrap();

        let payload = reassemble_sent(&sent.lock().unwrap());
        let pos = find_last(&payload, &PLP_UNKNOWN_LEN_BYTES).unwrap();
        let after = &payload[pos + PLP_UNKNOWN_LEN_BYTES.len()..];

        // Exactly one framed chunk followed by exactly one terminator; the empty
        // chunk contributed nothing.
        let mut expected = Vec::new();
        expected.extend_from_slice(&2u32.to_le_bytes());
        expected.extend_from_slice(&[0x11, 0x22]);
        expected.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert_eq!(after, expected.as_slice());
    }

    /// Two data-at-execution parameters advance NeedData(@a) -> NeedData(@b) ->
    /// Done, and both values are framed in order on the wire.
    #[tokio::test]
    async fn streamed_write_two_params_advances_need_data_then_done() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let status = client
            .begin_sp_executesql(
                "INSERT INTO t(a, b) VALUES (@a, @b)".to_string(),
                vec![streamed_varbinary("@a"), streamed_varbinary("@b")],
                (),
            )
            .await
            .unwrap();
        assert!(
            matches!(&status, StreamedParamStatus::NeedData { param_name } if param_name == "@a")
        );

        let a_value = [0xA1u8; 4];
        client.write_streamed_chunk(&a_value).await.unwrap();
        let status = client.end_streamed_param().await.unwrap();
        assert!(
            matches!(&status, StreamedParamStatus::NeedData { param_name } if param_name == "@b")
        );

        let b_value = [0xB2u8; 5];
        client.write_streamed_chunk(&b_value).await.unwrap();
        let status = client.end_streamed_param().await.unwrap();
        assert!(matches!(
            status,
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));

        // @b is the last streamed param: its opener is the last sentinel, and the
        // bytes after it are exactly @b's framed value + terminator.
        let payload = reassemble_sent(&sent.lock().unwrap());
        let b_pos = find_last(&payload, &PLP_UNKNOWN_LEN_BYTES).unwrap();
        let mut expected_b = Vec::new();
        expected_b.extend_from_slice(&(b_value.len() as u32).to_le_bytes());
        expected_b.extend_from_slice(&b_value);
        expected_b.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert_eq!(
            &payload[b_pos + PLP_UNKNOWN_LEN_BYTES.len()..],
            expected_b.as_slice()
        );

        // @a's opener precedes @b's, and its framed value + terminator sits right
        // after it (followed by @b's parameter header).
        let a_pos = find_last(&payload[..b_pos], &PLP_UNKNOWN_LEN_BYTES).unwrap();
        let mut expected_a = Vec::new();
        expected_a.extend_from_slice(&(a_value.len() as u32).to_le_bytes());
        expected_a.extend_from_slice(&a_value);
        expected_a.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert!(
            payload[a_pos + PLP_UNKNOWN_LEN_BYTES.len()..].starts_with(&expected_a),
            "@a's framed value + terminator must immediately follow its opener"
        );
        assert!(a_pos < b_pos, "@a must be serialized before @b");
    }

    /// With no data-at-execution parameter, `begin_sp_executesql` delegates to
    /// the atomic path: it sends the RPC, consumes the response, and returns
    /// Complete without parking any streamed state.
    #[tokio::test]
    async fn begin_without_data_at_exec_delegates_and_returns_complete() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let status = client
            .begin_sp_executesql(
                "INSERT INTO t(id) VALUES (@id)".to_string(),
                vec![RpcParameter::new(
                    Some("@id".to_string()),
                    StatusFlags::NONE,
                    SqlType::Int(Some(7)),
                )],
                (),
            )
            .await
            .unwrap();

        assert!(matches!(
            status,
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
        assert!(
            !sent.lock().unwrap().is_empty(),
            "the atomic RPC should have been sent"
        );
    }

    /// Always Encrypted does not block the atomic fallback when there are no
    /// data-at-execution parameters.
    #[tokio::test]
    async fn begin_without_data_at_exec_allows_always_encrypted_atomic_fallback() {
        let mut client = client_over_bytes_with_ae(done_bytes(DONE_FINAL));

        let status = client
            .begin_sp_executesql("SELECT 1".to_string(), Vec::new(), ())
            .await
            .unwrap();

        assert!(matches!(
            status,
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
    }

    /// A mid-value send failure aborts the streamed write: the error is
    /// surfaced, the parked message is dropped (state returns to `Idle`, not left
    /// `Active`/resumable), and the transport is closed so the incomplete RPC
    /// cannot desynchronize a later command.
    #[tokio::test]
    async fn streamed_write_chunk_send_failure_aborts_stream() {
        let (mut client, fail) = create_failing_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Active(_)
        ));

        // Fail the next wire send; a chunk large enough to overflow the packet
        // payload buffer forces a flush (and thus a `send`) inside
        // write_streamed_chunk.
        fail.store(true, std::sync::atomic::Ordering::SeqCst);
        let big = vec![0xABu8; 10_000];
        let _err = client
            .write_streamed_chunk(&big)
            .await
            .expect_err("a send failure must surface as an error");

        // The streamed write is aborted, not left resumable.
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
        assert!(
            client.is_connection_dead(),
            "an incomplete RPC must make the connection non-reusable"
        );

        // Further streamed calls now fail cleanly (no active stream) rather than
        // appending to the corrupt message.
        let followup = client
            .write_streamed_chunk(&[0x00])
            .await
            .expect_err("no active streamed parameter after abort");
        assert!(matches!(followup, UsageError(_)));
        let end = client
            .end_streamed_param()
            .await
            .expect_err("no active streamed parameter after abort");
        assert!(matches!(end, UsageError(_)));
    }

    /// A send failure while finalizing the last streamed parameter (flushing the
    /// terminator + message) aborts the same way: error surfaced, state `Idle`,
    /// transport closed.
    #[tokio::test]
    async fn end_streamed_param_send_failure_aborts_stream() {
        let (mut client, fail) = create_failing_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        // A small chunk stays buffered (fits one packet, no send yet).
        client
            .write_streamed_chunk(&[0x01, 0x02, 0x03])
            .await
            .unwrap();

        // finalize() inside end_streamed_param flushes the message -> send fails.
        fail.store(true, std::sync::atomic::Ordering::SeqCst);
        let _err = client
            .end_streamed_param()
            .await
            .expect_err("finalize send failure must surface");

        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
        assert!(
            client.transport.connection_known_dead(),
            "a failed final send must make the connection non-reusable"
        );
    }

    /// Beginning a streamed execution while one is already active is rejected.
    #[tokio::test]
    async fn begin_while_stream_active_errors() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        let err = client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .expect_err("cannot begin a second streamed execution while one is active");
        assert!(matches!(err, UsageError(_)));
    }

    /// An unnamed data-at-execution parameter is rejected: streamed values must
    /// be named so `sp_executesql` can match them by name.
    #[tokio::test]
    async fn begin_rejects_unnamed_data_at_exec_param() {
        let mut client = create_test_client_with_tokens(vec![]);
        let bad =
            RpcParameter::data_at_exec(None, StatusFlags::NONE, StreamedSqlType::VarBinaryMax);

        let err = client
            .begin_sp_executesql("INSERT INTO t(v) VALUES (@v)".to_string(), vec![bad], ())
            .await
            .expect_err("unnamed data-at-exec parameter must be rejected");
        assert!(matches!(err, UsageError(_)));
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
    }

    /// All non-streaming execute entry points must reject data-at-exec params
    /// with a usage error instead of panicking or writing malformed RPC values.
    #[tokio::test]
    async fn execute_sp_executesql_rejects_data_at_exec_params() {
        let mut client = create_test_client_with_tokens(vec![]);
        let err = client
            .execute_sp_executesql("SELECT @v".to_string(), vec![streamed_varbinary("@v")], ())
            .await
            .expect_err("streamed params are only valid via begin_sp_executesql");
        assert!(matches!(err, UsageError(_)));
    }

    #[tokio::test]
    async fn execute_stored_procedure_rejects_data_at_exec_params() {
        let mut client = create_test_client_with_tokens(vec![]);
        let err = client
            .execute_stored_procedure(
                "dbo.p".to_string(),
                None,
                Some(vec![streamed_varbinary("@v")]),
                (),
            )
            .await
            .expect_err("streamed params are only valid via begin_sp_executesql");
        assert!(matches!(err, UsageError(_)));
    }

    #[tokio::test]
    async fn execute_prepared_rejects_data_at_exec_params() {
        let mut client = create_test_client_with_tokens(vec![]);
        let mut statement = PreparedStatement::new("SELECT @v");
        let mut orphaned = None;
        let err = client
            .execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                (),
            )
            .await
            .expect_err("streamed params are only valid via begin_sp_executesql");
        assert!(matches!(err, UsageError(_)));
    }

    // ── begin_execute_prepared: data-at-execution keeps the prepared path ──
    //
    // Data-at-execution must not downgrade a prepared statement to ad-hoc
    // `sp_executesql`, so these pin the proc id that actually reaches the wire:
    // sp_prepexec (13) is `FF FF 0D 00`, sp_execute (12) is `FF FF 0C 00`.

    #[tokio::test]
    async fn begin_execute_prepared_streams_into_sp_prepexec_when_unmaterialized() {
        let (mut client, sent) = create_capturing_client(vec![
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ]);
        let mut statement = PreparedStatement::new("INSERT INTO t(v) VALUES (@v)");
        let mut orphaned = None;

        let status = client
            .begin_execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                (),
            )
            .await
            .expect("begin must park for the streamed value");
        assert!(matches!(status, StreamedParamStatus::NeedData { .. }));

        let statement_id = statement
            .id()
            .expect("the parked prepexec must claim an identity for its @handle");

        client.write_streamed_chunk(&[0xAA, 0xBB]).await.unwrap();
        let status = client
            .end_streamed_param()
            .await
            .expect("closing the only streamed parameter completes the RPC");
        assert!(matches!(status, StreamedParamStatus::Complete(_)));

        // Asserted after finalize: the parked prefix stays buffered until the
        // last parameter closes, so nothing is on the wire before that.
        assert!(
            sent.lock()
                .unwrap()
                .windows(4)
                .any(|w| w == [0xFF, 0xFF, 0x0D, 0x00]),
            "a data-at-execution prepare must go out as sp_prepexec"
        );
        assert_eq!(
            client.prepared_handles.get(&statement_id).copied(),
            Some(9),
            "the trailing @handle must materialize under the claimed identity"
        );
    }

    #[tokio::test]
    async fn begin_execute_prepared_streams_into_sp_execute_when_handle_is_live() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let statement_id = sid(1);
        let mut statement =
            PreparedStatement::materialized_for_test("INSERT INTO t(v) VALUES (@v)", statement_id);
        client.prepared_handles.insert(statement_id, 55);
        let mut orphaned = None;

        let status = client
            .begin_execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                (),
            )
            .await
            .expect("begin must park for the streamed value");
        assert!(matches!(status, StreamedParamStatus::NeedData { .. }));
        assert_eq!(
            statement.id(),
            Some(statement_id),
            "reuse must keep the statement's identity"
        );
        assert!(
            client.pending_capture.is_none(),
            "sp_execute returns no @handle, so no capture may be armed"
        );

        client.write_streamed_chunk(&[0xAA]).await.unwrap();
        let status = client.end_streamed_param().await.unwrap();
        assert!(matches!(status, StreamedParamStatus::Complete(_)));

        let bytes = sent.lock().unwrap().clone();
        assert!(
            bytes.windows(4).any(|w| w == [0xFF, 0xFF, 0x0C, 0x00]),
            "a live handle must be reused via sp_execute, not re-prepared"
        );
        // The @handle positional addressing plan 55 — see
        // `execute_prepared_reuses_a_live_handle_via_sp_execute` for the layout.
        let expected = [0x00, 0x00, 0x26, 0x04, 0x04, 0x37, 0x00, 0x00, 0x00];
        assert!(
            bytes.windows(expected.len()).any(|w| w == expected),
            "the streamed sp_execute must address the cached handle"
        );
    }

    /// With no streamed parameters the call is an ordinary prepared execute and
    /// reports its result directly rather than parking.
    #[tokio::test]
    async fn begin_execute_prepared_without_streamed_params_completes() {
        let (mut client, sent) = create_capturing_client(vec![
            Tokens::ReturnValue(ae_return_value_token("@handle", ColumnValues::Int(9), None)),
            done_no_more(),
        ]);
        let mut statement = PreparedStatement::new("SELECT 1");
        let mut orphaned = None;

        let status = client
            .begin_execute_prepared(&mut statement, Vec::new(), &mut orphaned, ())
            .await
            .expect("a materialized-only execute must not park");
        assert!(matches!(status, StreamedParamStatus::Complete(_)));
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
        assert!(
            sent.lock()
                .unwrap()
                .windows(4)
                .any(|w| w == [0xFF, 0xFF, 0x0D, 0x00])
        );
    }

    /// The orphan's drop is not piggybacked onto a streamed prepexec: the
    /// request stays open for the whole chunk sequence and may never reach the
    /// server, so releasing it here could lose a live server-side plan.
    #[tokio::test]
    async fn begin_execute_prepared_keeps_the_orphan_for_the_caller() {
        let (mut client, _sent) = create_capturing_client(vec![]);
        let orphan_id = sid(1);
        client.prepared_handles.insert(orphan_id, 77);
        let mut statement = PreparedStatement::new("INSERT INTO t(v) VALUES (@v)");
        let mut orphaned = Some(orphan_id);

        client
            .begin_execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                (),
            )
            .await
            .expect("begin must park for the streamed value");

        assert_eq!(
            orphaned,
            Some(orphan_id),
            "the caller keeps ownership of the orphan's release"
        );
        assert_eq!(
            client.prepared_handles.get(&orphan_id).copied(),
            Some(77),
            "the orphan's handle must stay live and releasable via unprepare"
        );
    }

    /// Cancelling a parked `sp_prepexec` disarms the `@handle` capture. Leaving
    /// it armed would divert the next unrelated RPC's first RETURNVALUE into the
    /// handle map, aliasing a plan the statement never prepared.
    #[tokio::test]
    async fn cancel_streamed_write_disarms_the_prepexec_handle_capture() {
        let (mut client, _sent) = create_capturing_client(vec![]);
        let mut statement = PreparedStatement::new("INSERT INTO t(v) VALUES (@v)");
        let mut orphaned = None;

        client
            .begin_execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                (),
            )
            .await
            .expect("begin must park for the streamed value");
        assert!(client.pending_capture.is_some());

        client.cancel_streamed_write().await;

        assert!(client.pending_capture.is_none());
        let statement_id = statement.id().expect("the parked prepexec claimed an id");
        assert!(
            !client.prepared_handles.contains_key(&statement_id),
            "a cancelled prepare leaves the identity inert so the next execute re-prepares"
        );
    }

    /// Opening a streamed RPC consumes the connection's pending RESETCONNECTION
    /// bit. Cancelling before the first packet goes out must return it, or the
    /// pool's one-shot reset is silently swallowed.
    #[tokio::test]
    async fn cancel_streamed_write_rearms_an_unsent_connection_reset() {
        use crate::message::messages::PacketStatusFlags;
        use crate::token::tokens::{EnvChangeContainer, EnvChangeToken, EnvChangeTokenSubType};

        // The request that ends up carrying the re-armed bit must see the
        // server acknowledge it, or the client declares the session dirty and
        // fails it - see `observe_response_token`.
        let (mut client, sent) = create_capturing_client(vec![
            Tokens::EnvChange(EnvChangeToken {
                sub_type: EnvChangeTokenSubType::ResetConnection,
                change_type: EnvChangeContainer::from((0u32, 0u32)),
            }),
            done_no_more(),
        ]);
        let mut statement = PreparedStatement::new("INSERT INTO t(v) VALUES (@v)");
        let mut orphaned = None;

        client.prepare_reset_connection(false);
        client
            .begin_execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                (),
            )
            .await
            .expect("begin must park for the streamed value");
        assert!(
            sent.lock().unwrap().is_empty(),
            "the parked message must not have reached the network yet"
        );

        client.cancel_streamed_write().await;

        client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect("the next request should succeed");

        let sent = sent.lock().unwrap();
        assert_eq!(
            sent[1] & PacketStatusFlags::ResetConnection as u8,
            PacketStatusFlags::ResetConnection as u8,
            "the reset the cancelled message consumed must ride the next request"
        );
    }

    /// Cancelling while idle must be a no-op that keeps the connection reusable.
    #[tokio::test]
    async fn cancel_streamed_write_on_idle_client_is_noop() {
        let mut client = create_test_client_with_tokens(vec![]);
        client.cancel_streamed_write().await;
        assert!(
            !client.is_connection_dead(),
            "cancelling while idle must not kill a reusable connection"
        );
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
    }

    /// Cancelling before any packet has left the client discards the request
    /// locally: nothing is written to the wire and the connection stays usable.
    #[tokio::test]
    async fn cancel_streamed_write_before_first_packet_discards_locally() {
        let (mut client, sent) = create_capturing_client(vec![]);
        let status = client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .expect("begin must park for streamed value");
        assert!(matches!(
            status,
            StreamedParamStatus::NeedData { param_name: _ }
        ));
        assert!(
            sent.lock().unwrap().is_empty(),
            "the RPC header must still be buffered, not on the wire"
        );

        client.cancel_streamed_write().await;

        assert!(
            sent.lock().unwrap().is_empty(),
            "a request the server never saw must not be cancelled over the wire"
        );
        assert!(
            !client.is_connection_dead(),
            "abandoning an unsent request must leave the connection reusable"
        );
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
        assert!(matches!(
            client.write_streamed_chunk(&[0x01]).await,
            Err(UsageError(_))
        ));
    }

    /// Cancelling after part of the request is on the wire closes the message
    /// with EOM | IGNORE so the server discards it, consumes the DONE it
    /// answers with, and keeps the connection reusable.
    #[tokio::test]
    async fn cancel_streamed_write_after_partial_send_ignores_and_drains() {
        use crate::message::messages::PacketStatusFlags;

        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .expect("begin must park for streamed value");

        // Overflow the payload buffer so at least one packet is flushed.
        client
            .write_streamed_chunk(&vec![0xABu8; 10_000])
            .await
            .unwrap();
        let sent_before_cancel = sent.lock().unwrap().len();
        assert!(
            sent_before_cancel > 0,
            "a large chunk must have flushed at least one packet"
        );

        client.cancel_streamed_write().await;

        // The trailing packet must carry EOM | IGNORE and no payload.
        let wire = sent.lock().unwrap().clone();
        let last = &wire[wire.len() - PacketWriter::PACKET_HEADER_SIZE..];
        assert_eq!(
            last[1],
            PacketStatusFlags::Eom as u8 | PacketStatusFlags::Ignore as u8,
            "the cancelled message must be terminated with an ignore packet"
        );
        assert_eq!(
            u16::from_be_bytes([last[2], last[3]]) as usize,
            PacketWriter::PACKET_HEADER_SIZE
        );

        assert!(
            !client.is_connection_dead(),
            "an ignored request leaves the connection clean for reuse"
        );
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
        assert!(matches!(
            client.write_streamed_chunk(&[0x01]).await,
            Err(UsageError(_))
        ));
    }

    /// If the ignore packet cannot be sent, the request is neither complete nor
    /// retracted, so the connection must be closed rather than handed back.
    #[tokio::test]
    async fn cancel_streamed_write_falls_back_to_close_when_ignore_fails() {
        let (mut client, fail) = create_failing_capturing_client(vec![done_no_more()]);
        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .expect("begin must park for streamed value");
        client
            .write_streamed_chunk(&vec![0xABu8; 10_000])
            .await
            .unwrap();

        fail.store(true, std::sync::atomic::Ordering::SeqCst);
        client.cancel_streamed_write().await;

        assert!(
            client.is_connection_dead(),
            "a request that could not be retracted must not be reused"
        );
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
    }

    /// The retraction is only complete once the DONE the server answers the
    /// ignore packet with has been consumed. If that read fails the next
    /// command on this connection would pick the DONE up as its own, so the
    /// connection is closed instead of pooled.
    #[tokio::test]
    async fn cancel_streamed_write_falls_back_to_close_when_the_drain_fails() {
        // No DONE queued: the ignore packet goes out but is never acknowledged.
        let (mut client, _sent) = create_capturing_client(vec![]);
        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .expect("begin must park for streamed value");
        client
            .write_streamed_chunk(&vec![0xABu8; 10_000])
            .await
            .unwrap();

        client.cancel_streamed_write().await;

        assert!(
            client.is_connection_dead(),
            "an unacknowledged retraction leaves the stream desynchronized"
        );
        assert!(matches!(
            client.streamed_write_state,
            StreamedWriteState::Idle
        ));
    }

    /// Opens an RPC message with `payload_len` bytes and suspends it - the state
    /// a send site holds when serialization fails part-way.
    async fn suspend_message_with(client: &mut TdsClient, payload_len: usize) -> SuspendedMessage {
        suspend_message_under(client, payload_len, None).await
    }

    /// As [`suspend_message_with`], but the message carries `cancel_handle` the
    /// way a real request's writer does.
    async fn suspend_message_under(
        client: &mut TdsClient,
        payload_len: usize,
        cancel_handle: Option<&CancelHandle>,
    ) -> SuspendedMessage {
        let mut writer = PacketWriter::new(
            PacketType::RpcRequest,
            client.transport.as_writer(),
            None,
            cancel_handle,
        );
        writer
            .write_async(&vec![0xABu8; payload_len])
            .await
            .unwrap();
        writer.suspend()
    }

    /// Dropped locally, and `abandon` rather than `drop` because opening the
    /// message consumed the connection's pending RESETCONNECTION bit.
    #[tokio::test]
    async fn retract_partial_request_before_first_packet_discards_locally() {
        let (mut client, sent) = create_capturing_client(vec![]);
        client
            .transport
            .as_writer()
            .set_reset_mode(ResetConnectionMode::Reset);
        let message = suspend_message_with(&mut client, 16).await;
        assert!(message.nothing_sent());

        client.retract_partial_request(message).await;

        assert!(
            sent.lock().unwrap().is_empty(),
            "a request the server never saw must not be retracted over the wire"
        );
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::Reset,
            "the abandoned message must hand its reset back to the connection"
        );
        assert!(
            !client.is_connection_dead(),
            "abandoning an unsent request must leave the connection reusable"
        );
    }

    /// Once a packet is on the wire the server is mid-message, so the request is
    /// closed with EOM | IGNORE and its DONE consumed.
    #[tokio::test]
    async fn retract_partial_request_after_partial_send_ignores_and_drains() {
        use crate::message::messages::PacketStatusFlags;

        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let message = suspend_message_with(&mut client, 10_000).await;
        assert!(
            !message.nothing_sent(),
            "a payload larger than one packet must have flushed"
        );

        client.retract_partial_request(message).await;

        let wire = sent.lock().unwrap().clone();
        let last = &wire[wire.len() - PacketWriter::PACKET_HEADER_SIZE..];
        assert_eq!(
            last[1],
            PacketStatusFlags::Eom as u8 | PacketStatusFlags::Ignore as u8,
            "the retracted message must be terminated with an ignore packet"
        );
        assert_eq!(
            u16::from_be_bytes([last[2], last[3]]) as usize,
            PacketWriter::PACKET_HEADER_SIZE,
            "the ignore packet carries no payload"
        );
        assert!(
            !client.is_connection_dead(),
            "a retracted request leaves the connection clean for reuse"
        );
    }

    /// Packet #1 recorded the RESETCONNECTION dispatch, but the server discards
    /// the whole ignored message, reset included. Unless the record is cleared
    /// and the bit re-armed, the withdrawal's own DONE reads as a request that
    /// ran without resetting and condemns a healthy connection.
    #[tokio::test]
    async fn retracting_hands_back_a_reset_the_server_discarded() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);
        client.prepare_reset_connection(false);
        let message = suspend_message_with(&mut client, 10_000).await;
        assert!(!message.nothing_sent(), "the reset must be on the wire");

        client.retract_partial_request(message).await;

        assert!(
            !client.is_connection_dead(),
            "withdrawing a reset-carrying request must not condemn the connection"
        );
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::Reset,
            "the discarded reset must ride the next request instead"
        );
    }

    /// The retraction must not inherit the caller's cancellation. The request is
    /// already over; a cancelled cleanup would strand the very message it exists
    /// to withdraw.
    #[tokio::test]
    async fn retracting_ignores_a_cancel_fired_against_the_request() {
        use crate::message::messages::PacketStatusFlags;

        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let parent = CancelHandle::new();
        let message = suspend_message_under(&mut client, 10_000, Some(&parent)).await;
        client.cancel_handle = Some(parent.child_handle());
        parent.cancel();

        client.retract_partial_request(message).await;

        let wire = sent.lock().unwrap().clone();
        let last = &wire[wire.len() - PacketWriter::PACKET_HEADER_SIZE..];
        assert_eq!(
            last[1],
            PacketStatusFlags::Eom as u8 | PacketStatusFlags::Ignore as u8,
            "a fired cancel must not stop the ignore packet"
        );
        assert!(
            !client.is_connection_dead(),
            "the drain must still run, leaving the connection reusable"
        );
    }

    /// `PacketWriter` only checks its budget once a write returns, so a stalled
    /// peer would block the withdrawal forever. The deadline must fire, and the
    /// transport must be retired rather than reused - dropping a write future
    /// mid-flight is only safe because nothing writes to that stream again.
    #[tokio::test(start_paused = true)]
    async fn the_ignore_packet_gives_up_on_a_stalled_peer() {
        let transport = TestTransport::new();
        let hang = Arc::clone(&transport.send_should_hang);
        let mut client = create_test_client_with_transport(transport);
        let message = suspend_message_with(&mut client, 10_000).await;

        hang.store(true, std::sync::atomic::Ordering::SeqCst);
        client.retract_partial_request(message).await;

        assert!(
            client.is_connection_dead(),
            "a withdrawal that cannot be written must retire the transport"
        );
    }

    /// A budget expiry on the *last* packet leaves the server holding the whole
    /// request, so there is nothing to withdraw. Sending `EOM | IGNORE` there
    /// would open a second message and leave its DONE for the next command;
    /// the request has to be cancelled with an attention instead.
    #[tokio::test]
    async fn a_complete_message_is_cancelled_rather_than_withdrawn() {
        let transport = TestTransport::new();
        let attentions = Arc::clone(&transport.attentions);
        let sent = Arc::clone(&transport.sent);
        let mut client = create_test_client_with_transport(transport);

        let mut writer = PacketWriter::new(
            PacketType::RpcRequest,
            client.transport.as_writer(),
            None,
            None,
        );
        writer.write_async(&[0xABu8; 16]).await.unwrap();
        writer.finalize().await.unwrap();
        let message = writer.suspend();
        assert!(message.message_complete(), "finalize sent the last packet");
        let sent_before = sent.lock().unwrap().len();

        client.retract_partial_request(message).await;

        assert_eq!(
            attentions.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "a request the server has in full must be cancelled, not withdrawn"
        );
        assert_eq!(
            sent.lock().unwrap().len(),
            sent_before,
            "no second message may be opened to withdraw the first"
        );
        assert!(
            !client.transport.connection_known_dead(),
            "an acknowledged attention leaves the connection reusable"
        );
    }

    /// If the ignore packet cannot be sent, the request is neither complete nor
    /// retracted, so the socket is discarded rather than pooled.
    #[tokio::test]
    async fn retract_partial_request_falls_back_to_close_when_ignore_fails() {
        let (mut client, fail) = create_failing_capturing_client(vec![done_no_more()]);
        let message = suspend_message_with(&mut client, 10_000).await;

        fail.store(true, std::sync::atomic::Ordering::SeqCst);
        client.retract_partial_request(message).await;

        assert!(
            client.is_connection_dead(),
            "a request that could not be retracted must not be reused"
        );
    }

    /// The retraction is only complete once the DONE is consumed. If that read
    /// fails, the next command would pick the DONE up as its own.
    #[tokio::test]
    async fn retract_partial_request_falls_back_to_close_when_the_drain_fails() {
        // No DONE queued: the ignore packet goes out but is never acknowledged.
        let (mut client, _sent) = create_capturing_client(vec![]);
        let message = suspend_message_with(&mut client, 10_000).await;

        client.retract_partial_request(message).await;

        assert!(
            client.is_connection_dead(),
            "an unacknowledged retraction leaves the stream desynchronized"
        );
    }

    /// The liveness check is the cached flag, never the socket-polling
    /// `is_connection_dead`: this runs with a half-written message outstanding,
    /// where a `try_read` probe could swallow the server's answer to it.
    #[tokio::test]
    async fn retract_partial_request_skips_the_withdrawal_on_a_dead_connection() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        client.prepare_reset_connection(false);
        let message = suspend_message_with(&mut client, 10_000).await;
        let sent_before = sent.lock().unwrap().len();
        client.transport.mark_known_dead();

        client.retract_partial_request(message).await;

        assert_eq!(
            sent.lock().unwrap().len(),
            sent_before,
            "no withdrawal may be attempted on a dead connection"
        );
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::Reset,
            "the skipped message must still hand back the reset arm it took"
        );
    }

    /// Drives a real send site, so removing the retraction from
    /// `execute_sp_executesql` cannot leave the suite green. Parameter 1 flushes
    /// a packet; parameter 2 is rejected by `serialize_string` after it.
    #[tokio::test]
    async fn a_send_site_retracts_when_serialization_fails_after_a_flush() {
        use crate::message::messages::PacketStatusFlags;

        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);
        let big = RpcParameter::new(
            Some("@big".to_string()),
            StatusFlags::NONE,
            SqlType::VarcharMax(Some(SqlString::from_utf8_string("a".repeat(20_000)))),
        );
        let overlong = RpcParameter::new(
            Some("@bad".to_string()),
            StatusFlags::NONE,
            SqlType::Varchar(
                Some(SqlString::from_utf8_string("abcdefghij".to_string())),
                1,
            ),
        );

        let result = client
            .execute_sp_executesql("SELECT @big, @bad".to_string(), vec![big, overlong], ())
            .await;

        assert!(result.is_err(), "the over-long value must be rejected");

        let wire = sent.lock().unwrap().clone();
        let last = &wire[wire.len() - PacketWriter::PACKET_HEADER_SIZE..];
        assert_eq!(
            last[1],
            PacketStatusFlags::Eom as u8 | PacketStatusFlags::Ignore as u8,
            "the half-sent request must be withdrawn, not dropped"
        );
        assert!(
            !client.is_connection_dead(),
            "a withdrawn request leaves the connection reusable"
        );
    }

    fn partially_serializable_cursor_params() -> Vec<RpcParameter> {
        vec![
            RpcParameter::new(
                Some("@big".to_string()),
                StatusFlags::NONE,
                SqlType::VarcharMax(Some(SqlString::from_utf8_string("a".repeat(20_000)))),
            ),
            RpcParameter::new(
                Some("@bad".to_string()),
                StatusFlags::NONE,
                SqlType::Varchar(
                    Some(SqlString::from_utf8_string("abcdefghij".to_string())),
                    1,
                ),
            ),
        ]
    }

    fn assert_cursor_send_was_retracted(client: &TdsClient, sent: &Arc<std::sync::Mutex<Vec<u8>>>) {
        use crate::message::messages::PacketStatusFlags;

        let wire = sent.lock().unwrap().clone();
        assert!(
            wire.len() >= PacketWriter::PACKET_HEADER_SIZE,
            "expected at least one complete TDS packet, got {} bytes",
            wire.len()
        );
        let last = &wire[wire.len() - PacketWriter::PACKET_HEADER_SIZE..];
        assert_eq!(
            u16::from_be_bytes([last[2], last[3]]) as usize,
            PacketWriter::PACKET_HEADER_SIZE,
            "the withdrawal must end with a header-only TDS packet"
        );
        assert_eq!(
            last[1],
            PacketStatusFlags::Eom as u8 | PacketStatusFlags::Ignore as u8,
            "the half-sent cursor RPC must be withdrawn"
        );
        assert!(
            !client.is_connection_dead(),
            "a withdrawn cursor RPC must leave the connection reusable"
        );
    }

    fn assert_overlong_parameter_error(error: crate::error::Error) {
        assert!(
            error.to_string().contains("exceeds schema size"),
            "the caller must receive the original serialization error, got {error}"
        );
    }

    #[tokio::test]
    async fn cursor_open_with_params_retracts_a_partial_send() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let error = client
            .cursor_open_with_params(
                "SELECT @big, @bad",
                partially_serializable_cursor_params(),
                crate::cursor::CursorScrollOption::FORWARD_ONLY,
                crate::cursor::CursorConcurrency::READONLY,
                0,
                None,
                None,
            )
            .await
            .expect_err("the over-long cursor parameter must fail");

        assert_overlong_parameter_error(error);
        assert_cursor_send_was_retracted(&client, &sent);
    }

    #[tokio::test]
    async fn cursor_open_retracts_when_cancelled_after_a_flush() {
        let cancel = CancelHandle::new();
        let mut transport = TestTransport::with_tokens(vec![done_no_more()]);
        let sent = Arc::clone(&transport.sent);
        transport.cancel_after_send = Some(cancel.cancel_token.clone());
        let mut client = create_test_client_with_transport(transport);

        let error = client
            .cursor_open(
                &"a".repeat(20_000),
                crate::cursor::CursorScrollOption::FORWARD_ONLY,
                crate::cursor::CursorConcurrency::READONLY,
                0,
                None,
                Some(&cancel),
            )
            .await
            .expect_err("cancellation after packet one must stop serialization");

        assert!(matches!(
            error,
            crate::error::Error::OperationCancelledError(_)
        ));
        assert_cursor_send_was_retracted(&client, &sent);
    }

    #[tokio::test]
    async fn cursor_prepare_retracts_when_cancelled_after_a_flush() {
        let cancel = CancelHandle::new();
        let mut transport = TestTransport::with_tokens(vec![done_no_more()]);
        let sent = Arc::clone(&transport.sent);
        transport.cancel_after_send = Some(cancel.cancel_token.clone());
        let mut client = create_test_client_with_transport(transport);

        let error = client
            .cursor_prepare(
                &"a".repeat(20_000),
                "",
                crate::cursor::CursorScrollOption::FORWARD_ONLY,
                crate::cursor::CursorConcurrency::READONLY,
                None,
                Some(&cancel),
            )
            .await
            .expect_err("cancellation after packet one must stop serialization");

        assert!(matches!(
            error,
            crate::error::Error::OperationCancelledError(_)
        ));
        assert_cursor_send_was_retracted(&client, &sent);
    }

    #[tokio::test]
    async fn set_cursor_option_retracts_when_cancelled_after_a_flush() {
        let cancel = CancelHandle::new();
        let mut transport = TestTransport::with_tokens(vec![done_no_more()]);
        let sent = Arc::clone(&transport.sent);
        transport.cancel_after_send = Some(cancel.cancel_token.clone());
        let mut client = create_test_client_with_transport(transport);

        let error = client
            .set_cursor_option(
                1,
                crate::cursor::CursorOptionCode::CursorName,
                crate::cursor::CursorOptionValue::String("a".repeat(20_000)),
                None,
                Some(&cancel),
            )
            .await
            .expect_err("cancellation after packet one must stop serialization");

        assert!(matches!(
            error,
            crate::error::Error::OperationCancelledError(_)
        ));
        assert_cursor_send_was_retracted(&client, &sent);
    }

    #[tokio::test]
    async fn perform_cursor_operation_retracts_a_partial_send() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let error = client
            .perform_cursor_operation(
                1,
                crate::cursor::CursorOperation::UPDATE,
                1,
                "",
                partially_serializable_cursor_params(),
                None,
                None,
            )
            .await
            .expect_err("the over-long cursor parameter must fail");

        assert_overlong_parameter_error(error);
        assert_cursor_send_was_retracted(&client, &sent);
    }

    #[tokio::test]
    async fn cursor_prepexec_retracts_a_partial_send() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let error = client
            .cursor_prepexec(
                "SELECT @big, @bad",
                partially_serializable_cursor_params(),
                crate::cursor::CursorScrollOption::FORWARD_ONLY,
                crate::cursor::CursorConcurrency::READONLY,
                0,
                None,
                None,
            )
            .await
            .expect_err("the over-long cursor parameter must fail");

        assert_overlong_parameter_error(error);
        assert_cursor_send_was_retracted(&client, &sent);
    }

    #[tokio::test]
    async fn cursor_execute_retracts_a_partial_send() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let error = client
            .cursor_execute(
                1,
                partially_serializable_cursor_params(),
                crate::cursor::CursorScrollOption::FORWARD_ONLY,
                crate::cursor::CursorConcurrency::READONLY,
                0,
                None,
                None,
            )
            .await
            .expect_err("the over-long cursor parameter must fail");

        assert_overlong_parameter_error(error);
        assert_cursor_send_was_retracted(&client, &sent);
    }

    /// The retraction runs on its own budget, so a request that had a timeout
    /// left does not have it spent by the withdrawal — and one that had none
    /// still gets a bounded drain rather than blocking forever.
    #[tokio::test]
    async fn retracting_does_not_spend_the_request_timeout() {
        for budget in [None, Some(Duration::from_secs(30))] {
            let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);
            let message = suspend_message_with(&mut client, 10_000).await;
            client.remaining_request_timeout = budget;

            client.retract_partial_request(message).await;

            assert_eq!(
                client.remaining_request_timeout, budget,
                "the cancel budget must not leak into the request's"
            );
        }
    }

    /// The drain that consumes the withdrawal's DONE must run under
    /// [`CANCEL_TIMEOUT`], never under the request's own budget. A request
    /// without a timeout is the case that matters: inheriting its `None` would
    /// block forever on a server that never acknowledges the withdrawal, holding
    /// the connection with no way for the application to intervene.
    ///
    /// Asserting the budget the read was *given* is the whole property; that
    /// `tokio::time::timeout` honours a `Duration` is not this crate's to prove.
    #[tokio::test]
    async fn the_withdrawal_drain_runs_under_the_cancel_budget() {
        for request_budget in [None, Some(Duration::from_secs(3600))] {
            let (mut client, observed) = create_timeout_observing_client(vec![done_no_more()]);
            let message = suspend_message_with(&mut client, 10_000).await;
            client.remaining_request_timeout = request_budget;

            client.retract_partial_request(message).await;

            let seen = observed.lock().unwrap().clone();
            assert_eq!(seen.len(), 1, "the withdrawal reads exactly one DONE");
            assert_eq!(
                seen[0],
                Some(CANCEL_TIMEOUT),
                "request budget {request_budget:?} must not reach the withdrawal"
            );
        }
    }

    /// A parked streamed write owns the connection until it closes. A second
    /// execute would interleave its RPC into the half-written request.
    #[tokio::test]
    async fn begin_execute_prepared_rejects_a_second_call_while_streaming() {
        let (mut client, _sent) = create_capturing_client(vec![]);
        let mut statement = PreparedStatement::new("INSERT INTO t(v) VALUES (@v)");
        let mut orphaned = None;

        client
            .begin_execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                (),
            )
            .await
            .expect("begin must park for the streamed value");

        let mut second = PreparedStatement::new("SELECT 1");
        let err = client
            .begin_execute_prepared(&mut second, Vec::new(), &mut orphaned, ())
            .await
            .expect_err("the connection is busy with a parked streamed write");
        assert!(matches!(err, UsageError(_)));
    }

    /// Always Encrypted resolves parameter ciphertext from the complete value
    /// set before the request is built, which a value that only arrives in later
    /// chunks cannot satisfy. The combination is refused rather than silently
    /// sent as plaintext.
    #[tokio::test]
    async fn begin_execute_prepared_rejects_streamed_params_under_always_encrypted() {
        use crate::connection::client_context::ExecutionColumnEncryptionSetting;
        use crate::message::features::always_encrypted::AlwaysEncryptedFeature;
        use crate::message::login::Feature;

        let mut negotiated_settings =
            crate::handler::handler_factory::create_test_negotiated_settings_internal();
        let mut feature = AlwaysEncryptedFeature::default();
        feature.set_acknowledged(true);
        negotiated_settings
            .session_settings
            .supported_features
            .push(Box::new(feature));

        let mut client = TdsClient::new(
            AnyTransport::dynamic(TestTransport::new()),
            negotiated_settings,
            crate::connection::execution_context::ExecutionContext::new(),
            ClientContext::with_data_source("tcp:localhost,1433"),
            Vec::new(),
        );

        let mut statement = PreparedStatement::new("INSERT INTO t(v) VALUES (@v)");
        let mut orphaned = None;
        let err = client
            .begin_execute_prepared(
                &mut statement,
                vec![streamed_varbinary("@v")],
                &mut orphaned,
                ExecuteOptions::new().column_encryption(ExecutionColumnEncryptionSetting::Enabled),
            )
            .await
            .expect_err("a streamed value cannot be encrypted");
        assert!(matches!(err, UsageError(_)));
    }

    /// `write_streamed_chunk` with no active streamed parameter is a usage error.
    #[tokio::test]
    async fn write_streamed_chunk_without_active_stream_errors() {
        let mut client = create_test_client_with_tokens(vec![]);
        let err = client
            .write_streamed_chunk(&[0x01])
            .await
            .expect_err("no active streamed parameter");
        assert!(matches!(err, UsageError(_)));
    }

    /// `end_streamed_param` with no active streamed parameter is a usage error.
    #[tokio::test]
    async fn end_streamed_param_without_active_stream_errors() {
        let mut client = create_test_client_with_tokens(vec![]);
        let err = client
            .end_streamed_param()
            .await
            .expect_err("no active streamed parameter");
        assert!(matches!(err, UsageError(_)));
    }

    #[tokio::test]
    async fn write_streamed_chunk_empty_while_idle_is_usage_error() {
        let mut client = create_test_client_with_tokens(vec![]);
        let err = client
            .write_streamed_chunk(&[])
            .await
            .expect_err("empty chunk while Idle must be a usage error");
        assert!(matches!(err, UsageError(_)));
    }

    #[tokio::test]
    async fn normal_command_blocked_while_streamed_write_active() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);
        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();
        let err = client
            .execute_sp_executesql("SELECT 1".to_string(), vec![], ())
            .await
            .expect_err("normal command must be blocked while streaming");
        assert!(matches!(err, UsageError(_)));
        client.write_streamed_null().unwrap();
        let status = client.end_streamed_param().await.unwrap();
        assert!(matches!(
            status,
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));
    }

    #[tokio::test]
    async fn write_streamed_chunk_resets_timeout_to_configured_budget() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);
        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                ExecuteOptions::new().timeout_secs(30),
            )
            .await
            .unwrap();
        client.remaining_request_timeout = Some(Duration::from_secs(1));
        client.write_streamed_chunk(&[0x01]).await.unwrap();
        assert_eq!(
            client.remaining_request_timeout,
            Some(Duration::from_secs(30))
        );
        client.remaining_request_timeout = Some(Duration::from_secs(1));
        client.end_streamed_param().await.unwrap();
    }
    /// Little-endian UTF-16 encoding of `s`, matching how parameter names are
    /// written on the wire (length-prefixed unicode).
    fn utf16le(s: &str) -> Vec<u8> {
        s.encode_utf16().flat_map(u16::to_le_bytes).collect()
    }

    /// A materialized (send-now) named parameter and a data-at-execution one may
    /// be mixed: the materialized value is sent atomically in the RPC prefix and
    /// the streamed value follows. Offline analogue of the sparse non-PLP + PLP
    /// e2e test. The materialized name precedes the streamed value opener, and
    /// the streamed value frames correctly.
    #[tokio::test]
    async fn streamed_write_mixes_materialized_and_data_at_exec() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        let materialized = RpcParameter::new(
            Some("@id".to_string()),
            StatusFlags::NONE,
            SqlType::Int(Some(7)),
        );

        let status = client
            .begin_sp_executesql(
                "INSERT INTO t(id, v) VALUES (@id, @v)".to_string(),
                vec![materialized, streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();
        assert!(
            matches!(&status, StreamedParamStatus::NeedData { param_name } if param_name == "@v")
        );

        let value = [0xCDu8; 8];
        client.write_streamed_chunk(&value).await.unwrap();
        assert!(matches!(
            client.end_streamed_param().await.unwrap(),
            StreamedParamStatus::Complete(
                StatementResult::NoRows { .. } | StatementResult::Rows | StatementResult::End
            )
        ));

        let payload = reassemble_sent(&sent.lock().unwrap());

        // The streamed value opener is the last unknown-length sentinel, and the
        // materialized parameter's name is serialized before it.
        let v_pos = find_last(&payload, &PLP_UNKNOWN_LEN_BYTES).unwrap();
        let id_name = utf16le("@id");
        let id_pos = find_last(&payload[..v_pos], &id_name)
            .expect("materialized parameter name must be serialized before the streamed value");
        assert!(id_pos < v_pos, "@id must precede the streamed @v value");

        let mut expected = Vec::new();
        expected.extend_from_slice(&(value.len() as u32).to_le_bytes());
        expected.extend_from_slice(&value);
        expected.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert_eq!(
            &payload[v_pos + PLP_UNKNOWN_LEN_BYTES.len()..],
            expected.as_slice()
        );
    }

    /// After `begin_sp_executesql` parks the message, the streamed state must
    /// retain the un-emitted parameters and the collation used to write their
    /// TYPE_INFO. Analogue of the read side's pause-state-preserves-collation
    /// test.
    #[tokio::test]
    async fn streamed_write_pause_state_preserves_pending_and_collation() {
        let (mut client, _sent) = create_capturing_client(vec![done_no_more()]);
        let expected_collation = client.negotiated_settings.database_collation;

        client
            .begin_sp_executesql(
                "INSERT INTO t(a, b, c) VALUES (@a, @b, @c)".to_string(),
                vec![
                    streamed_varbinary("@a"),
                    streamed_varbinary("@b"),
                    streamed_varbinary("@c"),
                ],
                (),
            )
            .await
            .unwrap();

        match &client.streamed_write_state {
            StreamedWriteState::Active(ctx) => {
                // @a is open for data; @b and @c remain pending, in order.
                assert_eq!(ctx.pending.len(), 2);
                assert_eq!(ctx.pending[0].name.as_deref(), Some("@b"));
                assert_eq!(ctx.pending[1].name.as_deref(), Some("@c"));
                assert_eq!(ctx.db_collation, expected_collation);
            }
            StreamedWriteState::Idle => panic!("streamed write should be Active after begin"),
        }
    }

    /// A single chunk larger than the TDS packet payload is split across multiple
    /// packets on the wire yet reassembles into one contiguous length-prefixed
    /// value. Analogue of multi-packet incremental reads.
    #[tokio::test]
    async fn streamed_write_large_chunk_spans_multiple_packets() {
        let (mut client, sent) = create_capturing_client(vec![done_no_more()]);

        client
            .begin_sp_executesql(
                "INSERT INTO t(v) VALUES (@v)".to_string(),
                vec![streamed_varbinary("@v")],
                (),
            )
            .await
            .unwrap();

        // Larger than the mock transport's 4096-byte packet so the value must
        // span several TDS packets.
        let big: Vec<u8> = (0..10_000u32).map(|i| (i % 251) as u8).collect();
        client.write_streamed_chunk(&big).await.unwrap();
        client.end_streamed_param().await.unwrap();

        // The captured stream is more than one packet.
        assert!(
            sent.lock().unwrap().len() > 4096,
            "a 10 KB value must produce multiple TDS packets"
        );

        let payload = reassemble_sent(&sent.lock().unwrap());
        let pos = find_last(&payload, &PLP_UNKNOWN_LEN_BYTES).unwrap();

        let mut expected = Vec::new();
        expected.extend_from_slice(&(big.len() as u32).to_le_bytes());
        expected.extend_from_slice(&big);
        expected.extend_from_slice(&PLP_TERMINATOR_BYTES);
        assert_eq!(
            &payload[pos + PLP_UNKNOWN_LEN_BYTES.len()..],
            expected.as_slice()
        );
    }

    // ── ResetConnection ENVCHANGE: full client-side state transition (A1/A3) ──

    fn error_token_with_severity(severity: u8) -> crate::token::tokens::ErrorToken {
        crate::token::tokens::ErrorToken {
            number: 4060,
            state: 1,
            severity,
            message: "test error".to_string(),
            server_name: "test-server".to_string(),
            proc_name: String::new(),
            line_number: 1,
        }
    }

    /// A server-acknowledged connection reset must return the client to its
    /// login baseline: session-bound caches emptied and negotiated
    /// database/language/collation restored to their login values, so a
    /// previous borrower's `USE otherdb` / `SET LANGUAGE` and prepared handles
    /// do not leak to the next borrower.
    #[tokio::test]
    async fn reset_connection_ack_clears_caches_and_restores_login_defaults() {
        use crate::security::describe_parameter_encryption::DescribeParameterEncryptionResult;
        use crate::token::tokens::{
            EnvChangeContainer, EnvChangeToken, EnvChangeTokenSubType, SqlCollation,
        };

        let mut client = create_test_client_with_tokens(vec![
            Tokens::EnvChange(EnvChangeToken {
                sub_type: EnvChangeTokenSubType::ResetConnection,
                change_type: EnvChangeContainer::from((0u32, 0u32)),
            }),
            done_no_more(),
        ]);

        // Session-bound state a borrower accumulated before the reset.
        client.prepared_handles.insert(sid(1), 55);
        client
            .prepared_param_encryption
            .insert(sid(1), Arc::new(DescribeParameterEncryptionResult::new()));
        client.pending_capture = Some(sid(2));
        client.pending_prepared_param_encryption =
            Some(Arc::new(DescribeParameterEncryptionResult::new()));
        client.negotiated_settings.database = "otherdb".to_string();
        client.negotiated_settings.language = "français".to_string();
        client.negotiated_settings.database_collation = SqlCollation {
            info: 0,
            lcid_language_id: 0x0000,
            col_flags: 0,
            sort_id: 0,
        };

        client.drain_stream().await.unwrap();

        assert!(
            client.prepared_handles.is_empty(),
            "prepared handles belong to the reset session"
        );
        assert!(
            client.prepared_param_encryption.is_empty(),
            "cached AE describe metadata must be dropped"
        );
        assert!(client.pending_capture.is_none());
        assert!(client.pending_prepared_param_encryption.is_none());
        assert_eq!(client.database(), "master", "database reverts to login");
        assert_eq!(client.language(), "us_english", "language reverts to login");
        assert_eq!(
            client.get_collation().lcid_language_id,
            0x0409,
            "collation reverts to login"
        );
    }

    /// Arming the reset drops the session-bound caches immediately, without a
    /// round trip, and leaves the acknowledgement outstanding until the server
    /// confirms it on the request that carries the bit.
    #[tokio::test]
    async fn prepare_reset_connection_clears_caches_and_arms_bit() {
        use crate::message::messages::PacketStatusFlags;
        use crate::token::tokens::{EnvChangeContainer, EnvChangeToken, EnvChangeTokenSubType};

        let (mut client, sent) = create_capturing_client(vec![
            Tokens::EnvChange(EnvChangeToken {
                sub_type: EnvChangeTokenSubType::ResetConnection,
                change_type: EnvChangeContainer::from((0u32, 0u32)),
            }),
            done_no_more(),
        ]);
        client.prepared_handles.insert(sid(1), 55);

        client.prepare_reset_connection(false);

        assert!(
            client.prepared_handles.is_empty(),
            "arming must drop session-bound caches without waiting for the ack"
        );
        assert!(
            client.reset_pending(),
            "the acknowledgement is still outstanding until the server confirms"
        );
        assert!(
            sent.lock().unwrap().is_empty(),
            "arming must not send anything on its own"
        );

        // The next request carries the bit and collects the acknowledgement.
        client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect("the carrying request should succeed");
        client.close_query().await.expect("drain the ack");

        let sent = sent.lock().unwrap();
        assert_eq!(
            sent[1] & PacketStatusFlags::ResetConnection as u8,
            PacketStatusFlags::ResetConnection as u8,
            "the next request must carry the RESETCONNECTION bit in its first packet"
        );
        assert!(
            !client.reset_pending(),
            "the ResetConnection ack must clear the pending flag"
        );
    }

    /// The fail-at-checkout guarantee: a request that carried the
    /// RESETCONNECTION bit and completed without the server's ENVCHANGE ran
    /// against a session that was never reset. The client fails that request and
    /// marks itself dead so a pool discards the connection instead of handing a
    /// dirty session to the next borrower.
    #[tokio::test]
    async fn unacknowledged_reset_fails_the_carrying_request_and_marks_it_dead() {
        // No ResetConnection ENVCHANGE: the batch just completes.
        let mut client = create_test_client_with_tokens(vec![done_no_more()]);
        client.prepare_reset_connection(false);

        let err = client
            .execute(
                "SET TRANSACTION ISOLATION LEVEL READ COMMITTED".to_string(),
                (),
            )
            .await
            .expect_err("an unacknowledged reset must fail the carrying request");

        assert!(
            matches!(err, crate::error::Error::ConnectionResetNotAcknowledged),
            "expected ConnectionResetNotAcknowledged, got {err:?}"
        );
        assert!(
            client.is_connection_dead(),
            "the connection must be marked dead so the pool discards it"
        );
        assert!(
            !client.reset_pending(),
            "the failure is reported once; the drain that follows must not repeat it"
        );
    }

    /// A row-returning carrier fails at its COLMETADATA rather than waiting for
    /// the rows to be read: the reset ENVCHANGE precedes everything the request
    /// produces, so the first result-set token already proves it never arrived.
    #[tokio::test]
    async fn unacknowledged_reset_fails_a_row_returning_carrier_at_its_metadata() {
        let mut client = create_test_client_with_tokens(vec![empty_col_metadata(), done_no_more()]);
        client.prepare_reset_connection(false);

        let err = client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect_err("an unacknowledged reset must fail the carrying request");

        assert!(
            matches!(err, crate::error::Error::ConnectionResetNotAcknowledged),
            "expected ConnectionResetNotAcknowledged, got {err:?}"
        );
        assert!(client.is_connection_dead());
    }

    /// The server's own diagnostic must win over the reset verdict: a request
    /// that fails outright tells the caller something more actionable, and the
    /// unacknowledged reset is still caught on the next token.
    #[tokio::test]
    async fn server_error_on_the_carrier_is_not_masked_by_the_reset_verdict() {
        let mut client = create_test_client_with_tokens(vec![
            Tokens::Error(error_token_with_severity(16)),
            done_no_more(),
        ]);
        client.prepare_reset_connection(false);

        let err = client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect_err("the server error must surface");

        assert!(
            matches!(err, crate::error::Error::SqlServerError { .. }),
            "the server diagnostic must reach the caller, got {err:?}"
        );
        assert!(
            client.is_connection_dead(),
            "the unacknowledged reset is not lost: the drain that follows the error \
             still condemns the connection"
        );
    }

    /// The bit is armed on the connection but consumed by the packet writer, so
    /// an arm that never reached the wire owes nothing. This is the shape a
    /// transparent reconnect leaves behind — the armed bit died with the old
    /// transport — and it must never condemn the responses that follow.
    #[tokio::test]
    async fn armed_reset_that_never_reached_the_wire_condemns_nothing() {
        let mut client = create_test_client_with_tokens(vec![done_no_more()]);
        client.prepare_reset_connection(false);

        client
            .drain_stream()
            .await
            .expect("a response no reset bit was sent on must not be condemned");

        assert!(
            !client.is_connection_dead(),
            "nothing was ever owed, so nothing may be failed"
        );
        assert!(
            client.reset_pending(),
            "the reset is still armed and will ride the next request"
        );
    }

    #[test]
    fn attention_ack_does_not_disprove_reset_for_an_interrupted_request() {
        use crate::connection::transport::network_transport::AttentionSettlement;

        let mut client = create_test_client();
        client.reset_state = ResetAckState::AwaitingAck;
        client.recovery_context.session_recovery_negotiated = true;

        assert!(client.apply_attention_settlement(AttentionSettlement {
            tokens: vec![Tokens::Done(DoneToken {
                status: DoneStatus::ATTN,
                cur_cmd: CurrentCommand::Select,
                row_count: 0,
            })],
            overflowed: false,
        }));
        assert!(!client.is_connection_dead());
        assert!(client.recovery_context.session_recovery_negotiated);
        assert!(client.reset_pending());

        client.settle_abandoned_reset_verification();
        assert!(!client.reset_pending());
        assert!(!client.is_connection_dead());
    }

    /// Regression: a carrying request whose response is abandoned before a
    /// reset verdict must not leave its suspicion behind for the *next* request
    /// to answer for. Doing so would mark a healthy connection dead on a token
    /// that had nothing to do with the reset.
    #[tokio::test]
    async fn abandoned_carrier_does_not_condemn_the_next_request() {
        let mut client = create_test_client_with_tokens(vec![done_no_more()]);
        client.prepare_reset_connection(false);

        // Send the carrier but never read its response: the bit is on the wire
        // and no verdict token was observed.
        client
            .send_query_batch(
                "SET TRANSACTION ISOLATION LEVEL READ COMMITTED".to_string(),
                ().into(),
            )
            .await
            .expect("the carrier is sent");
        assert!(
            client.reset_pending(),
            "precondition: the reset is still outstanding when the response is abandoned"
        );

        // The next, unrelated request must complete normally.
        client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect("an unrelated request must not answer for an abandoned reset");

        assert!(
            !client.is_connection_dead(),
            "the next request must not be charged for a reset it never carried"
        );
        assert!(
            !client.reset_pending(),
            "the abandoned reset is settled, not left outstanding forever"
        );
    }

    /// The other abandonment shape: the response *was* partially read — a
    /// non-verdict token advanced tracking to `AwaitingAck` — and then ended
    /// before any token could settle it. Cancellation landing mid-response
    /// produces this, and like the never-read case it must not be carried into
    /// the next request.
    #[tokio::test]
    async fn abandoned_carrier_that_reached_awaiting_ack_is_settled_too() {
        // One INFO token, then the stream ends: INFO is not evidence the
        // request ran, so tracking advances to `AwaitingAck` and stops there.
        let mut client = create_test_client_with_tokens(vec![info_token(0, 0, "mid-response")]);
        client.prepare_reset_connection(false);

        client
            .execute(
                "SET TRANSACTION ISOLATION LEVEL READ COMMITTED".to_string(),
                (),
            )
            .await
            .expect_err("the scripted stream ends before the batch completes");
        assert!(
            !client.is_connection_dead(),
            "an inconclusive token must not condemn the carrier itself"
        );
        assert!(
            client.reset_pending(),
            "precondition: the acknowledgement is still outstanding when the response ends"
        );

        client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect_err("the scripted transport has no tokens left");

        assert!(
            !client.is_connection_dead(),
            "the next request must not be charged for the abandoned reset"
        );
        assert!(
            !client.reset_pending(),
            "the abandoned reset is settled at the start of the next command"
        );
    }

    /// The settlement above must not fire on the ordinary armed-but-unsent
    /// reset: starting a command while a reset is armed is the normal path, and
    /// that command is the one that carries the bit.
    #[tokio::test]
    async fn starting_a_command_leaves_an_unsent_armed_reset_alone() {
        let mut client = create_test_client_with_tokens(vec![
            Tokens::EnvChange(crate::token::tokens::EnvChangeToken {
                sub_type: EnvChangeTokenSubType::ResetConnection,
                change_type: crate::token::tokens::EnvChangeContainer::from((0u32, 0u32)),
            }),
            done_no_more(),
        ]);
        client.prepare_reset_connection(false);

        client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect("the armed reset must still ride this request and be acknowledged");

        assert!(!client.is_connection_dead());
        assert!(
            !client.reset_pending(),
            "the acknowledgement arrived on the carrying request"
        );
    }

    /// Session recovery supersedes a pending reset: the new login is already at
    /// the session defaults and the old bit died with the old transport, so no
    /// acknowledgement is coming. Adopting the recovered session must clear the
    /// pending reset, or the first response on a healthy new connection would
    /// report it as unacknowledged and throw the connection away.
    #[tokio::test]
    async fn adopting_a_recovered_session_clears_a_pending_reset() {
        // A server error is inconclusive about the reset, and the stream ends
        // there — the shape of a session that errored and then dropped — so the
        // reset is still outstanding when recovery kicks in.
        let mut client =
            create_test_client_with_tokens(vec![Tokens::Error(error_token_with_severity(16))]);
        client.prepare_reset_connection(false);
        let _ = client.execute("SELECT 1".to_string(), ()).await;
        assert!(client.reset_pending());

        client
            .adopt_recovered_session(
                AnyTransport::dynamic(TestTransport::with_tokens(vec![done_no_more()])),
                crate::handler::handler_factory::create_test_negotiated_settings_internal(),
                ExecutionContext::new(),
                Vec::new(),
                &[],
            )
            .expect("adopting a recovered session must succeed");

        assert!(
            !client.reset_pending(),
            "a fresh login supersedes the reset it can no longer acknowledge"
        );
        client
            .drain_stream()
            .await
            .expect("the recovered session must serve responses normally");
    }

    /// Regression: the cursor RPCs consume their responses via `drain_stream`
    /// but never call `begin_command`, so settling only there left a cursor op
    /// issued after an abandoned carrier to be condemned on its first token —
    /// the exact false positive the settlement exists to prevent. Every cursor
    /// entry point does call `check_and_reconnect`, so the settle lives there
    /// too. Driven through `check_and_reconnect` directly, which is the shared
    /// request boundary the cursor path relies on.
    #[tokio::test]
    async fn cursor_path_request_boundary_settles_an_abandoned_carrier() {
        let mut client = create_test_client_with_tokens(vec![done_no_more()]);
        client.prepare_reset_connection(false);

        // Send a carrier but never read its response, leaving no reset verdict.
        client
            .send_query_batch(
                "SET TRANSACTION ISOLATION LEVEL READ COMMITTED".to_string(),
                ().into(),
            )
            .await
            .expect("the carrier is sent");
        assert!(
            client.reset_pending(),
            "precondition: the acknowledgement is outstanding when the response is abandoned"
        );

        // A cursor op's boundary: no `begin_command`, only `check_and_reconnect`.
        client
            .check_and_reconnect(None, None)
            .await
            .expect("the boundary check must not fail");

        assert!(
            !client.reset_pending(),
            "the cursor path's request boundary must settle the abandoned reset"
        );
        assert!(
            !client.is_connection_dead(),
            "a cursor op must not be charged for a reset it never carried"
        );
    }

    /// Regression: the arm is consumed by `PacketWriter::new` *before* any bytes
    /// are written, so a message abandoned during serialization takes it with it
    /// while leaving no dispatch record — e.g. a parameter-encoding failure,
    /// which propagates without condemning the transport. The connection would
    /// then sit in `Armed` forever: nothing carries the bit, so nothing reaches
    /// `AwaitingAck`, and the session is silently never reset. The request
    /// boundary must put the arm back.
    #[tokio::test]
    async fn an_arm_lost_with_an_abandoned_message_is_restored_at_the_next_boundary() {
        use crate::message::messages::ResetConnectionMode;

        let mut client = create_test_client_with_tokens(vec![
            Tokens::EnvChange(crate::token::tokens::EnvChangeToken {
                sub_type: EnvChangeTokenSubType::ResetConnection,
                change_type: crate::token::tokens::EnvChangeContainer::from((0u32, 0u32)),
            }),
            done_no_more(),
        ]);
        client.prepare_reset_connection(false);

        // Simulate a message that consumed the arm and was then abandoned before
        // anything reached the wire: the writer's mode is taken, and no dispatch
        // was recorded.
        let taken = client.transport.as_writer().take_reset_mode();
        assert_eq!(
            taken,
            ResetConnectionMode::Reset,
            "precondition: arm consumed"
        );
        assert!(
            !client.transport.as_writer().take_reset_dispatched(),
            "precondition: nothing reached the wire"
        );

        // The next request's boundary must put the arm back on the writer. This
        // is asserted directly rather than via the scripted response: the mock
        // replays its ResetConnection ENVCHANGE unconditionally, so collecting an
        // acknowledgement proves nothing about whether the bit was actually sent.
        client.settle_abandoned_reset_verification();
        assert!(
            client.reset_pending(),
            "the reset is still owed; it must not be silently dropped"
        );
        assert_eq!(
            client.transport.as_writer().take_reset_mode(),
            ResetConnectionMode::Reset,
            "the lost arm must be restored to the writer, or no request ever carries the bit"
        );
        // Put it back for the end-to-end leg (the assertion above consumed it).
        client
            .transport
            .as_writer()
            .set_reset_mode(ResetConnectionMode::Reset);

        // ...so this request actually carries the bit and collects the ack.
        client
            .execute("SELECT 1".to_string(), ())
            .await
            .expect("the re-armed reset must ride this request");
        assert!(
            !client.reset_pending(),
            "the restored arm must have been carried and acknowledged"
        );
        assert!(!client.is_connection_dead());
    }

    /// The fourth `receive_token` loop — `consume_done_token`, the INSERT BULK
    /// preamble's response reader — must reach the same verdict as the other
    /// three when the carrier's response lacks the acknowledgement.
    #[tokio::test]
    async fn unacknowledged_reset_is_caught_in_consume_done_token() {
        let mut client = create_test_client_with_tokens(vec![done_no_more()]);
        client.prepare_reset_connection(false);

        client
            .send_query_batch("SELECT 1".to_string(), ().into())
            .await
            .expect("the carrier is sent");

        let err = client
            .consume_done_token()
            .await
            .expect_err("an unacknowledged reset must fail here too");

        assert!(
            matches!(err, crate::error::Error::ConnectionResetNotAcknowledged),
            "expected ConnectionResetNotAcknowledged, got {err:?}"
        );
        assert!(client.is_connection_dead());
    }

    /// D3: a server fatal-error token (severity/class ≥ 20) marks the transport
    /// known-dead even on a still-open socket, so a pool checkout discards it.
    #[test]
    fn fatal_error_token_marks_connection_known_dead() {
        let mut client = create_test_client();
        assert!(!client.is_connection_dead());

        let info = client.record_error_token(&error_token_with_severity(FATAL_ERROR_SEVERITY));

        assert_eq!(info.class, FATAL_ERROR_SEVERITY as i32);
        assert!(
            client.is_connection_dead(),
            "a class >= 20 error must mark the connection dead"
        );
    }

    /// D3 boundary: an error just below the fatal threshold (e.g. a plain
    /// severity-16 user error) leaves the connection reusable.
    #[test]
    fn nonfatal_error_token_leaves_connection_alive() {
        let mut client = create_test_client();

        client.record_error_token(&error_token_with_severity(FATAL_ERROR_SEVERITY - 1));

        assert!(
            !client.is_connection_dead(),
            "a class < 20 error must not mark the connection dead"
        );
    }
}