clickhouse-dfe 0.1.2

HyperI extensions for the official ClickHouse Rust client: TCP transport, dynamic inserts, unified client
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
//! Background-task socket-state owner for ClickHouse TCP connections.
//!
//! Built on the generic `crate::worker::CommandWorker` primitive. The
//! actor owns the writer half of a [`MaybeTlsStream`]; an independent
//! reader sub-task owns the read half and forwards every decoded server
//! packet through a bounded mpsc channel, so the read loop keeps running
//! while a write command is in flight.
//!
//! # Why an actor instead of borrowed I/O
//!
//! Holding `&mut Connection` across the two halves for the duration of a
//! query is structurally cancellation-unsafe: any `tokio::select!`,
//! `tokio::time::timeout` or caller disconnect that drops the future
//! mid-`read_packet()` leaves the socket in an unknown state, and the
//! only recovery is tearing the connection down. Owning the I/O inside a
//! long-lived task means a dropped caller future never disturbs the
//! wire; the actor observes the reply channel closing and reacts at
//! protocol level (Cancel packet, bounded drain, return to pool).
//!
//! Three capabilities only this shape unlocks:
//!
//! 1. Protocol-level Cancel during an in-flight query -- the writer is
//!    free to send it because no caller holds it.
//! 2. Full-duplex Exception detection during INSERT -- the reader
//!    sub-task surfaces a server-side rejection before the next block
//!    goes on the wire.
//! 3. Idle keepalive -- Ping between commands without racing a caller
//!    for the writer.
//!
//! # Internal layout
//!
//! ```text
//!     callers                  ConnectionActor
//!   (ConnectionHandle           (CommandWorker)            reader_task
//!    .ping().await)                                       (independent)
//!         |                          |                          |
//!         v                          |                          |
//!   WorkerHandle<Cmd>                |                          |
//!         |                          |                          |
//!         v                          |                          |
//!     mpsc::channel ----------> handle(Cmd) ----------> writer half ----> socket
//!                                    ^                                    |
//!                                    |                                    |
//!                                pkt_rx <---------- pkt_tx <-- read_packet
//! ```
//!
//! # Reader-half ownership
//!
//! `crate::tcp::connect::split_buffered` splits the stream before the
//! actor is spawned, so the actor owns the writer half and only that,
//! and the reader task owns the read half and only that. The halves
//! `tokio::io::split` returns are `Send + 'static` whenever the stream
//! is, which is what `tokio::spawn` needs for the reader sub-task.

use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use tokio::io::{AsyncWriteExt, BufReader, BufWriter, ReadHalf, WriteHalf};
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio::time::Sleep;

use crate::error::{Error, Result};
use crate::tcp::client_info::ClientInfo;
use crate::tcp::connect;
use crate::tcp::protocol::ServerHello;
use crate::tcp::reader::{self, ServerPacket};
use crate::tcp::transport::MaybeTlsStream;
use crate::tcp::writer::{self, CLIENT_NAME, CLIENT_VERSION_MAJOR_STR, CLIENT_VERSION_MINOR_STR};
use crate::worker::{self, CommandWorker, WorkerControl, WorkerHandle};

/// Bounded internal channel between the reader sub-task and the actor's
/// command loop. The reader decodes inline, so a queued packet is a whole
/// materialised block: at ClickHouse's 65,409-row default block size a
/// 20-column `UInt64` result is ~10 MB per slot, and this cap is what
/// bounds per-connection memory. Four slots keep the reader a step ahead
/// of the actor; falling behind blocks it, which propagates kernel TCP
/// backpressure to the server.
const PACKET_CHANNEL_CAPACITY: usize = 4;

/// Interval the reusable idle timer parks at when no `read_timeout` is
/// configured. The timer is re-armed on every packet wait, so this only
/// costs a wakeup on a command that has been waiting this long, and the
/// wait resumes rather than failing.
const IDLE_TIMER_PARK: Duration = Duration::from_secs(3600);

/// Capacity of the actor's command mpsc. 16 covers the "one in-flight
/// plus a few queued" pattern that pooled connections see; high
/// fan-in callers (an inserter feeding hundreds of blocks/sec) should
/// be served by a different connection entirely.
const DEFAULT_CMD_CHANNEL: usize = 16;

/// Capacity of the per-stream mpsc that
/// [`ConnectionHandle::execute_stream_cursor`] allocates between the
/// actor and the [`crate::tcp::cursor::TcpRawCursor`]. Every slot is a
/// decoded block, so it is bounded for the same reason
/// [`PACKET_CHANNEL_CAPACITY`] is; four keeps the cursor supplied
/// without doubling the buffered block count.
const STREAM_CHANNEL_CAPACITY: usize = 4;

/// Upper bound on how long the actor waits to drain response packets to
/// EndOfStream after sending a Cancel or after a server Exception. A
/// wedged server that ignores Cancel must not hold the actor task, and
/// thereby its pool slot, indefinitely.
const DRAIN_TIMEOUT: Duration = Duration::from_secs(30);

/// Cap on a single INSERT block's pre-encoded payload. One oversized
/// block stalls the actor for the length of its socket write and blocks
/// every other command on that connection, so blocks past this cap are
/// rejected rather than transmitted. The server's `max_insert_block_size`
/// default of 1M rows sits far below this ceiling at any sane row width.
const MAX_INSERT_BLOCK_BYTES: usize = 512 * 1024 * 1024;

/// Runtime state of the actor. `Idle` post-handshake, between commands,
/// and after FinishInsert or a surfaced Exception; `InsertActive`
/// between a successful `BeginInsert` and its matching `FinishInsert`.
///
/// A runtime enum rather than type-state: the actor is a single
/// sequential task driving a wire protocol, and out-of-state commands
/// reply with an error instead of panicking so the caller can recover.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ActorState {
    Idle,
    InsertActive,
}

/// Commands the [`ConnectionActor`] accepts.
///
/// Each variant embeds its own reply channel -- `oneshot` for single
/// replies, `mpsc` for streams -- so the actor never has to track
/// caller identity.
pub(crate) enum ConnectionCmd {
    /// Send a Ping; reply with `Ok(())` when Pong arrives, `Err` on
    /// I/O failure or a server Exception in place of Pong.
    Ping { reply: oneshot::Sender<Result<()>> },
    /// Run a query that does not produce client-visible rows (DDL,
    /// `SET`, INSERT-with-no-data, etc.). The actor writes the Query
    /// packet, an empty-block terminator, then drains response packets
    /// until EndOfStream (`Ok`) or a server Exception (`Err`). Receiver
    /// drop mid-flight triggers a protocol-level Cancel followed by a
    /// bounded drain so the connection stays reusable.
    ExecuteQuery {
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
        reply: oneshot::Sender<Result<()>>,
    },
    /// Begin an INSERT session. The actor writes the Query packet
    /// (typically `INSERT INTO ... FORMAT Native`), drains protocol
    /// chatter until the server's schema-block Data packet arrives,
    /// transitions to [`ActorState::InsertActive`], and replies with
    /// the `(name, type_name)` column pairs the schema block carried.
    /// An empty vec means the schema block carried no column metadata.
    BeginInsert {
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
        reply: oneshot::Sender<Result<Vec<(String, String)>>>,
    },
    /// Send a single Native-format data block during an in-flight
    /// INSERT. The actor drains already-queued server packets first, so
    /// a rejection of an earlier block aborts the INSERT before any more
    /// bytes go on the wire -- the full-duplex win the HTTP transport
    /// cannot get.
    SendInsertBlock {
        column_bytes: Vec<u8>,
        num_columns: u64,
        num_rows: u64,
        reply: oneshot::Sender<Result<()>>,
    },
    /// Terminate an INSERT session. The actor writes the empty-block
    /// sentinel, drains response packets to EndOfStream (or surfaces
    /// an Exception that arrives in between), then returns the actor
    /// to [`ActorState::Idle`] so the connection can be reused.
    FinishInsert { reply: oneshot::Sender<Result<()>> },
    /// Run a streaming SELECT, forwarding each server packet through
    /// `results`. Receiver drop triggers a protocol Cancel plus a
    /// bounded drain; a mid-stream Exception is forwarded as `Err`.
    /// Decoding happens inside the reader sub-task, so this command is
    /// purely a forwarding pipeline.
    ExecuteStream {
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
        results: mpsc::Sender<Result<ServerPacket>>,
    },
}

/// Cheap-clone send-side handle to a [`ConnectionActor`]. Every field is
/// reference-counted, so cloning is `O(1)`.
///
/// The actor task lives exactly as long as the last clone: the shared
/// `WorkerControl` drops with it and signals graceful shutdown, which
/// closes the writer half and aborts the reader sub-task.
/// [`Self::close`] takes that shutdown explicitly and waits for the
/// task, so a panic inside it surfaces.
#[derive(Clone)]
#[non_exhaustive]
pub struct ConnectionHandle {
    inner: WorkerHandle<ConnectionCmd>,
    server_hello: Arc<ServerHello>,
    poisoned: Arc<AtomicBool>,
    /// Owns the actor task. Shared so every clone counts toward the
    /// task's lifetime; `Option` so [`ConnectionHandle::close`] can take
    /// the control out and consume-await it from behind the `Arc`.
    control: Arc<tokio::sync::Mutex<Option<WorkerControl<ConnectionCmd>>>>,
}

impl ConnectionHandle {
    /// Shut the actor down and wait for its task to finish.
    ///
    /// Dropping the last clone signals the same shutdown but returns
    /// immediately; this waits, so the socket and the reader sub-task are
    /// provably gone when the call returns. Idempotent -- the second call
    /// finds the control already taken and returns `Ok(())`.
    ///
    /// # Errors
    ///
    /// [`Error::Custom`] wrapping the `JoinError` if the actor task
    /// panicked.
    pub async fn close(self) -> Result<()> {
        let control = self.control.lock().await.take();
        match control {
            Some(control) => control.shutdown().await.map_err(|e| {
                Error::Custom(format!(
                    "tcp: connection actor task did not exit cleanly: {e}"
                ))
            }),
            None => Ok(()),
        }
    }

    /// True until the connection is poisoned, which the pool consults on
    /// `recycle`. Poisoning is one-way: a poisoned handle never recovers.
    #[must_use]
    pub fn is_alive(&self) -> bool {
        !self.poisoned.load(Ordering::Acquire)
    }

    /// Mark the connection as broken. Idempotent and lock-free.
    pub(crate) fn poison(&self) {
        self.poisoned.store(true, Ordering::Release);
    }

    /// Negotiated server hello info (immutable after handshake).
    pub(crate) fn server_hello(&self) -> &ServerHello {
        &self.server_hello
    }

    /// Send a Ping and await Pong. Packets that interleave are drained
    /// inside the actor.
    ///
    /// # Errors
    ///
    /// [`Error::Custom`] if the actor has exited or dropped the reply
    /// channel; any writer or reader error otherwise. An I/O failure
    /// poisons the connection.
    pub async fn ping(&self) -> Result<()> {
        let (reply, rx) = oneshot::channel();
        self.inner
            .send(ConnectionCmd::Ping { reply })
            .await
            .map_err(|_| Error::Custom("tcp: connection actor closed".into()))?;
        rx.await
            .map_err(|_| Error::Custom("tcp: connection actor dropped ping reply".into()))?
    }

    /// Run a query that streams no rows back (DDL, `SET`,
    /// INSERT-without-data, `KILL QUERY`). Returns on EndOfStream, on an
    /// Exception, or -- if the caller's future is dropped mid-flight --
    /// once the actor has sent Cancel and drained.
    ///
    /// Dropping the returned future closes the reply channel, which the
    /// actor observes and answers at protocol level, so a cancellation
    /// never poisons the connection.
    ///
    /// # Errors
    ///
    /// [`Error::Custom`] if the actor has exited or dropped the reply
    /// channel, [`Error::ServerException`] if the server returned one in
    /// place of EndOfStream, or a writer / reader / drain-timeout error.
    pub async fn execute_query(
        &self,
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
    ) -> Result<()> {
        let (reply, rx) = oneshot::channel();
        self.inner
            .send(ConnectionCmd::ExecuteQuery {
                query_id,
                query,
                extra_settings,
                params,
                reply,
            })
            .await
            .map_err(|_| Error::Custom("tcp: connection actor closed".into()))?;
        rx.await.map_err(|_| {
            Error::Custom("tcp: connection actor dropped execute_query reply".into())
        })?
    }

    /// Begin an INSERT session and return the `(name, type_name)` pairs
    /// the server echoed in its schema block.
    ///
    /// `query` is the full SQL, typically
    /// `INSERT INTO <table> FORMAT Native`. [`Self::send_insert_block`]
    /// then writes blocks and [`Self::finish_insert`] ends the session.
    ///
    /// # Errors
    ///
    /// [`Error::Custom`] if the actor is already in an INSERT or has
    /// exited, [`Error::ServerException`] if the server rejected the
    /// INSERT before its schema block, or a writer / reader error.
    pub async fn begin_insert(
        &self,
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
    ) -> Result<Vec<(String, String)>> {
        let (reply, rx) = oneshot::channel();
        self.inner
            .send(ConnectionCmd::BeginInsert {
                query_id,
                query,
                extra_settings,
                params,
                reply,
            })
            .await
            .map_err(|_| Error::Custom("tcp: connection actor closed".into()))?;
        rx.await
            .map_err(|_| Error::Custom("tcp: connection actor dropped begin_insert reply".into()))?
    }

    /// Send one Native-format block during an in-flight INSERT.
    ///
    /// `column_bytes` is the pre-encoded payload from
    /// [`crate::native::encode_columns`]; the actor never re-encodes. It
    /// drains queued server packets first, so a rejection of an earlier
    /// block aborts the INSERT before more bytes go on the wire.
    ///
    /// # Errors
    ///
    /// [`Error::Custom`] if no INSERT is active or the actor has exited,
    /// [`Error::ServerException`] from full-duplex detection of an
    /// earlier block's rejection, or an I/O error.
    pub async fn send_insert_block(
        &self,
        column_bytes: Vec<u8>,
        num_columns: u64,
        num_rows: u64,
    ) -> Result<()> {
        let (reply, rx) = oneshot::channel();
        self.inner
            .send(ConnectionCmd::SendInsertBlock {
                column_bytes,
                num_columns,
                num_rows,
                reply,
            })
            .await
            .map_err(|_| Error::Custom("tcp: connection actor closed".into()))?;
        rx.await.map_err(|_| {
            Error::Custom("tcp: connection actor dropped send_insert_block reply".into())
        })?
    }

    /// Run a streaming SELECT and forward server packets through
    /// `results` in wire order: the schema block
    /// ([`ServerPacket::Data`] with `num_rows == 0`), zero or more
    /// payload blocks, then [`ServerPacket::EndOfStream`], which the
    /// cursor uses as its "no more rows" sentinel.
    ///
    /// Dropping the receiver triggers a protocol Cancel plus a bounded
    /// drain inside the actor, leaving the connection reusable.
    ///
    /// # Errors
    ///
    /// [`Error::Custom`] if the actor has exited. Every later error
    /// reaches the caller through `results`, not this return.
    pub(crate) async fn execute_stream(
        &self,
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
        results: mpsc::Sender<Result<ServerPacket>>,
    ) -> Result<()> {
        self.inner
            .send(ConnectionCmd::ExecuteStream {
                query_id,
                query,
                extra_settings,
                params,
                results,
            })
            .await
            .map_err(|_| Error::Custom("tcp: connection actor closed".into()))
    }

    /// Open a streaming SELECT and hand back a
    /// [`crate::tcp::cursor::TcpRawCursor`] that yields decoded
    /// blocks until `EndOfStream`.
    ///
    /// Allocates a small bounded mpsc pair, dispatches `ExecuteStream`,
    /// and wraps the receiver.
    ///
    /// # Errors
    ///
    /// - [`Error::Custom`] if the actor command channel is closed.
    /// - The first error returned by the actor reaches the caller via
    ///   `TcpRawCursor::next_block()`, not this constructor.
    pub async fn execute_stream_cursor(
        &self,
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
    ) -> Result<crate::tcp::cursor::TcpRawCursor> {
        let (tx, rx) = mpsc::channel(STREAM_CHANNEL_CAPACITY);
        self.execute_stream(query_id, query, extra_settings, params, tx)
            .await?;
        Ok(crate::tcp::cursor::TcpRawCursor::from_receiver(rx))
    }

    /// Terminate an in-flight INSERT session: write the empty Data block
    /// the server takes as end-of-input, drain to EndOfStream, and
    /// return to `Idle` so the connection can be reused.
    ///
    /// # Errors
    ///
    /// [`Error::Custom`] if no INSERT is active or the actor has exited,
    /// [`Error::ServerException`] if the server rejected the INSERT on
    /// commit, or an I/O or drain-timeout error.
    pub async fn finish_insert(&self) -> Result<()> {
        let (reply, rx) = oneshot::channel();
        self.inner
            .send(ConnectionCmd::FinishInsert { reply })
            .await
            .map_err(|_| Error::Custom("tcp: connection actor closed".into()))?;
        rx.await.map_err(|_| {
            Error::Custom("tcp: connection actor dropped finish_insert reply".into())
        })?
    }
}

/// Internal message carried over the reader -> actor mpsc; splitting
/// `Packet` from `Error` keeps every consumer off `Result` matching.
enum ReaderMessage {
    Packet(ServerPacket),
    Error(Error),
}

/// Tunables threaded into the actor at spawn time. Kept as a small
/// struct (rather than positional `spawn` args) so future per-connection
/// dials can be added without churning every `spawn` call site.
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct ActorConfig {
    /// Per-packet idle read timeout. When `Some(d)`, a query, stream or
    /// begin-insert read that goes `d` without receiving ANY packet is
    /// treated as a stalled server: the connection is poisoned and the
    /// caller sees [`Error::TimedOut`]. The timer resets on every packet,
    /// so this bounds the gap BETWEEN packets, not the whole query.
    /// `None` leaves reads bounded only by caller-side cancellation.
    pub read_timeout: Option<Duration>,
    /// Quota key echoed into every Query packet's `ClientInfo`, so the
    /// server attributes the query to the same quota the handshake
    /// addendum named.
    pub quota_key: String,
}

/// Background task that owns the writer half and the receive end of
/// the reader -> actor channel. Implements the crate's `CommandWorker`
/// trait, whose generic runner handles the lifecycle plumbing (command
/// loop, drain on shutdown, panic surfacing).
pub struct ConnectionActor {
    writer: BufWriter<WriteHalf<MaybeTlsStream>>,
    pkt_rx: mpsc::Receiver<ReaderMessage>,
    /// Aborted in `Drop`. Dropping a `JoinHandle` does NOT cancel the
    /// task, and the reader parks in `read_packet` until the server's own
    /// receive timeout, so without the abort every recycled connection
    /// leaks a task, an FD and a socket.
    reader_task: JoinHandle<()>,
    server_hello: Arc<ServerHello>,
    poisoned: Arc<AtomicBool>,
    /// Idle or InsertActive. Gates which commands are accepted in
    /// `CommandWorker::handle` -- see [`ActorState`] rustdoc.
    state: ActorState,
    /// Per-packet idle read timeout; see [`ActorConfig::read_timeout`].
    read_timeout: Option<Duration>,
    /// Quota key echoed into every Query packet's `ClientInfo`.
    quota_key: String,
    /// One timer for the life of the connection, re-armed per packet
    /// wait. A fresh `tokio::time::sleep` per loop iteration allocates a
    /// timer entry per packet on a streaming SELECT.
    idle_sleep: Pin<Box<Sleep>>,
}

/// One outcome of waiting for the next server packet.
enum PacketWait {
    /// The idle timer fired.
    Idle,
    /// The reader sub-task delivered a message, or closed (`None`).
    Message(Option<ReaderMessage>),
}

/// One outcome of a drain-loop wait that also watches its caller.
enum QueryEvent {
    /// The caller dropped its receiver.
    CallerGone,
    /// The idle timer fired.
    Idle,
    /// The reader sub-task delivered a message, or closed (`None`).
    Message(Option<ReaderMessage>),
}

impl ConnectionActor {
    /// Spawn an actor over a freshly handshaken stream, returning the
    /// cheap-clone handle that owns its task.
    ///
    /// `crate::tcp::connect::split_buffered` splits the stream: the read
    /// half goes to the reader sub-task, the write half to the actor. On
    /// shutdown the actor closes the write half and its `Drop` aborts
    /// the reader task, which releases the socket.
    #[must_use]
    pub fn spawn(stream: MaybeTlsStream, server_hello: ServerHello) -> ConnectionHandle {
        Self::spawn_with_config(stream, server_hello, ActorConfig::default())
    }

    /// Spawn an actor with explicit [`ActorConfig`] tunables; the pool's
    /// `Manager::create` uses this form to thread its dials through.
    #[must_use]
    pub fn spawn_with_config(
        stream: MaybeTlsStream,
        server_hello: ServerHello,
        config: ActorConfig,
    ) -> ConnectionHandle {
        let (reader_half, writer_half) = connect::split_buffered(stream);

        let server_hello = Arc::new(server_hello);
        let poisoned = Arc::new(AtomicBool::new(false));

        // Reader sub-task: owns the read half, feeds packets through
        // the bounded mpsc until the socket closes or the actor's
        // receiver drops.
        let revision = server_hello.revision;
        let (pkt_tx, pkt_rx) = mpsc::channel(PACKET_CHANNEL_CAPACITY);
        let reader_task = tokio::spawn(reader_loop(reader_half, pkt_tx, revision));

        let actor = ConnectionActor {
            writer: writer_half,
            pkt_rx,
            reader_task,
            server_hello: Arc::clone(&server_hello),
            poisoned: Arc::clone(&poisoned),
            state: ActorState::Idle,
            read_timeout: config.read_timeout,
            quota_key: config.quota_key,
            idle_sleep: Box::pin(tokio::time::sleep(IDLE_TIMER_PARK)),
        };

        let control = worker::spawn(actor, DEFAULT_CMD_CHANNEL);
        let inner = control.handle();
        // The last handle drop signals shutdown, which closes the socket.
        ConnectionHandle {
            inner,
            server_hello,
            poisoned,
            control: Arc::new(tokio::sync::Mutex::new(Some(control))),
        }
    }

    /// Re-arm the idle timer for the next packet wait. With no
    /// `read_timeout` configured it parks at [`IDLE_TIMER_PARK`], and the
    /// wait resumes rather than failing when that elapses.
    fn arm_idle(&mut self) {
        let gap = self.read_timeout.unwrap_or(IDLE_TIMER_PARK);
        self.idle_sleep
            .as_mut()
            .reset(tokio::time::Instant::now() + gap);
    }

    /// Wait for the next reader message under the idle timer.
    async fn next_packet(&mut self) -> PacketWait {
        self.arm_idle();
        let Self {
            idle_sleep, pkt_rx, ..
        } = self;
        tokio::select! {
            biased;
            () = idle_sleep.as_mut() => PacketWait::Idle,
            msg = pkt_rx.recv() => PacketWait::Message(msg),
        }
    }

    /// Poison and return [`Error::TimedOut`] when the fired idle timer is
    /// a real deadline; `None` means it was only the park interval.
    fn idle_timed_out(&self) -> Option<Error> {
        self.read_timeout?;
        self.poisoned.store(true, Ordering::Release);
        Some(Error::TimedOut)
    }

    /// `ClientInfo` for one client-originated query. `query_id` is echoed
    /// into `initial_query_id` so `system.query_log.initial_query_id`
    /// matches the id the caller traces and `KILL QUERY` matches on.
    fn client_info_for(&self, query_id: &str) -> ClientInfo {
        let mut info = ClientInfo::for_initial_query(
            CLIENT_NAME,
            CLIENT_VERSION_MAJOR_STR.parse().unwrap_or(0),
            CLIENT_VERSION_MINOR_STR.parse().unwrap_or(0),
            self.server_hello.revision,
            &self.quota_key,
        );
        info.initial_query_id.push_str(query_id);
        info
    }

    /// Write the Query packet and the empty-block terminator that ends
    /// the pre-query phase. Either failing leaves the wire half-written,
    /// so every caller poisons on `Err`.
    async fn issue_query(
        &mut self,
        query_id: &str,
        query: &str,
        extra_settings: &[(String, String)],
        params: &[(String, String)],
    ) -> Result<()> {
        let client_info = self.client_info_for(query_id);
        let revision = self.server_hello.revision;
        writer::send_query(
            &mut self.writer,
            revision,
            query_id,
            query,
            extra_settings,
            params,
            &client_info,
        )
        .await?;
        writer::send_empty_block(&mut self.writer, revision).await
    }

    /// Send a Ping and wait for the Pong. Stray Progress / Log /
    /// ProfileEvents packets that interleave between Ping and Pong
    /// are logged at trace level and discarded; a server Exception
    /// surfaces as `Error::ServerException`. Reader sub-task exit or
    /// any I/O error poisons the connection.
    async fn do_ping(&mut self) -> Result<()> {
        writer::send_ping(&mut self.writer).await.inspect_err(|_| {
            self.poisoned.store(true, Ordering::Release);
        })?;
        loop {
            let msg = match self.next_packet().await {
                PacketWait::Idle => match self.idle_timed_out() {
                    Some(e) => return Err(e),
                    None => continue,
                },
                PacketWait::Message(msg) => msg,
            };
            match msg {
                Some(ReaderMessage::Packet(ServerPacket::Pong)) => return Ok(()),
                Some(ReaderMessage::Packet(ServerPacket::Exception(exc))) => {
                    // Server-side rejection. Not an I/O failure -- the
                    // socket is still usable -- but the caller needs
                    // to see the error.
                    return Err(exc.into_error());
                }
                Some(ReaderMessage::Packet(other)) => {
                    tracing::trace!(
                        target: "clickhouse::tcp",
                        ?other,
                        "ignoring interleaved packet during ping"
                    );
                }
                Some(ReaderMessage::Error(e)) => {
                    self.poisoned.store(true, Ordering::Release);
                    return Err(e);
                }
                None => {
                    // Reader sub-task exited without sending an Error
                    // (e.g. its sender dropped). Treat as a torn-down
                    // socket; poison and surface.
                    self.poisoned.store(true, Ordering::Release);
                    return Err(Error::Custom("tcp: reader sub-task exited mid-ping".into()));
                }
            }
        }
    }

    /// Write a Query packet (followed by an empty-block terminator)
    /// and drain server response packets until EndOfStream or an
    /// Exception. Watches the reply channel via `reply.closed()` so a
    /// caller-side cancellation triggers a protocol-level Cancel and a
    /// bounded drain instead of tearing the socket down.
    async fn do_execute_query(
        &mut self,
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
        mut reply: oneshot::Sender<Result<()>>,
    ) {
        if let Err(e) = self
            .issue_query(&query_id, &query, &extra_settings, &params)
            .await
        {
            self.poisoned.store(true, Ordering::Release);
            let _ = reply.send(Err(e));
            return;
        }

        // Drain response packets. `biased;` orders the cancel branch
        // first so a reply-drop racing against an in-flight packet
        // always wins -- we never want to deliver a successful Ok to
        // a caller that has already moved on.
        loop {
            self.arm_idle();
            let event = {
                let Self {
                    idle_sleep, pkt_rx, ..
                } = &mut *self;
                tokio::select! {
                    biased;
                    () = reply.closed() => QueryEvent::CallerGone,
                    () = idle_sleep.as_mut() => QueryEvent::Idle,
                    msg = pkt_rx.recv() => QueryEvent::Message(msg),
                }
            };

            match event {
                QueryEvent::CallerGone => {
                    self.cancel_and_drain("caller dropped the reply").await;
                    return;
                }
                QueryEvent::Idle => {
                    // The timer resets per packet, so reaching here means
                    // a stalled backend rather than a slow-but-
                    // progressing one.
                    if let Some(e) = self.idle_timed_out() {
                        let _ = reply.send(Err(e));
                        return;
                    }
                }
                QueryEvent::Message(Some(ReaderMessage::Packet(ServerPacket::EndOfStream))) => {
                    let _ = reply.send(Ok(()));
                    return;
                }
                QueryEvent::Message(Some(ReaderMessage::Packet(ServerPacket::Exception(exc)))) => {
                    // An Exception is terminal and leaves the connection
                    // reusable: the server sends EndOfStream only on the
                    // success path, so a drain here would stall to
                    // DRAIN_TIMEOUT and poison a healthy connection.
                    let _ = reply.send(Err(exc.into_error()));
                    return;
                }
                // Progress / Log / ProfileInfo / ProfileEvents and the
                // rest carry nothing an execute_query caller wants.
                QueryEvent::Message(Some(ReaderMessage::Packet(_))) => {}
                QueryEvent::Message(Some(ReaderMessage::Error(e))) => {
                    self.poisoned.store(true, Ordering::Release);
                    let _ = reply.send(Err(e));
                    return;
                }
                QueryEvent::Message(None) => {
                    self.poisoned.store(true, Ordering::Release);
                    let _ = reply.send(Err(Error::Custom(
                        "tcp: reader sub-task exited mid-query".into(),
                    )));
                    return;
                }
            }
        }
    }

    /// Send a protocol Cancel and drain to EndOfStream so the next
    /// caller starts on a clean stream pointer. `reason` names the
    /// trigger in the warning a failure logs.
    async fn cancel_and_drain(&mut self, reason: &str) {
        if let Err(e) = writer::send_cancel(&mut self.writer).await {
            self.poisoned.store(true, Ordering::Release);
            tracing::warn!(
                target: "clickhouse::tcp",
                error = %e,
                reason,
                "failed to send Cancel"
            );
            return;
        }
        if let Err(e) = self.drain_to_end_of_stream().await {
            // drain_to_end_of_stream poisons on its own failure modes.
            tracing::warn!(
                target: "clickhouse::tcp",
                error = %e,
                reason,
                "drain after Cancel did not reach EndOfStream"
            );
        }
    }

    /// Open an INSERT session and return the `(name, type_name)` pairs
    /// the server's schema block carried.
    ///
    /// The state transition lives in the `handle()` arm, so an `Err`
    /// return leaves the actor in `Idle` and the connection usable for
    /// further commands.
    async fn do_begin_insert(
        &mut self,
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
    ) -> Result<Vec<(String, String)>> {
        // The empty trailing block signals end-of-prequery and prompts
        // the server to answer with its schema block.
        if let Err(e) = self
            .issue_query(&query_id, &query, &extra_settings, &params)
            .await
        {
            self.poisoned.store(true, Ordering::Release);
            return Err(e);
        }

        // Drain until the schema block (Data with num_rows == 0) or
        // an Exception. Progress / Log / TableColumns are normal
        // pre-schema chatter -- discard.
        loop {
            let msg = match self.next_packet().await {
                PacketWait::Idle => match self.idle_timed_out() {
                    Some(e) => return Err(e),
                    None => continue,
                },
                PacketWait::Message(msg) => msg,
            };
            match msg {
                Some(ReaderMessage::Packet(ServerPacket::Data { columns, .. })) => {
                    // `read_packet` routes num_rows > 0 through the
                    // DataBlock variant, so a Data packet here is the
                    // schema block.
                    return Ok(columns);
                }
                Some(ReaderMessage::Packet(ServerPacket::DataBlock(block))) => {
                    // A payload block before the schema block is a
                    // protocol violation -- INSERT clients always see
                    // schema first. Poison and surface so the caller
                    // doesn't sit in a broken INSERT.
                    self.poisoned.store(true, Ordering::Release);
                    return Err(Error::BadResponse(format!(
                        "tcp: server sent payload Data block (num_rows={}) \
                         before INSERT schema block",
                        block.num_rows
                    )));
                }
                Some(ReaderMessage::Packet(ServerPacket::Exception(exc))) => {
                    return Err(exc.into_error());
                }
                Some(ReaderMessage::Packet(ServerPacket::EndOfStream)) => {
                    // The server finished without asking for data, which
                    // means it feeds itself (`INSERT ... SELECT`);
                    // `begin_insert` is for client-fed INSERT only.
                    return Err(Error::BadResponse(
                        "tcp: server returned EndOfStream before INSERT schema block \
                         (was this INSERT ... SELECT?)"
                            .into(),
                    ));
                }
                Some(ReaderMessage::Packet(_)) => {}
                Some(ReaderMessage::Error(e)) => {
                    self.poisoned.store(true, Ordering::Release);
                    return Err(e);
                }
                None => {
                    self.poisoned.store(true, Ordering::Release);
                    return Err(Error::Custom(
                        "tcp: reader sub-task exited mid begin_insert".into(),
                    ));
                }
            }
        }
    }

    /// Send one Native block during an in-flight INSERT, draining
    /// already-queued server packets first: a constraint-violating row
    /// in block N surfaces on block N+1's send, with no socket teardown.
    ///
    /// State returns to `Idle` on Exception or I/O failure; a successful
    /// write keeps the session in `InsertActive`.
    async fn do_send_insert_block(
        &mut self,
        column_bytes: Vec<u8>,
        num_columns: u64,
        num_rows: u64,
        reply: oneshot::Sender<Result<()>>,
    ) {
        // Nothing has hit the wire, so the session stays in
        // InsertActive and the caller can re-send a smaller block.
        if column_bytes.len() > MAX_INSERT_BLOCK_BYTES {
            let _ = reply.send(Err(Error::Custom(format!(
                "tcp: INSERT block of {} bytes exceeds the {MAX_INSERT_BLOCK_BYTES} byte cap; \
                 split the batch into smaller blocks",
                column_bytes.len()
            ))));
            return;
        }

        // Full-duplex check FIRST. `try_recv` is non-blocking, so we
        // drain everything queued without waiting for new packets.
        loop {
            match self.pkt_rx.try_recv() {
                Ok(ReaderMessage::Packet(ServerPacket::Exception(exc))) => {
                    // Terminal, and the connection stays usable: return to
                    // Idle and surface without draining, because no
                    // EndOfStream follows an Exception.
                    self.state = ActorState::Idle;
                    let _ = reply.send(Err(exc.into_error()));
                    return;
                }
                // Progress / Log -- keep draining.
                Ok(ReaderMessage::Packet(_)) => {}
                Ok(ReaderMessage::Error(e)) => {
                    self.poisoned.store(true, Ordering::Release);
                    self.state = ActorState::Idle;
                    let _ = reply.send(Err(e));
                    return;
                }
                Err(mpsc::error::TryRecvError::Empty) => break,
                Err(mpsc::error::TryRecvError::Disconnected) => {
                    // The reader sub-task is gone, so nothing will ever
                    // observe the server's answer to this block.
                    self.poisoned.store(true, Ordering::Release);
                    self.state = ActorState::Idle;
                    let _ = reply.send(Err(Error::Custom(
                        "tcp: reader sub-task exited mid-INSERT".into(),
                    )));
                    return;
                }
            }
        }

        let result = writer::send_data_block(
            &mut self.writer,
            self.server_hello.revision,
            "",
            &column_bytes,
            num_columns,
            num_rows,
        )
        .await;
        if result.is_err() {
            self.poisoned.store(true, Ordering::Release);
            self.state = ActorState::Idle;
        }
        let _ = reply.send(result);
    }

    /// Terminate an INSERT session: write the empty-block sentinel,
    /// drain response packets to EndOfStream (or surface an
    /// Exception). Caller's `handle()` arm returns the actor to Idle
    /// regardless of outcome.
    async fn do_finish_insert(&mut self) -> Result<()> {
        if let Err(e) = writer::send_empty_block(&mut self.writer, self.server_hello.revision).await
        {
            self.poisoned.store(true, Ordering::Release);
            return Err(e);
        }
        self.drain_to_end_of_stream().await
    }

    /// Streaming SELECT body: forward every packet the reader sub-task
    /// emits into `results` in wire order, so the cursor can stitch the
    /// blocks back together. `Pong`, `Log` and `ProfileEvents` are
    /// dropped here.
    ///
    /// Cancellation works the same way as
    /// [`Self::do_execute_query`]: `results.closed()` wins the
    /// `tokio::select!` with `biased;` and triggers a protocol Cancel
    /// plus a bounded drain.
    async fn do_execute_stream(
        &mut self,
        query_id: String,
        query: String,
        extra_settings: Vec<(String, String)>,
        params: Vec<(String, String)>,
        results: mpsc::Sender<Result<ServerPacket>>,
    ) {
        if let Err(e) = self
            .issue_query(&query_id, &query, &extra_settings, &params)
            .await
        {
            self.poisoned.store(true, Ordering::Release);
            let _ = results.send(Err(e)).await;
            return;
        }

        loop {
            self.arm_idle();
            let event = {
                let Self {
                    idle_sleep, pkt_rx, ..
                } = &mut *self;
                tokio::select! {
                    biased;
                    () = results.closed() => QueryEvent::CallerGone,
                    () = idle_sleep.as_mut() => QueryEvent::Idle,
                    msg = pkt_rx.recv() => QueryEvent::Message(msg),
                }
            };

            match event {
                QueryEvent::CallerGone => {
                    self.cancel_and_drain("stream receiver dropped").await;
                    return;
                }
                QueryEvent::Idle => {
                    if let Some(e) = self.idle_timed_out() {
                        let _ = results.send(Err(e)).await;
                        return;
                    }
                }
                QueryEvent::Message(Some(ReaderMessage::Packet(ServerPacket::EndOfStream))) => {
                    // The cursor's "no more rows" sentinel; the stream is
                    // complete whether or not the send lands.
                    let _ = results.send(Ok(ServerPacket::EndOfStream)).await;
                    return;
                }
                QueryEvent::Message(Some(ReaderMessage::Packet(ServerPacket::Exception(exc)))) => {
                    // Terminal, and no EndOfStream follows, so draining
                    // here would stall to DRAIN_TIMEOUT and poison a
                    // healthy connection.
                    let _ = results.send(Err(exc.into_error())).await;
                    return;
                }
                // Protocol chatter with no cursor relevance; the reader
                // has already consumed the block bytes behind the marker.
                QueryEvent::Message(Some(ReaderMessage::Packet(
                    ServerPacket::Pong | ServerPacket::Log | ServerPacket::ProfileEvents,
                ))) => {}
                QueryEvent::Message(Some(ReaderMessage::Packet(pkt))) => {
                    if results.send(Ok(pkt)).await.is_err() {
                        // The receiver went away between the select and
                        // this send.
                        self.cancel_and_drain("stream receiver dropped mid-send")
                            .await;
                        return;
                    }
                }
                QueryEvent::Message(Some(ReaderMessage::Error(e))) => {
                    self.poisoned.store(true, Ordering::Release);
                    let _ = results.send(Err(e)).await;
                    return;
                }
                QueryEvent::Message(None) => {
                    self.poisoned.store(true, Ordering::Release);
                    let _ = results
                        .send(Err(Error::Custom(
                            "tcp: reader sub-task exited mid-stream".into(),
                        )))
                        .await;
                    return;
                }
            }
        }
    }

    /// Drain response packets until EndOfStream, bounded by
    /// [`DRAIN_TIMEOUT`]. Used after sending Cancel (post caller-drop)
    /// or after a server Exception so the next caller starts on a
    /// clean stream pointer.
    ///
    /// On timeout the connection is poisoned, so the pool's `recycle`
    /// refuses it on the `is_alive()` check.
    async fn drain_to_end_of_stream(&mut self) -> Result<()> {
        let drain = async {
            loop {
                match self.pkt_rx.recv().await {
                    Some(ReaderMessage::Packet(ServerPacket::EndOfStream)) => return Ok(()),
                    Some(ReaderMessage::Packet(ServerPacket::Exception(exc))) => {
                        // The caller already has its own error; this one
                        // only affects the drain's return value.
                        return Err(exc.into_error());
                    }
                    Some(ReaderMessage::Packet(_)) => {}
                    Some(ReaderMessage::Error(e)) => {
                        self.poisoned.store(true, Ordering::Release);
                        return Err(e);
                    }
                    None => {
                        self.poisoned.store(true, Ordering::Release);
                        return Err(Error::Custom(
                            "tcp: reader sub-task exited mid-drain".into(),
                        ));
                    }
                }
            }
        };
        let Ok(drained) = tokio::time::timeout(DRAIN_TIMEOUT, drain).await else {
            self.poisoned.store(true, Ordering::Release);
            return Err(Error::Custom(
                "tcp: drain to EndOfStream exceeded 30s timeout".into(),
            ));
        };
        drained
    }
}

impl CommandWorker for ConnectionActor {
    type Command = ConnectionCmd;

    fn name() -> &'static str {
        "clickhouse.tcp-connection"
    }

    async fn handle(&mut self, cmd: Self::Command) {
        // State gate: Ping / ExecuteQuery / BeginInsert / ExecuteStream
        // only in `Idle`, SendInsertBlock / FinishInsert only in
        // `InsertActive`. An out-of-state command replies with an error
        // and leaves the actor alive so the caller can recover.
        match (self.state, cmd) {
            (
                ActorState::InsertActive,
                ConnectionCmd::Ping { reply } | ConnectionCmd::ExecuteQuery { reply, .. },
            ) => {
                let _ = reply.send(Err(Error::Custom("tcp: actor busy in INSERT".into())));
            }
            (ActorState::InsertActive, ConnectionCmd::BeginInsert { reply, .. }) => {
                let _ = reply.send(Err(Error::Custom("tcp: actor already in INSERT".into())));
            }
            (ActorState::InsertActive, ConnectionCmd::ExecuteStream { results, .. }) => {
                // One Err frame so the cursor's first poll surfaces the
                // misuse; the caller can finish_insert and retry.
                let _ = results
                    .send(Err(Error::Custom("tcp: actor busy in INSERT".into())))
                    .await;
            }
            (
                ActorState::Idle,
                ConnectionCmd::SendInsertBlock { reply, .. }
                | ConnectionCmd::FinishInsert { reply },
            ) => {
                let _ = reply.send(Err(Error::Custom("tcp: no INSERT session active".into())));
            }
            (ActorState::Idle, ConnectionCmd::Ping { reply }) => {
                let result = self.do_ping().await;
                if reply.send(result).is_err() {
                    // The socket is in a known state, so this is only
                    // worth a warn.
                    tracing::warn!(
                        target: "clickhouse::tcp",
                        "ping reply dropped by caller before send"
                    );
                }
            }
            (
                ActorState::Idle,
                ConnectionCmd::ExecuteQuery {
                    query_id,
                    query,
                    extra_settings,
                    params,
                    reply,
                },
            ) => {
                // do_execute_query owns the reply Sender for the full
                // duration so it can watch `reply.closed()` and react
                // to caller-side cancellation at protocol level.
                self.do_execute_query(query_id, query, extra_settings, params, reply)
                    .await;
            }
            (
                ActorState::Idle,
                ConnectionCmd::BeginInsert {
                    query_id,
                    query,
                    extra_settings,
                    params,
                    reply,
                },
            ) => {
                let result = self
                    .do_begin_insert(query_id, query, extra_settings, params)
                    .await;
                if result.is_ok() {
                    self.state = ActorState::InsertActive;
                }
                if reply.send(result).is_err() {
                    tracing::warn!(
                        target: "clickhouse::tcp",
                        "begin_insert reply dropped by caller before send"
                    );
                }
            }
            (
                ActorState::InsertActive,
                ConnectionCmd::SendInsertBlock {
                    column_bytes,
                    num_columns,
                    num_rows,
                    reply,
                },
            ) => {
                self.do_send_insert_block(column_bytes, num_columns, num_rows, reply)
                    .await;
            }
            (ActorState::InsertActive, ConnectionCmd::FinishInsert { reply }) => {
                let result = self.do_finish_insert().await;
                // The session is over either way, so return to Idle and
                // leave the connection reusable for non-INSERT commands.
                self.state = ActorState::Idle;
                if reply.send(result).is_err() {
                    tracing::warn!(
                        target: "clickhouse::tcp",
                        "finish_insert reply dropped by caller before send"
                    );
                }
            }
            (
                ActorState::Idle,
                ConnectionCmd::ExecuteStream {
                    query_id,
                    query,
                    extra_settings,
                    params,
                    results,
                },
            ) => {
                // do_execute_stream owns `results` for the full command
                // lifetime so it can watch `results.closed()` and react
                // to receiver-drop at protocol level.
                self.do_execute_stream(query_id, query, extra_settings, params, results)
                    .await;
            }
        }
    }

    /// Close the write half so the server sees FIN. `WriteHalf` has no
    /// `Drop` of its own, so nothing else ends the session from our side.
    async fn on_shutdown(&mut self) {
        if let Err(e) = self.writer.shutdown().await {
            tracing::debug!(
                target: "clickhouse::tcp",
                error = %e,
                "closing the writer half on shutdown failed"
            );
        }
    }
}

impl Drop for ConnectionActor {
    fn drop(&mut self) {
        // The reader owns the read half; aborting it is what releases the
        // socket, because it is parked in `read_packet` and will not
        // observe the closed writer for the server's whole idle timeout.
        self.reader_task.abort();
        if self.poisoned.load(Ordering::Acquire) {
            tracing::warn!(
                target: "clickhouse::tcp",
                "connection actor dropped while poisoned"
            );
        } else {
            tracing::debug!(
                target: "clickhouse::tcp",
                "connection actor dropped cleanly"
            );
        }
    }
}

/// Reader sub-task body: own the read half, forward packets one at a
/// time, and on I/O or decode failure send one `Error` and exit. A
/// closed receiver means the actor has already torn the connection down.
async fn reader_loop(
    mut r: BufReader<ReadHalf<MaybeTlsStream>>,
    tx: mpsc::Sender<ReaderMessage>,
    server_revision: u64,
) {
    loop {
        match reader::read_packet(&mut r, server_revision).await {
            Ok(pkt) => {
                if tx.send(ReaderMessage::Packet(pkt)).await.is_err() {
                    // Actor dropped the receiver. Exit silently;
                    // nothing else can usefully observe the socket.
                    return;
                }
            }
            Err(e) => {
                let _ = tx.send(ReaderMessage::Error(e)).await;
                return;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::native::io::ClickHouseWrite;
    use crate::tcp::mock::{write_schema_block, write_uint64_payload_block};
    use crate::tcp::protocol::{ClientPacketId, DBMS_TCP_PROTOCOL_VERSION, ServerPacketId};
    use tokio::io::AsyncWriteExt;
    use tokio::net::{TcpListener, TcpStream};

    // Compile-time check: ConnectionHandle must be Send + Sync so it
    // can cross task boundaries through any pool. A regression here
    // would silently break the actor's async-friendly story.
    static_assertions::assert_impl_all!(ConnectionHandle: Send, Sync);

    /// Pair an actor over a loopback `TcpStream` with the server side of
    /// the same connection, so the wire format can be scripted directly.
    /// A real loopback rather than `tokio::io::duplex` because
    /// `MaybeTlsStream::Plain` wraps a concrete `TcpStream`.
    async fn paired() -> (ConnectionHandle, TcpStream) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let connect_fut = TcpStream::connect(addr);
        let accept_fut = async { listener.accept().await.unwrap().0 };
        let (client, server) = tokio::join!(connect_fut, accept_fut);
        let client = client.unwrap();
        let _ = client.set_nodelay(true);
        let _ = server.set_nodelay(true);

        let stream = MaybeTlsStream::Plain(client);
        let hello = ServerHello {
            server_name: "mock".to_string(),
            version: (1, 0, 0),
            revision: DBMS_TCP_PROTOCOL_VERSION,
            timezone: None,
            display_name: None,
        };
        let handle = ConnectionActor::spawn(stream, hello);
        (handle, server)
    }

    /// Like [`paired`] but threads an explicit [`ActorConfig`] (e.g. a
    /// `read_timeout`) into the spawned actor.
    async fn paired_with_config(config: ActorConfig) -> (ConnectionHandle, TcpStream) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let connect_fut = TcpStream::connect(addr);
        let accept_fut = async { listener.accept().await.unwrap().0 };
        let (client, server) = tokio::join!(connect_fut, accept_fut);
        let client = client.unwrap();
        let _ = client.set_nodelay(true);
        let _ = server.set_nodelay(true);
        let stream = MaybeTlsStream::Plain(client);
        let hello = ServerHello {
            server_name: "mock".to_string(),
            version: (1, 0, 0),
            revision: DBMS_TCP_PROTOCOL_VERSION,
            timezone: None,
            display_name: None,
        };
        let handle = ConnectionActor::spawn_with_config(stream, hello, config);
        (handle, server)
    }

    /// Read one byte from the server side.
    async fn read_byte(server: &mut TcpStream) -> u8 {
        let mut buf = [0u8; 1];
        tokio::io::AsyncReadExt::read_exact(server, &mut buf)
            .await
            .unwrap();
        buf[0]
    }

    #[tokio::test]
    async fn ping_happy_path() {
        let (handle, mut server) = paired().await;

        // Server side: read the Ping varint, reply with Pong.
        let server_task = tokio::spawn(async move {
            let id = read_byte(&mut server).await;
            assert_eq!(u64::from(id), ClientPacketId::Ping as u64);
            server
                .write_var_uint(ServerPacketId::Pong as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            // Hold the connection open so the read half stays usable;
            // dropping `server` here would close the socket and
            // poison the actor on the next read.
            server
        });

        handle.ping().await.expect("ping should succeed");
        assert!(handle.is_alive());

        // Release the server side; reader sub-task will exit on the
        // resulting socket close, but the test has already passed.
        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn ping_during_reader_disconnect() {
        let (handle, server) = paired().await;

        // Drop the server side immediately. The reader sub-task will
        // observe EOF on its next read; the ping should surface as
        // an error and the handle should be poisoned.
        drop(server);

        let result = handle.ping().await;
        assert!(result.is_err(), "ping should fail after server hangup");
        assert!(
            !handle.is_alive(),
            "handle should be poisoned after reader-task exit"
        );
    }

    /// `WriteHalf` has no `Drop`, and the reader parks in `read_packet`
    /// until the server's own receive timeout, so without the explicit
    /// close and abort every recycled connection leaks a task, an FD and
    /// a socket.
    #[tokio::test]
    async fn dropping_the_last_handle_closes_the_socket_and_exits_the_reader() {
        use tokio::io::AsyncReadExt;
        let (handle, mut server) = paired().await;
        drop(handle);

        // A closed client side reads as EOF, not as a stall.
        let mut buf = [0u8; 64];
        let n = tokio::time::timeout(Duration::from_secs(2), server.read(&mut buf))
            .await
            .expect("the socket must close promptly, not wait on a server timeout")
            .expect("read after client close");
        assert_eq!(n, 0, "expected EOF on the server side, got {n} bytes");
    }

    /// `close` is the awaited form of the same shutdown, so callers that
    /// need the socket provably gone (the pool refusing a connection)
    /// have something to wait on.
    #[tokio::test]
    async fn close_waits_for_the_actor_and_is_idempotent() {
        use tokio::io::AsyncReadExt;
        let (handle, mut server) = paired().await;
        let second = handle.clone();

        handle.close().await.expect("close should succeed");

        let mut buf = [0u8; 64];
        let n = tokio::time::timeout(Duration::from_secs(2), server.read(&mut buf))
            .await
            .expect("close must have shut the socket down")
            .expect("read after close");
        assert_eq!(n, 0);

        // The control is already taken, so a second close is a no-op.
        second.close().await.expect("second close should be Ok");
    }

    /// A server that ignores Cancel must not hold the actor, and thereby
    /// its pool slot, past [`DRAIN_TIMEOUT`]. The connection is poisoned
    /// so the pool refuses it rather than handing on a stream pointer
    /// parked mid-result.
    ///
    /// Every wait here is driven explicitly -- a real socket read, or
    /// [`tokio::time::advance`]. Nothing may wait on a timer firing by
    /// itself: auto-advance is skipped whenever the driver was woken
    /// (tokio `runtime/time/mod.rs`, `park_thread_timeout`), and the
    /// reader sub-task's registered socket read makes that routine under
    /// load, so a `tokio::time::timeout` here hangs instead of firing.
    #[tokio::test(start_paused = true)]
    async fn drain_timeout_poisons_when_cancel_is_ignored() {
        use tokio::io::AsyncReadExt;
        let (handle, mut server) = paired().await;

        let cancel_handle = handle.clone();
        let exec = tokio::spawn(async move {
            cancel_handle
                .execute_query(
                    "q_drain".into(),
                    "SELECT sleep(9)".into(),
                    Vec::new(),
                    Vec::new(),
                )
                .await
        });

        // The Query packet reaching the server proves the actor is past
        // `issue_query` and sitting in its drain loop.
        let mut buf = [0u8; 4096];
        let n = server.read(&mut buf).await.expect("the Query packet");
        assert!(n > 0, "the actor must have issued the query");

        // Aborting drops the reply receiver, which is the caller-gone
        // path: Cancel, then the bounded drain. The server stays silent,
        // so the drain can only end on its own timeout.
        exec.abort();

        for _ in 0..10 {
            if !handle.is_alive() {
                break;
            }
            tokio::time::advance(DRAIN_TIMEOUT).await;
            tokio::task::yield_now().await;
        }
        assert!(
            !handle.is_alive(),
            "a drain that never reaches EndOfStream must poison the connection"
        );

        drop(server);
    }

    /// The pool hands the same connection to the next caller, so a
    /// cursor dropped mid-stream has to leave the socket on a clean
    /// packet boundary.
    #[tokio::test]
    async fn dropping_the_cursor_cancels_and_leaves_the_connection_reusable() {
        let (handle, mut server) = paired().await;

        let server_task = tokio::spawn(async move {
            use tokio::io::AsyncReadExt;
            let _drained = drain_client_bytes(&mut server).await;
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            write_uint64_payload_block(&mut server, &[1, 2, 3]).await;

            // Wait for the Cancel the cursor drop triggers, then answer
            // EndOfStream so the actor's drain completes.
            let mut chunk = [0u8; 4096];
            let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
            let mut saw_cancel = false;
            while tokio::time::Instant::now() < deadline {
                let left = deadline.saturating_duration_since(tokio::time::Instant::now());
                match tokio::time::timeout(left, server.read(&mut chunk)).await {
                    Ok(Ok(0)) => break,
                    Ok(Ok(n)) => {
                        if chunk[..n].contains(&(ClientPacketId::Cancel as u8)) {
                            saw_cancel = true;
                            break;
                        }
                    }
                    _ => break,
                }
            }
            assert!(saw_cancel, "dropping the cursor must send Cancel");
            server
                .write_var_uint(ServerPacketId::EndOfStream as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();

            // Then serve the follow-up Ping.
            let id = read_byte(&mut server).await;
            assert_eq!(u64::from(id), ClientPacketId::Ping as u64);
            server
                .write_var_uint(ServerPacketId::Pong as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        let mut cursor = handle
            .execute_stream_cursor(
                "rs_drop".into(),
                "SELECT number AS n FROM numbers(3)".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("execute_stream_cursor should succeed");
        // Take the schema block only, then abandon the stream.
        let schema = cursor.next_block().await.unwrap().expect("schema block");
        assert_eq!(schema.num_rows, 0);
        drop(cursor);

        handle
            .ping()
            .await
            .expect("the connection must be reusable after a cursor drop");
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }

    /// One oversized block would hold the actor for its whole socket
    /// write, so it is rejected before any byte goes on the wire and the
    /// session stays open for a smaller one.
    #[tokio::test]
    async fn send_insert_block_rejects_oversized_block_and_stays_in_insert() {
        let (handle, mut server) = paired().await;

        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            tokio::time::sleep(Duration::from_millis(400)).await;
            server
        });

        handle
            .begin_insert(
                "q_big".into(),
                "INSERT INTO t FORMAT Native".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("begin_insert should succeed");

        let err = handle
            .send_insert_block(vec![0u8; MAX_INSERT_BLOCK_BYTES + 1], 1, 1)
            .await
            .expect_err("an oversized block must be refused");
        match err {
            Error::Custom(msg) => assert!(msg.contains("exceeds the"), "got {msg}"),
            other => panic!("expected Custom, got {other:?}"),
        }

        // Still in InsertActive: a normal block is accepted.
        handle
            .send_insert_block(Vec::new(), 1, 0)
            .await
            .expect("the session must survive a refused block");
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }

    /// A SELECT issued during an INSERT is caller misuse; the cursor
    /// must surface it rather than hang, and the actor must survive.
    #[tokio::test]
    async fn execute_stream_during_insert_yields_one_err_frame() {
        let (handle, mut server) = paired().await;

        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            tokio::time::sleep(Duration::from_millis(400)).await;
            server
        });

        handle
            .begin_insert(
                "q_busy_stream".into(),
                "INSERT INTO t FORMAT Native".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("begin_insert should succeed");

        let mut cursor = handle
            .execute_stream_cursor("rs_busy".into(), "SELECT 1".into(), Vec::new(), Vec::new())
            .await
            .expect("dispatch succeeds; the misuse surfaces on the cursor");
        let err = cursor
            .next_block()
            .await
            .expect_err("a SELECT during an INSERT must surface an error");
        match err {
            Error::Custom(msg) => assert!(msg.contains("busy in INSERT"), "got {msg}"),
            other => panic!("expected Custom, got {other:?}"),
        }
        assert!(handle.is_alive(), "misuse must not poison the connection");

        let _server = server_task.await.unwrap();
    }

    /// A rejected INSERT leaves the socket in a known state, so the
    /// actor stays in Idle and the connection stays poolable.
    #[tokio::test]
    async fn begin_insert_exception_leaves_actor_idle_and_alive() {
        let (handle, mut server) = paired().await;

        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            write_server_exception(&mut server, 60, "no such table").await;
            // Then answer the Ping that proves the actor is Idle.
            let id = read_byte(&mut server).await;
            assert_eq!(u64::from(id), ClientPacketId::Ping as u64);
            server
                .write_var_uint(ServerPacketId::Pong as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        let err = handle
            .begin_insert(
                "q_reject".into(),
                "INSERT INTO nope FORMAT Native".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect_err("the server rejected the INSERT");
        match err {
            Error::ServerException { code, .. } => assert_eq!(code, 60),
            other => panic!("expected ServerException, got {other:?}"),
        }

        assert!(handle.is_alive(), "a rejection must not poison");
        handle
            .ping()
            .await
            .expect("the actor must be back in Idle after a rejected INSERT");

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn double_drop_safety() {
        let (handle, mut server) = paired().await;

        // Issue a ping; the server-side task is intentionally lazy
        // (sleeps before replying) so the call is in flight when we
        // drop the second handle clone.
        let clone = handle.clone();
        let ping_fut = tokio::spawn(async move { clone.ping().await });

        // Read the Ping byte to confirm the actor sent it, then
        // reply slowly so the future is alive across the drop.
        let server_task = tokio::spawn(async move {
            let _ = read_byte(&mut server).await;
            tokio::time::sleep(Duration::from_millis(20)).await;
            server
                .write_var_uint(ServerPacketId::Pong as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        // Drop the original handle while the ping is in flight; the
        // worker stays alive because the spawned ping-future still
        // holds its own clone.
        drop(handle);

        // Ping completes normally despite the drop.
        let ping_result = ping_fut.await.unwrap();
        assert!(
            ping_result.is_ok(),
            "ping should still succeed: {ping_result:?}"
        );

        // Server side cleans up.
        let _server = server_task.await.unwrap();
    }

    // -----------------------------------------------------------------
    // ExecuteQuery
    // -----------------------------------------------------------------

    /// Drain (discard) bytes from the server side of the loopback until
    /// either `cancel_byte_seen` flips to true (a Cancel packet has
    /// arrived) or `eof` is observed. The Query packet plus its
    /// empty-block terminator is verbose; tests just need to swallow
    /// the bytes so the kernel buffer doesn't fill and stall the actor.
    async fn drain_client_bytes(server: &mut TcpStream) -> Vec<u8> {
        use tokio::io::AsyncReadExt;
        let mut buf = Vec::new();
        let mut chunk = [0u8; 4096];
        // Best-effort drain with a short overall budget -- tests that
        // need the bytes back inspect `buf` after.
        let deadline = tokio::time::Instant::now() + Duration::from_millis(200);
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                break;
            }
            match tokio::time::timeout(remaining, server.read(&mut chunk)).await {
                Ok(Ok(n)) if n > 0 => buf.extend_from_slice(&chunk[..n]),
                // EOF, a read error, or the deadline: the caller inspects
                // whatever arrived before this point.
                _ => break,
            }
        }
        buf
    }

    #[tokio::test]
    async fn execute_query_happy_path() {
        let (handle, mut server) = paired().await;

        // Server side: swallow whatever the client writes, then send
        // EndOfStream so do_execute_query returns Ok.
        let server_task = tokio::spawn(async move {
            // Brief drain so the actor's writes don't stall on a full
            // socket buffer (the Query packet is small enough that
            // this never blocks in practice, but a real read keeps
            // the symmetry obvious).
            let _drained = drain_client_bytes(&mut server).await;
            server
                .write_var_uint(ServerPacketId::EndOfStream as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        let result = handle
            .execute_query("q1".into(), "SELECT 1".into(), Vec::new(), Vec::new())
            .await;
        assert!(result.is_ok(), "execute_query should succeed: {result:?}");
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn execute_query_surfaces_server_exception() {
        let (handle, mut server) = paired().await;

        // Server side: drain client bytes, then write a query Exception
        // and NOTHING after it. A real server does not send EndOfStream
        // after a query Exception (it is terminal), so the actor must
        // surface the error promptly WITHOUT draining. If it drained, it
        // would block until DRAIN_TIMEOUT and then poison the
        // connection -- which the is_alive assertion below would catch.
        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            server
                .write_var_uint(ServerPacketId::Exception as u64)
                .await
                .unwrap();
            server.write_i32_le(60i32).await.unwrap();
            server
                .write_string("DB::Exception".as_bytes())
                .await
                .unwrap();
            server
                .write_string("table not found".as_bytes())
                .await
                .unwrap();
            server.write_string("".as_bytes()).await.unwrap();
            tokio::io::AsyncWriteExt::write_u8(&mut server, 0u8)
                .await
                .unwrap(); // obsolete has_nested byte
            server.flush().await.unwrap();
            server
        });

        let err = handle
            .execute_query(
                "q2".into(),
                "SELECT * FROM nope".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect_err("expected server Exception to surface");
        match err {
            Error::ServerException { code, .. } => assert_eq!(code, 60),
            other => panic!("expected ServerException, got {other:?}"),
        }
        // A query Exception is terminal and non-fatal: the connection
        // stays alive and reusable (NOT poisoned, NOT drained).
        assert!(
            handle.is_alive(),
            "connection should remain alive after a server Exception"
        );

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn execute_query_cancel_on_reply_drop() {
        let (handle, mut server) = paired().await;

        // Server side: drain the initial Query bytes, then sit quiet
        // -- no EndOfStream yet, so the actor stays in the drain loop.
        // Once the client drops the reply, the actor will send Cancel;
        // we read until we observe the Cancel varint (0x03), then
        // reply EndOfStream so the actor's bounded drain finishes.
        let server_task = tokio::spawn(async move {
            use tokio::io::AsyncReadExt;
            // Drain bytes until we have a fair chance of seeing the
            // Query+empty-block stream fully written.
            let mut initial = Vec::new();
            let mut chunk = [0u8; 4096];
            // Read with a small timeout per chunk so we eventually stop
            // and let the test issue the drop.
            loop {
                match tokio::time::timeout(Duration::from_millis(50), server.read(&mut chunk)).await
                {
                    Ok(Ok(0)) => break,
                    Ok(Ok(n)) => initial.extend_from_slice(&chunk[..n]),
                    _ => break,
                }
            }
            assert!(
                !initial.is_empty(),
                "server should have seen at least the Query packet"
            );

            // Now keep reading; we expect a Cancel byte (0x03) to
            // arrive after the test drops the future.
            let mut saw_cancel = false;
            let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
            while tokio::time::Instant::now() < deadline {
                let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                match tokio::time::timeout(remaining, server.read(&mut chunk)).await {
                    Ok(Ok(0)) => break,
                    Ok(Ok(n)) => {
                        if chunk[..n].contains(&(ClientPacketId::Cancel as u8)) {
                            saw_cancel = true;
                            break;
                        }
                    }
                    _ => break,
                }
            }
            assert!(saw_cancel, "server should have observed Cancel byte");

            // Reply EndOfStream so the actor's drain finishes within
            // the timeout, leaving the connection reusable.
            server
                .write_var_uint(ServerPacketId::EndOfStream as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        // Issue execute_query but drop the future quickly via a
        // timeout that resolves before the server sends EndOfStream.
        // `tokio::time::timeout` drops the inner future on expiry,
        // which drops the oneshot::Receiver -- the cancel path.
        let cancel_handle = handle.clone();
        let exec_fut = cancel_handle.execute_query(
            "qcancel".into(),
            "SELECT sleep(10)".into(),
            Vec::new(),
            Vec::new(),
        );
        // Brief timeout so the actor has time to flush the Query
        // packet to the server before we drop the future.
        let timeout_result = tokio::time::timeout(Duration::from_millis(150), exec_fut).await;
        assert!(
            timeout_result.is_err(),
            "execute_query should not have completed inside the timeout"
        );

        // Wait for the server-side task to observe the Cancel and send
        // EndOfStream.
        let mut server = server_task.await.unwrap();

        // The actor must still be alive (not poisoned) and the
        // connection still usable -- prove it by reusing the same
        // handle for a ping.
        assert!(
            handle.is_alive(),
            "handle should remain alive after a successful cancel-and-drain"
        );

        // Drive a ping over the same connection. The server-side task
        // now answers Pong; the actor must see it cleanly.
        let ping_server_task = tokio::spawn(async move {
            let id = read_byte(&mut server).await;
            assert_eq!(u64::from(id), ClientPacketId::Ping as u64);
            server
                .write_var_uint(ServerPacketId::Pong as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });
        handle
            .ping()
            .await
            .expect("connection should be reusable after cancel");
        let _server = ping_server_task.await.unwrap();
    }

    // -----------------------------------------------------------------
    // INSERT lifecycle (BeginInsert / SendInsertBlock / FinishInsert)
    // -----------------------------------------------------------------

    /// Write a single server Exception packet with the supplied code +
    /// message, and nothing after it. This is the realistic terminal
    /// shape: a real server sends NO EndOfStream after a query
    /// Exception, so the actor must surface the error without draining.
    async fn write_server_exception(server: &mut TcpStream, code: i32, message: &str) {
        server
            .write_var_uint(ServerPacketId::Exception as u64)
            .await
            .unwrap();
        server.write_i32_le(code).await.unwrap();
        server.write_string(b"DB::Exception").await.unwrap();
        server.write_string(message.as_bytes()).await.unwrap();
        server.write_string(b"").await.unwrap();
        AsyncWriteExt::write_u8(server, 0).await.unwrap(); // obsolete has_nested byte
        server.flush().await.unwrap();
    }

    #[tokio::test]
    async fn insert_state_machine_rejects_ping_when_busy() {
        let (handle, mut server) = paired().await;

        // Server side: drain the BeginInsert Query bytes, send the
        // schema block, then hold the connection open so the actor
        // sits in InsertActive while we issue the ping.
        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            // Hold the connection -- keep the server side alive so the
            // ping rejection is observed before the actor sees EOF.
            tokio::time::sleep(Duration::from_millis(200)).await;
            server
        });

        // Drive BeginInsert; the call returns once the schema block
        // arrives.
        let headers = handle
            .begin_insert(
                "q_busy".into(),
                "INSERT INTO t FORMAT Native".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("begin_insert should succeed against scripted server");
        assert_eq!(headers, vec![("n".to_string(), "UInt64".to_string())]);

        // Ping while busy -- must reject without exiting InsertActive.
        let err = handle
            .ping()
            .await
            .expect_err("ping during InsertActive must error");
        match err {
            Error::Custom(msg) => assert!(
                msg.contains("busy"),
                "expected 'busy' in ping error, got {msg}"
            ),
            other => panic!("expected Custom busy error, got {other:?}"),
        }
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn send_insert_block_without_begin_errs() {
        let (handle, _server) = paired().await;

        let err = handle
            .send_insert_block(Vec::new(), 0, 0)
            .await
            .expect_err("send_insert_block in Idle must error");
        match err {
            Error::Custom(msg) => assert!(
                msg.contains("no INSERT session"),
                "expected 'no INSERT session' in error, got {msg}"
            ),
            other => panic!("expected Custom error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn finish_insert_returns_to_idle() {
        let (handle, mut server) = paired().await;

        // Server side: drain BeginInsert bytes, send schema block.
        // Then drain SendInsertBlock + FinishInsert bytes, send
        // EndOfStream so do_finish_insert returns Ok. Finally
        // answer the post-finish Ping with Pong.
        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            // Drain SendInsertBlock + FinishInsert (just bytes; we
            // do not parse them here).
            let _block_bytes = drain_client_bytes(&mut server).await;
            server
                .write_var_uint(ServerPacketId::EndOfStream as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            // Now serve the Ping that follows: read the Ping varint
            // and reply Pong.
            let id = read_byte(&mut server).await;
            assert_eq!(u64::from(id), ClientPacketId::Ping as u64);
            server
                .write_var_uint(ServerPacketId::Pong as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        let headers = handle
            .begin_insert(
                "q_finish".into(),
                "INSERT INTO t FORMAT Native".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("begin_insert should succeed");
        assert_eq!(headers.len(), 1);

        // Send one (empty) block -- the actor is a transport here,
        // it does not validate the payload.
        handle
            .send_insert_block(Vec::new(), 1, 0)
            .await
            .expect("send_insert_block should succeed");

        handle
            .finish_insert()
            .await
            .expect("finish_insert should return Ok on EndOfStream");

        // Prove the actor returned to Idle: a Ping must now succeed.
        handle
            .ping()
            .await
            .expect("connection should be reusable after finish_insert");
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn full_duplex_exception_aborts_send() {
        let (handle, mut server) = paired().await;

        // Server side: drain BeginInsert bytes, send schema block, then
        // push a single Exception (no EndOfStream after it -- the
        // realistic terminal shape) simulating a constraint violation
        // surfaced before the client's second SendInsertBlock.
        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            // Push an Exception "between blocks" -- give the actor a
            // moment to handle the schema block first.
            tokio::time::sleep(Duration::from_millis(20)).await;
            write_server_exception(&mut server, 241, "MEMORY_LIMIT_EXCEEDED").await;
            server
        });

        handle
            .begin_insert(
                "q_fd".into(),
                "INSERT INTO t FORMAT Native".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("begin_insert should succeed");

        // Wait long enough for the Exception to land in the reader's
        // mpsc queue, then call send_insert_block -- the try_recv
        // drain must see the Exception and abort before writing.
        tokio::time::sleep(Duration::from_millis(100)).await;
        let err = handle
            .send_insert_block(Vec::new(), 1, 0)
            .await
            .expect_err("send_insert_block must surface the queued Exception");
        match err {
            Error::ServerException { code, .. } => assert_eq!(code, 241),
            other => panic!("expected ServerException(241), got {other:?}"),
        }

        // Actor should be Idle again; connection still usable for
        // non-INSERT commands.
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }

    // -----------------------------------------------------------------
    // ExecuteStream (streaming SELECT)
    // -----------------------------------------------------------------

    #[tokio::test]
    async fn execute_stream_yields_schema_then_payload_then_eos() {
        let (handle, mut server) = paired().await;

        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            // Schema block (num_rows = 0) then a payload with three
            // values then EndOfStream.
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            write_uint64_payload_block(&mut server, &[10, 20, 30]).await;
            server
                .write_var_uint(ServerPacketId::EndOfStream as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        let mut cursor = handle
            .execute_stream_cursor(
                "rs_stream_unit".into(),
                "SELECT number AS n FROM numbers(3)".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("execute_stream_cursor should succeed");

        // First block: schema (num_rows = 0, schema vec non-empty).
        let schema_block = cursor
            .next_block()
            .await
            .expect("schema block decode")
            .expect("schema block");
        assert_eq!(schema_block.num_rows, 0);
        assert_eq!(
            schema_block.schema,
            vec![("n".to_string(), "UInt64".to_string())]
        );

        // Second block: payload (num_rows = 3, UInt64 column).
        let payload = cursor
            .next_block()
            .await
            .expect("payload decode")
            .expect("payload block");
        assert_eq!(payload.num_rows, 3);
        match &payload.columns[0] {
            crate::native::DecodedColumn::UInt64(values) => {
                assert_eq!(values, &vec![10u64, 20, 30]);
            }
            other => panic!("expected UInt64, got {other:?}"),
        }

        // Terminal EndOfStream surfaces as Ok(None); cursor remains
        // safe to poll past completion.
        assert!(cursor.next_block().await.unwrap().is_none());
        assert!(cursor.next_block().await.unwrap().is_none());
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn execute_stream_surfaces_server_exception() {
        let (handle, mut server) = paired().await;

        // Server side: drain Query bytes, then a single Exception (no
        // EndOfStream after it -- the realistic terminal shape).
        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            // Need not send a schema block first -- the server can
            // reject the query before any data flows.
            write_server_exception(&mut server, 60, "table not found").await;
            server
        });

        let mut cursor = handle
            .execute_stream_cursor(
                "rs_stream_err".into(),
                "SELECT * FROM doesnt_exist".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("execute_stream_cursor should succeed");

        let err = cursor
            .next_block()
            .await
            .expect_err("server Exception must surface");
        match err {
            Error::ServerException { code, .. } => assert_eq!(code, 60),
            other => panic!("expected ServerException, got {other:?}"),
        }
        // Subsequent polls return Ok(None) -- cursor is terminal after
        // surfacing the error.
        assert!(cursor.next_block().await.unwrap().is_none());

        // Connection still usable after a server-side rejection.
        assert!(handle.is_alive());
        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn execute_query_read_timeout_poisons() {
        // Server drains the Query bytes then goes silent -- it never
        // sends EndOfStream. With a short read_timeout the actor must
        // surface a retriable TimedOut (not hang) and poison the
        // connection so the pool drops it.
        let (handle, mut server) = paired_with_config(ActorConfig {
            read_timeout: Some(Duration::from_millis(80)),
            ..ActorConfig::default()
        })
        .await;

        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            // Hold the socket open but stay silent -- a stalled backend.
            tokio::time::sleep(Duration::from_millis(500)).await;
            server
        });

        let err = handle
            .execute_query(
                "rq_timeout".into(),
                "SELECT sleep(9)".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect_err("a silent server must surface TimedOut, not hang");
        assert!(matches!(err, Error::TimedOut), "got {err:?}");
        assert!(err.is_retriable(), "TimedOut must be retriable");
        assert!(!handle.is_alive(), "timed-out connection must be poisoned");

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn execute_stream_read_timeout_poisons() {
        // Server sends the schema block then stalls before any payload.
        // The cursor's first post-schema poll must surface TimedOut and
        // poison the connection -- not block until the caller gives up.
        let (handle, mut server) = paired_with_config(ActorConfig {
            read_timeout: Some(Duration::from_millis(80)),
            ..ActorConfig::default()
        })
        .await;

        let server_task = tokio::spawn(async move {
            // Send the schema block immediately (do NOT drain first --
            // drain_client_bytes runs a 200ms budget, which would delay
            // the schema past the 80ms read_timeout). The client's small
            // Query packet stays buffered in the kernel; the actor's send
            // does not stall. After the schema, go silent so the next
            // per-packet idle window elapses.
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            tokio::time::sleep(Duration::from_millis(500)).await;
            server
        });

        let mut cursor = handle
            .execute_stream_cursor(
                "rs_timeout".into(),
                "SELECT number AS n FROM numbers(9)".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("execute_stream_cursor should succeed");

        // Schema block arrives first.
        let schema = cursor.next_block().await.unwrap().expect("schema block");
        assert_eq!(schema.num_rows, 0);

        // Next poll waits on a silent server -> TimedOut, not a hang.
        let err = cursor
            .next_block()
            .await
            .expect_err("silent server mid-stream must surface TimedOut");
        assert!(matches!(err, Error::TimedOut), "got {err:?}");
        assert!(!handle.is_alive(), "timed-out connection must be poisoned");

        let _server = server_task.await.unwrap();
    }

    #[tokio::test]
    async fn execute_stream_aligns_rows_across_multiple_blocks() {
        // Two payload blocks of different widths back-to-back then EOS.
        // The cursor must yield each block's rows in order, with no
        // cross-boundary misalignment.
        let (handle, mut server) = paired().await;

        let server_task = tokio::spawn(async move {
            let _drained = drain_client_bytes(&mut server).await;
            write_schema_block(&mut server, &[("n", "UInt64")]).await;
            write_uint64_payload_block(&mut server, &[10, 20, 30]).await;
            write_uint64_payload_block(&mut server, &[40, 50]).await;
            server
                .write_var_uint(ServerPacketId::EndOfStream as u64)
                .await
                .unwrap();
            server.flush().await.unwrap();
            server
        });

        let mut cursor = handle
            .execute_stream_cursor(
                "rs_multiblock".into(),
                "SELECT number AS n FROM numbers(5)".into(),
                Vec::new(),
                Vec::new(),
            )
            .await
            .expect("execute_stream_cursor should succeed");

        // Schema, then block 1 (3 rows), then block 2 (2 rows), then EOS.
        let schema = cursor.next_block().await.unwrap().expect("schema block");
        assert_eq!(schema.num_rows, 0);

        let b1 = cursor.next_block().await.unwrap().expect("first payload");
        assert_eq!(b1.num_rows, 3);
        match &b1.columns[0] {
            crate::native::DecodedColumn::UInt64(v) => assert_eq!(v, &vec![10u64, 20, 30]),
            other => panic!("expected UInt64, got {other:?}"),
        }

        let b2 = cursor.next_block().await.unwrap().expect("second payload");
        assert_eq!(b2.num_rows, 2);
        match &b2.columns[0] {
            crate::native::DecodedColumn::UInt64(v) => assert_eq!(v, &vec![40u64, 50]),
            other => panic!("expected UInt64, got {other:?}"),
        }

        assert!(cursor.next_block().await.unwrap().is_none());
        assert!(handle.is_alive());

        let _server = server_task.await.unwrap();
    }
}