franken-snowflake-http 0.0.4

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

use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::time::Duration;

use asupersync::http::Response;
use asupersync::http::compress::{Decompressor, GzipDecompressor, IdentityDecompressor};
use asupersync::http::{
    Client as AsupersyncHttpClient, ClientError as AsupersyncClientError, Method, StatusCode,
};
use asupersync::{CancelKind, Cx, Time};
use franken_snowflake_core::budget::Budget;
use franken_snowflake_core::cancel::{CancelPolicy, CancelReason, cancel_policy};
use franken_snowflake_core::ids::{RequestId, StatementHandle};
use franken_snowflake_core::redact::{REDACTION_PLACEHOLDER, redact};
use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};

/// Crate version string.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

const SQL_API_STATEMENTS_PATH: &str = "/api/v2/statements";
const HEADER_AUTHORIZATION: &str = "Authorization";
const HEADER_TOKEN_TYPE: &str = "X-Snowflake-Authorization-Token-Type";
const HEADER_CONTENT_TYPE: &str = "Content-Type";
const HEADER_ACCEPT: &str = "Accept";
const HEADER_ACCEPT_ENCODING: &str = "Accept-Encoding";
const HEADER_CONTENT_ENCODING: &str = "Content-Encoding";
const JSON_MEDIA_TYPE: &str = "application/json";
const PARTITION_ACCEPT_ENCODING: &str = "gzip, identity";
const SNOWFLAKE_HOST_SUFFIX: &str = ".snowflakecomputing.com";
/// Official Snowflake SQL API resubmit contract consulted 2026-06-25.
pub const SNOWFLAKE_SQL_API_RESUBMIT_DOC_URL: &str = "https://docs.snowflake.com/en/developer-guide/sql-api/submitting-requests#resubmitting-a-request-to-execute-sql-statements";
/// Date the Snowflake SQL API resubmit contract above was consulted.
pub const SNOWFLAKE_SQL_API_RESUBMIT_DOC_CONSULTED: &str = "2026-06-25";

/// Transport APIs preserve the connector's in-process outcome carrier.
pub type TransportOutcome<T> = franken_snowflake_core::outcome::SnowflakeOutcome<T>;

/// Asupersync capability marker for this crate's effectful transport boundary.
///
/// Public APIs accept `&Cx` directly for now because the upstream capability
/// aliases are still settling, but this marker documents the intended authority:
/// IO + TIME + SPAWN, never REMOTE.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TransportCaps;

/// Asupersync-native Snowflake SQL API HTTP client facade.
#[derive(Clone)]
pub struct SnowflakeHttpClient<H = AsupersyncHttpClient> {
    config: TransportConfig,
    client: H,
}

/// The one network call the transport makes: a single HTTP exchange.
///
/// The Asupersync pooled client is the production implementation. Tests
/// inject a scripted transport so that `execute`'s retry, backoff,
/// idempotent-resubmit, and cancellation paths are provable without a socket
/// or an account.
pub trait RawHttp {
    /// Send one request; `timeout` is the remaining attempt budget when bounded.
    fn send(
        &self,
        cx: &Cx,
        method: Method,
        url: String,
        headers: Vec<(String, String)>,
        body: Vec<u8>,
        timeout: Option<Duration>,
    ) -> impl Future<Output = Result<Response, AsupersyncClientError>>;
}

impl RawHttp for AsupersyncHttpClient {
    async fn send(
        &self,
        cx: &Cx,
        method: Method,
        url: String,
        headers: Vec<(String, String)>,
        body: Vec<u8>,
        timeout: Option<Duration>,
    ) -> Result<Response, AsupersyncClientError> {
        let mut builder = self
            .request_builder(method, url)
            .headers(
                headers
                    .iter()
                    .map(|(name, value)| (name.as_str(), value.as_str())),
            )
            .body(body);
        if let Some(timeout) = timeout {
            builder = builder.timeout(timeout);
        }
        builder.send(cx).await
    }
}

impl<H> fmt::Debug for SnowflakeHttpClient<H> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SnowflakeHttpClient")
            .field("config", &self.config)
            .field("client", &"<asupersync-http-client>")
            .finish()
    }
}

impl SnowflakeHttpClient {
    /// Create a client from the runtime-owned pooled Asupersync HTTP client.
    #[must_use]
    pub fn default_for_runtime(config: TransportConfig, cx: &Cx) -> Self {
        Self {
            config,
            client: AsupersyncHttpClient::default_for_runtime(cx),
        }
    }
}

impl<H: RawHttp> SnowflakeHttpClient<H> {
    /// Build a client from an explicit configuration and raw HTTP transport
    /// (the Asupersync client in production, a scripted transport in tests).
    #[must_use]
    pub fn new(config: TransportConfig, client: H) -> Self {
        Self { config, client }
    }

    /// Access the immutable transport configuration.
    #[must_use]
    pub const fn config(&self) -> &TransportConfig {
        &self.config
    }

    /// Build a submit request plan without performing network I/O.
    pub fn submit_plan(&self, request: &SubmitHttpRequest) -> Result<WireRequest, TransportError> {
        self.wire_request(
            Method::Post,
            request.route.clone(),
            request.body.clone(),
            &request.auth,
            request.retry_resubmit,
        )
    }

    /// Build a poll request plan without performing network I/O.
    pub fn poll_plan(&self, request: &PollHttpRequest) -> Result<WireRequest, TransportError> {
        let route = TransportRoute::Poll {
            handle: request.statement_handle.clone(),
        };
        self.wire_request(Method::Get, route, Vec::new(), &request.auth, false)
    }

    /// Build a partition request plan without performing network I/O.
    pub fn partition_plan(
        &self,
        request: &PartitionHttpRequest,
    ) -> Result<WireRequest, TransportError> {
        let route = TransportRoute::Partition {
            handle: request.statement_handle.clone(),
            partition: request.partition,
        };
        self.wire_request(Method::Get, route, Vec::new(), &request.auth, false)
    }

    /// Build a cancel request plan without performing network I/O.
    pub fn cancel_plan(&self, request: &CancelHttpRequest) -> Result<WireRequest, TransportError> {
        let route = TransportRoute::Cancel {
            handle: request.statement_handle.clone(),
        };
        self.wire_request(Method::Post, route, Vec::new(), &request.auth, false)
    }

    /// Submit a SQL API statement over the live Asupersync HTTPS transport.
    pub async fn submit_statement(
        &self,
        cx: &Cx,
        request: SubmitHttpRequest,
    ) -> TransportOutcome<SubmitHttpResponse> {
        self.execute(cx, request, TransportRouteKind::Submit).await
    }

    /// Poll a submitted statement handle.
    pub async fn poll_statement(
        &self,
        cx: &Cx,
        request: PollHttpRequest,
    ) -> TransportOutcome<PollHttpResponse> {
        self.execute(cx, request, TransportRouteKind::Poll).await
    }

    /// Fetch and decode a result partition.
    pub async fn fetch_partition(
        &self,
        cx: &Cx,
        request: PartitionHttpRequest,
    ) -> TransportOutcome<PartitionBody> {
        self.execute(cx, request, TransportRouteKind::Partition)
            .await
    }

    /// Cancel a statement handle.
    pub async fn cancel_statement(
        &self,
        cx: &Cx,
        request: CancelHttpRequest,
    ) -> TransportOutcome<CancelHttpResponse> {
        self.execute(cx, request, TransportRouteKind::Cancel).await
    }

    /// Send a remote cancel during a bounded cleanup phase after local
    /// cancellation. The caller owns the cleanup `Cx`; this function deliberately
    /// does not manufacture a detached context inside the transport layer.
    ///
    /// Every policy except quiet drain attempts the remote cancel
    /// (`docs/transport_design.md`): a deadline/poll-quota/cost-budget
    /// cancellation used to skip it, which orphaned the statement server-side
    /// until `STATEMENT_TIMEOUT` even though the local caller had given up.
    pub async fn cancel_after_local_cancel(
        &self,
        cleanup_cx: &Cx,
        auth: AuthorizationDescriptor,
        statement_handle: StatementHandle,
        reason: CancelReason,
    ) -> TransportOutcome<CancelHttpResponse> {
        let policy = cancel_policy(reason.kind);
        if !franken_snowflake_core::cancel::attempts_remote_cancel(policy) {
            return TransportOutcome::cancelled(reason);
        }
        debug_assert!(matches!(
            policy,
            CancelPolicy::RemoteCancelAndReceipt
                | CancelPolicy::BoundedDrain
                | CancelPolicy::RetryOrDegrade
        ));
        run_with_cancellation_mask(
            cleanup_cx,
            self.cancel_statement(
                cleanup_cx,
                CancelHttpRequest {
                    auth,
                    statement_handle,
                    reason_kind: reason.kind,
                },
            ),
        )
        .await
    }

    /// Best-effort remote cancel of a statement the driver is abandoning because
    /// of a local error (transport failure, undecodable response) after the
    /// handle was issued. Runs under the cancellation mask so the cleanup request
    /// completes even if the ambient context is already cancelled.
    pub async fn cancel_orphaned_statement(
        &self,
        cleanup_cx: &Cx,
        auth: AuthorizationDescriptor,
        statement_handle: StatementHandle,
    ) -> TransportOutcome<CancelHttpResponse> {
        run_with_cancellation_mask(
            cleanup_cx,
            self.cancel_statement(
                cleanup_cx,
                CancelHttpRequest {
                    auth,
                    statement_handle,
                    reason_kind: CancelKind::FailFast,
                },
            ),
        )
        .await
    }

    /// Fetch partitions in order and stream them into the caller's sink.
    pub async fn stream_partitions<S>(
        &self,
        cx: &Cx,
        request: PartitionStreamRequest,
        sink: &mut S,
    ) -> TransportOutcome<PartitionStreamSummary>
    where
        S: PartitionSink,
    {
        if cx.checkpoint().is_err() {
            return TransportOutcome::cancelled(cancel_reason_or(
                cx,
                CancelReason::parent_cancelled,
            ));
        }
        let summary = match request.plan() {
            Ok(summary) => summary,
            Err(error) => return TransportOutcome::err(error.into_snowflake_error()),
        };
        for partition in request.seed_partitions.iter().cloned() {
            if cx.checkpoint().is_err() {
                let reason = cancel_reason_or(cx, CancelReason::parent_cancelled);
                return self
                    .cancel_stream_after_local_cancel(cx, &request, &summary, reason)
                    .await;
            }
            if let Err(error) = sink.accept(cx, partition).await {
                return TransportOutcome::err(error.into_snowflake_error());
            }
            if cx.checkpoint().is_err() {
                let reason = cancel_reason_or(cx, CancelReason::parent_cancelled);
                return self
                    .cancel_stream_after_local_cancel(cx, &request, &summary, reason)
                    .await;
            }
        }

        for partition in request.first_partition..request.end_partition_exclusive {
            if cx.checkpoint().is_err() {
                let reason = cancel_reason_or(cx, CancelReason::parent_cancelled);
                return self
                    .cancel_stream_after_local_cancel(cx, &request, &summary, reason)
                    .await;
            }
            let body: PartitionBody = match self
                .execute(
                    cx,
                    PlannedTransportRequest::partition(
                        request.auth.clone(),
                        request.statement_handle.clone(),
                        partition,
                        request.child_budget,
                    ),
                    TransportRouteKind::Partition,
                )
                .await
            {
                TransportOutcome::Ok(body) => body,
                TransportOutcome::Err(error) => return TransportOutcome::err(error),
                TransportOutcome::Cancelled(reason) => return TransportOutcome::cancelled(reason),
                TransportOutcome::Panicked(payload) => return TransportOutcome::panicked(payload),
            };
            let decoded = DecodedPartition {
                partition,
                body: body.body,
                compression: body.compression,
            };
            if let Err(error) = sink.accept(cx, decoded).await {
                return TransportOutcome::err(error.into_snowflake_error());
            }
            if cx.checkpoint().is_err() {
                let reason = cancel_reason_or(cx, CancelReason::parent_cancelled);
                return self
                    .cancel_stream_after_local_cancel(cx, &request, &summary, reason)
                    .await;
            }
        }

        TransportOutcome::ok(summary)
    }

    async fn cancel_stream_after_local_cancel(
        &self,
        cx: &Cx,
        request: &PartitionStreamRequest,
        _summary: &PartitionStreamSummary,
        reason: CancelReason,
    ) -> TransportOutcome<PartitionStreamSummary> {
        if request.remote_cancel_on_local_cancel {
            let cleanup = self
                .cancel_after_local_cancel(
                    cx,
                    request.auth.clone(),
                    request.statement_handle.clone(),
                    reason.clone(),
                )
                .await;
            stream_cancel_cleanup_outcome(cleanup, reason)
        } else {
            TransportOutcome::cancelled(reason)
        }
    }
}

fn stream_cancel_cleanup_outcome<T>(
    cleanup: TransportOutcome<T>,
    reason: CancelReason,
) -> TransportOutcome<PartitionStreamSummary> {
    match cleanup {
        TransportOutcome::Panicked(payload) => TransportOutcome::panicked(payload),
        TransportOutcome::Ok(_) | TransportOutcome::Err(_) | TransportOutcome::Cancelled(_) => {
            TransportOutcome::cancelled(reason)
        }
    }
}

impl<H: RawHttp> SnowflakeHttpClient<H> {
    async fn execute<R, T>(
        &self,
        cx: &Cx,
        request: R,
        route_kind: TransportRouteKind,
    ) -> TransportOutcome<T>
    where
        R: Into<PlannedTransportRequest>,
        T: FromResponseBody,
    {
        let mut retry_spent_ms = 0_u64;
        let planned = request.into();
        let wire = match self.wire_request(
            route_kind.method(),
            planned.route.clone(),
            planned.body.clone(),
            &planned.auth,
            planned.retry_resubmit,
        ) {
            Ok(wire) => wire,
            Err(error) => return TransportOutcome::err(error.into_snowflake_error()),
        };

        let mut attempt = 1_u32;
        loop {
            if cx.checkpoint().is_err() {
                return TransportOutcome::cancelled(cancel_reason_or(
                    cx,
                    CancelReason::parent_cancelled,
                ));
            }

            let attempt_budget =
                self.config
                    .retry
                    .attempt_budget(cx.budget(), planned.budget, attempt);
            let budget_now = asupersync::time::wall_now();
            if let Some(reason) = budget_exhaustion_reason_at(attempt_budget, budget_now) {
                return TransportOutcome::cancelled(reason);
            }
            let result = self
                .client
                .send(
                    cx,
                    route_kind.method(),
                    wire.url.clone(),
                    wire.headers
                        .iter()
                        .map(|h| (h.name.clone(), h.value.clone()))
                        .collect(),
                    wire.body.clone(),
                    budget_timeout_at(attempt_budget, budget_now),
                )
                .await;

            match result {
                Ok(response) => {
                    let retry_after_ms = retry_after_ms(response.headers.as_slice());
                    let retryable = is_retryable_status(response.status);
                    if retryable {
                        if !route_allows_automatic_retry(&wire.route) {
                            return TransportOutcome::err(
                                TransportError::new(
                                    TransportErrorCode::NonIdempotentSubmitRetryRefused,
                                    format!(
                                        "{} returned retryable HTTP status {}, but automatic retry requires requestId plus retry=true",
                                        route_kind.as_str(),
                                        response.status
                                    ),
                                )
                                .into_snowflake_error(),
                            );
                        }
                        if let Some(retry) = self.config.retry.next_retry(
                            planned.request_id.as_ref(),
                            route_kind,
                            attempt,
                            retry_after_ms,
                            retry_spent_ms,
                        ) {
                            if let Err(reason) = wait_retry_delay(cx, retry.delay).await {
                                return TransportOutcome::cancelled(reason);
                            }
                            attempt = attempt.saturating_add(1);
                            retry_spent_ms = retry.spent_after_ms;
                            continue;
                        }
                        return TransportOutcome::err(
                            TransportError::new(
                                TransportErrorCode::RetryBudgetExhausted,
                                format!(
                                    "{} exhausted retry budget after {attempt} attempts",
                                    route_kind.as_str()
                                ),
                            )
                            .into_snowflake_error(),
                        );
                    }
                    return match T::from_response(response, self.config.limits, planned.partition) {
                        Ok(value) => TransportOutcome::ok(value),
                        Err(error) => TransportOutcome::err(error.into_snowflake_error()),
                    };
                }
                Err(error) if error.is_cancelled() => {
                    return TransportOutcome::cancelled(cancel_reason_or(
                        cx,
                        CancelReason::parent_cancelled,
                    ));
                }
                Err(AsupersyncClientError::DeadlineExceeded) => {
                    return TransportOutcome::cancelled(cancel_reason_or(
                        cx,
                        CancelReason::deadline,
                    ));
                }
                Err(error) => {
                    if route_allows_automatic_retry(&wire.route)
                        && let Some(retry) = self.config.retry.next_retry(
                            planned.request_id.as_ref(),
                            route_kind,
                            attempt,
                            None,
                            retry_spent_ms,
                        )
                    {
                        if let Err(reason) = wait_retry_delay(cx, retry.delay).await {
                            return TransportOutcome::cancelled(reason);
                        }
                        attempt = attempt.saturating_add(1);
                        retry_spent_ms = retry.spent_after_ms;
                        continue;
                    }
                    return TransportOutcome::err(
                        TransportError::new(
                            TransportErrorCode::NetworkError,
                            format!("Asupersync HTTP client error: {error}"),
                        )
                        .into_snowflake_error(),
                    );
                }
            }
        }
    }

    fn wire_request(
        &self,
        method: Method,
        route: TransportRoute,
        body: Vec<u8>,
        auth: &AuthorizationDescriptor,
        retry_resubmit: bool,
    ) -> Result<WireRequest, TransportError> {
        let route_kind = route.kind();
        self.config.limits.enforce(route_kind, body.len())?;
        if matches!(route_kind, TransportRouteKind::Submit)
            && retry_resubmit
            && !route.has_retry_contract()
        {
            return Err(TransportError::new(
                TransportErrorCode::NonIdempotentSubmitRetryRefused,
                "submit retry requires requestId plus retry=true",
            ));
        }

        let mut headers = auth.wire_headers()?;
        headers.push(Header::new(HEADER_ACCEPT, JSON_MEDIA_TYPE)?);
        if matches!(route_kind, TransportRouteKind::Partition) {
            headers.push(Header::new(
                HEADER_ACCEPT_ENCODING,
                PARTITION_ACCEPT_ENCODING,
            )?);
        }
        if matches!(method, Method::Post) {
            headers.push(Header::new(HEADER_CONTENT_TYPE, JSON_MEDIA_TYPE)?);
        }
        Ok(WireRequest {
            method,
            url: self.config.endpoint.route_url(&route),
            route,
            headers,
            body,
        })
    }
}

/// Immutable transport configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransportConfig {
    /// Canonical Snowflake SQL API endpoint.
    pub endpoint: SnowflakeEndpoint,
    /// TLS root policy.
    pub tls_roots: TlsRootPolicy,
    /// Connection-pool constraints.
    pub pool: PoolConfig,
    /// Body-size limits.
    pub limits: BodyLimits,
    /// Retry/backoff behavior.
    pub retry: RetryPolicy,
    /// Attempt-log behavior.
    pub log: AttemptLogPolicy,
}

impl TransportConfig {
    /// Create a config with conservative defaults.
    #[must_use]
    pub fn new(endpoint: SnowflakeEndpoint) -> Self {
        Self {
            endpoint,
            tls_roots: TlsRootPolicy::NativeRoots,
            pool: PoolConfig::default(),
            limits: BodyLimits::default(),
            retry: RetryPolicy::default(),
            log: AttemptLogPolicy::default(),
        }
    }
}

/// Validated HTTPS endpoint for a Snowflake account host.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SnowflakeEndpoint {
    base_url: String,
    host: String,
}

impl SnowflakeEndpoint {
    /// Validate and canonicalize a Snowflake SQL API base endpoint.
    pub fn parse(raw: impl AsRef<str>) -> Result<Self, TransportError> {
        let raw = raw.as_ref().trim();
        if raw.is_empty() {
            return Err(TransportError::new(
                TransportErrorCode::InvalidSnowflakeHost,
                "Snowflake endpoint is empty",
            ));
        }
        let Some(rest) = raw.strip_prefix("https://") else {
            return Err(TransportError::new(
                TransportErrorCode::InvalidSnowflakeHost,
                "Snowflake endpoint must use https://",
            ));
        };
        if rest.contains('@') || raw.contains('#') || raw.contains('?') {
            return Err(TransportError::new(
                TransportErrorCode::InvalidSnowflakeHost,
                "Snowflake endpoint must not contain credentials, fragments, or query strings",
            ));
        }
        let trimmed = rest.trim_end_matches('/');
        if trimmed.contains('/') {
            return Err(TransportError::new(
                TransportErrorCode::InvalidSnowflakeHost,
                "Snowflake endpoint must not contain path segments",
            ));
        }
        let host = trimmed
            .split('/')
            .next()
            .filter(|candidate| !candidate.is_empty())
            .ok_or_else(|| {
                TransportError::new(
                    TransportErrorCode::InvalidSnowflakeHost,
                    "Snowflake endpoint host is missing",
                )
            })?;
        validate_host(host)?;
        let base_url = format!("https://{trimmed}");
        Ok(Self {
            base_url,
            host: host.to_owned(),
        })
    }

    /// Canonical base URL without a trailing slash.
    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Canonical host portion.
    #[must_use]
    pub fn host(&self) -> &str {
        &self.host
    }

    /// Build an absolute URL for a SQL API route.
    #[must_use]
    pub fn route_url(&self, route: &TransportRoute) -> String {
        format!("{}{}", self.base_url, route.path_and_query())
    }
}

fn validate_host(host: &str) -> Result<(), TransportError> {
    let valid = host
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'))
        && host.contains('.')
        && !host.starts_with('.')
        && !host.ends_with('.')
        && !host.contains("..")
        && host.ends_with(SNOWFLAKE_HOST_SUFFIX)
        && host.len() > SNOWFLAKE_HOST_SUFFIX.len();
    if valid {
        Ok(())
    } else {
        Err(TransportError::new(
            TransportErrorCode::InvalidSnowflakeHost,
            "Snowflake endpoint host is not canonical",
        ))
    }
}

/// TLS root source for live HTTPS.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum TlsRootPolicy {
    /// Use the OS trust store through Asupersync/rustls native roots.
    NativeRoots,
    /// Use a caller-provided PEM bundle.
    ExplicitPemBundle(PathBuf),
    /// Test-only marker. Refused unless a testkit path explicitly consumes it.
    TestOnlyInsecureDisabledByDefault,
}

/// Connection-pool policy. This mirrors the plan-level contract without exposing
/// unstable internals from Asupersync's pool.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PoolConfig {
    /// Maximum idle connections retained per endpoint.
    pub max_idle_per_endpoint: usize,
    /// Maximum in-flight requests per endpoint.
    pub max_in_flight_per_endpoint: usize,
}

impl Default for PoolConfig {
    fn default() -> Self {
        Self {
            max_idle_per_endpoint: 8,
            max_in_flight_per_endpoint: 16,
        }
    }
}

/// Response/request body limits enforced before decode.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BodyLimits {
    /// Maximum submit response bytes.
    pub max_submit_response_bytes: u64,
    /// Maximum poll response bytes.
    pub max_poll_response_bytes: u64,
    /// Maximum compressed partition bytes.
    pub max_partition_compressed_bytes: u64,
    /// Maximum uncompressed partition bytes.
    pub max_partition_uncompressed_bytes: u64,
    /// Maximum submit request body bytes.
    pub max_submit_request_bytes: u64,
}

impl BodyLimits {
    /// Enforce request body limits for a route.
    pub fn enforce(self, route: TransportRouteKind, body_len: usize) -> Result<(), TransportError> {
        let max = match route {
            TransportRouteKind::Submit => self.max_submit_request_bytes,
            TransportRouteKind::Poll
            | TransportRouteKind::Partition
            | TransportRouteKind::Cancel => u64::MAX,
        };
        if body_len as u64 > max {
            Err(TransportError::new(
                TransportErrorCode::BodyLimitExceeded,
                format!("request body has {body_len} bytes, limit is {max}"),
            ))
        } else {
            Ok(())
        }
    }

    /// Enforce partition compressed/uncompressed limits.
    pub fn enforce_partition_sizes(
        self,
        compressed: u64,
        uncompressed: u64,
    ) -> Result<(), TransportError> {
        if compressed > self.max_partition_compressed_bytes {
            return Err(TransportError::new(
                TransportErrorCode::BodyLimitExceeded,
                format!(
                    "compressed partition has {compressed} bytes, limit is {}",
                    self.max_partition_compressed_bytes
                ),
            ));
        }
        if uncompressed > self.max_partition_uncompressed_bytes {
            return Err(TransportError::new(
                TransportErrorCode::BodyLimitExceeded,
                format!(
                    "uncompressed partition has {uncompressed} bytes, limit is {}",
                    self.max_partition_uncompressed_bytes
                ),
            ));
        }
        Ok(())
    }

    /// Enforce non-partition response body limits.
    pub fn enforce_response_size(
        self,
        route: TransportRouteKind,
        body_len: usize,
    ) -> Result<(), TransportError> {
        let max = match route {
            TransportRouteKind::Submit => self.max_submit_response_bytes,
            TransportRouteKind::Poll => self.max_poll_response_bytes,
            TransportRouteKind::Cancel => self.max_poll_response_bytes,
            TransportRouteKind::Partition => self.max_partition_compressed_bytes,
        };
        if body_len as u64 > max {
            Err(TransportError::new(
                TransportErrorCode::BodyLimitExceeded,
                format!("response body has {body_len} bytes, limit is {max}"),
            ))
        } else {
            Ok(())
        }
    }
}

impl Default for BodyLimits {
    fn default() -> Self {
        Self {
            max_submit_response_bytes: 8 * 1024 * 1024,
            max_poll_response_bytes: 8 * 1024 * 1024,
            max_partition_compressed_bytes: 64 * 1024 * 1024,
            max_partition_uncompressed_bytes: 512 * 1024 * 1024,
            max_submit_request_bytes: 2 * 1024 * 1024,
        }
    }
}

/// Retry/backoff policy for transport calls.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RetryPolicy {
    /// Maximum number of attempts including the first try.
    pub max_attempts: u32,
    /// Base exponential delay.
    pub base_delay_ms: u64,
    /// Maximum delay after exponentiation.
    pub max_delay_ms: u64,
    /// Total retry sleep budget.
    pub total_budget_ms: u64,
    /// Whether to honor `Retry-After` when present.
    pub respect_retry_after: bool,
    /// Whether deterministic jitter is applied.
    pub deterministic_jitter: bool,
}

impl RetryPolicy {
    /// Compute the next retry delay.
    #[must_use]
    pub fn delay_for(
        self,
        request_id: Option<&RequestId>,
        route: TransportRouteKind,
        attempt: u32,
        retry_after_ms: Option<u64>,
        spent_ms: u64,
    ) -> Option<Duration> {
        if attempt == 0 || attempt >= self.max_attempts || spent_ms >= self.total_budget_ms {
            return None;
        }
        let from_header = retry_after_ms.filter(|_| self.respect_retry_after);
        let exponential = self
            .base_delay_ms
            .saturating_mul(2_u64.saturating_pow(attempt.saturating_sub(1)))
            .min(self.max_delay_ms);
        let mut delay = from_header.unwrap_or(exponential);
        if from_header.is_none() && self.deterministic_jitter {
            delay = delay.saturating_add(deterministic_jitter_ms(request_id, route, attempt));
        }
        let remaining = self.total_budget_ms.saturating_sub(spent_ms);
        if delay > remaining {
            None
        } else {
            Some(Duration::from_millis(delay))
        }
    }

    fn next_retry(
        self,
        request_id: Option<&RequestId>,
        route: TransportRouteKind,
        attempt: u32,
        retry_after_ms: Option<u64>,
        spent_ms: u64,
    ) -> Option<RetryDecision> {
        let delay = self.delay_for(request_id, route, attempt, retry_after_ms, spent_ms)?;
        Some(RetryDecision {
            delay,
            spent_after_ms: spent_ms.saturating_add(duration_millis_saturating(delay)),
        })
    }

    /// Budget slice for one transport attempt, meet-composed with the caller's
    /// ambient budget and any route-specific child budget.
    #[must_use]
    pub fn attempt_budget(self, ambient: Budget, route_budget: Budget, attempt: u32) -> Budget {
        let remaining_attempts = self
            .max_attempts
            .saturating_sub(attempt.saturating_sub(1))
            .max(1);
        // `.with_priority(0)`: `meet`/`combine` takes the *max* priority, and a
        // bare `Budget::new()` defaults priority to 128. Without this, the
        // poll-quota constraint would silently raise every retry's scheduling
        // priority to 128, discarding the configured ambient/route priority.
        // Priority 0 is the identity element for the max-combine, so this budget
        // constrains poll-quota only.
        ambient.meet(route_budget).meet(
            Budget::new()
                .with_poll_quota(remaining_attempts)
                .with_priority(0),
        )
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct RetryDecision {
    delay: Duration,
    spent_after_ms: u64,
}

fn duration_millis_saturating(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

fn budget_timeout_at(budget: Budget, now: Time) -> Option<Duration> {
    budget
        .deadline
        .map(|deadline| Duration::from_nanos(deadline.duration_since(now)))
}

fn budget_exhaustion_reason_at(budget: Budget, now: Time) -> Option<CancelReason> {
    if budget_timeout_at(budget, now).is_some_and(|timeout| timeout.is_zero()) {
        return Some(CancelReason::deadline());
    }
    if budget.poll_quota == 0 {
        return Some(CancelReason::poll_quota());
    }
    if matches!(budget.cost_quota, Some(0)) {
        return Some(CancelReason::cost_budget());
    }
    None
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 4,
            base_delay_ms: 100,
            max_delay_ms: 2_000,
            total_budget_ms: 10_000,
            respect_retry_after: true,
            deterministic_jitter: true,
        }
    }
}

fn deterministic_jitter_ms(
    request_id: Option<&RequestId>,
    route: TransportRouteKind,
    attempt: u32,
) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    for byte in request_id
        .map_or("no-request-id", RequestId::as_str)
        .bytes()
        .chain(route.as_str().bytes())
        .chain(attempt.to_le_bytes())
    {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash % 31
}

/// Attempt-log controls.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct AttemptLogPolicy {
    /// Emit per-attempt events.
    pub enabled: bool,
    /// Hash statement handles in logs.
    pub hash_statement_handles: bool,
    /// Redact account/host identifiers.
    pub redact_account_identifiers: bool,
}

impl Default for AttemptLogPolicy {
    fn default() -> Self {
        Self {
            enabled: true,
            hash_statement_handles: true,
            redact_account_identifiers: true,
        }
    }
}

/// Snowflake auth token class for the SQL API token-type header.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SnowflakeAuthTokenType {
    /// Programmatic access token.
    ProgrammaticAccessToken,
    /// Key-pair JWT.
    KeypairJwt,
    /// OAuth bearer token.
    OAuth,
}

impl SnowflakeAuthTokenType {
    /// Wire value for `X-Snowflake-Authorization-Token-Type`.
    #[must_use]
    pub const fn as_header_value(self) -> &'static str {
        match self {
            Self::ProgrammaticAccessToken => "PROGRAMMATIC_ACCESS_TOKEN",
            Self::KeypairJwt => "KEYPAIR_JWT",
            Self::OAuth => "OAUTH",
        }
    }
}

/// Redacted authorization descriptor supplied by the auth crate.
#[derive(Clone, PartialEq, Eq)]
pub struct AuthorizationDescriptor {
    token_type: SnowflakeAuthTokenType,
    bearer_token: String,
    redacted_fingerprint: String,
}

impl AuthorizationDescriptor {
    /// Create a descriptor from an already-resolved bearer token.
    ///
    /// The token is intentionally not exposed through `Debug`, `Display`, or
    /// serde. The auth crate owns secret-source resolution.
    #[must_use]
    pub fn bearer(
        token_type: SnowflakeAuthTokenType,
        bearer_token: impl Into<String>,
        redacted_fingerprint: impl Into<String>,
    ) -> Self {
        Self {
            token_type,
            bearer_token: bearer_token.into(),
            redacted_fingerprint: redacted_fingerprint.into(),
        }
    }

    /// Redacted fingerprint for logs.
    #[must_use]
    pub fn redacted_fingerprint(&self) -> &str {
        &self.redacted_fingerprint
    }

    fn wire_headers(&self) -> Result<Vec<Header>, TransportError> {
        Ok(vec![
            Header::new(
                HEADER_AUTHORIZATION,
                format!("Bearer {}", self.bearer_token),
            )?,
            Header::new(HEADER_TOKEN_TYPE, self.token_type.as_header_value())?,
        ])
    }
}

impl fmt::Debug for AuthorizationDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AuthorizationDescriptor")
            .field("token_type", &self.token_type)
            .field("redacted_fingerprint", &self.redacted_fingerprint)
            .finish_non_exhaustive()
    }
}

/// HTTP header pair.
#[derive(Clone, PartialEq, Eq, Hash, Deserialize)]
pub struct Header {
    /// Header name.
    pub name: String,
    /// Header value.
    pub value: String,
}

impl fmt::Debug for Header {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Header")
            .field("name", &self.name)
            .field("value", &redacted_header_value(&self.name, &self.value))
            .finish()
    }
}

impl Serialize for Header {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Header", 2)?;
        state.serialize_field("name", &self.name)?;
        state.serialize_field("value", &redacted_header_value(&self.name, &self.value))?;
        state.end()
    }
}

impl Header {
    /// Validate and construct a header.
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Result<Self, TransportError> {
        let name = name.into();
        let value = value.into();
        if !is_header_name(&name) || !is_header_value(&value) {
            return Err(TransportError::new(
                TransportErrorCode::HeaderRejected,
                "header contains invalid characters",
            ));
        }
        Ok(Self { name, value })
    }
}

fn redacted_header_value(name: &str, value: &str) -> String {
    let value = redact(value).into_owned();
    if !name.eq_ignore_ascii_case(HEADER_AUTHORIZATION) {
        return value;
    }
    if value.contains(REDACTION_PLACEHOLDER) {
        return value;
    }
    let mut words = value.split_whitespace();
    match (words.next(), words.next()) {
        (Some(scheme), Some(_)) => format!("{scheme} {REDACTION_PLACEHOLDER}"),
        _ => REDACTION_PLACEHOLDER.to_owned(),
    }
}

fn is_header_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-'))
}

fn is_header_value(value: &str) -> bool {
    value.bytes().all(|b| matches!(b, b'\t' | b' '..=b'~'))
}

/// SQL API transport route.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum TransportRoute {
    /// `POST /api/v2/statements`.
    Submit,
    /// `POST /api/v2/statements?<query pairs>`.
    SubmitWithQuery {
        /// Stable, caller-rendered submit query parameters in wire order.
        query: Vec<(&'static str, String)>,
    },
    /// `POST /api/v2/statements?requestId=...&retry=true`.
    SubmitRetry {
        /// Stable idempotency request id.
        request_id: RequestId,
    },
    /// `GET /api/v2/statements/{statementHandle}`.
    Poll {
        /// Statement handle.
        handle: StatementHandle,
    },
    /// `GET /api/v2/statements/{statementHandle}?partition=<n>`.
    Partition {
        /// Statement handle.
        handle: StatementHandle,
        /// Partition number.
        partition: u32,
    },
    /// `POST /api/v2/statements/{statementHandle}/cancel`.
    Cancel {
        /// Statement handle.
        handle: StatementHandle,
    },
}

impl TransportRoute {
    /// Coarse route kind.
    #[must_use]
    pub const fn kind(&self) -> TransportRouteKind {
        match self {
            Self::Submit | Self::SubmitWithQuery { .. } | Self::SubmitRetry { .. } => {
                TransportRouteKind::Submit
            }
            Self::Poll { .. } => TransportRouteKind::Poll,
            Self::Partition { .. } => TransportRouteKind::Partition,
            Self::Cancel { .. } => TransportRouteKind::Cancel,
        }
    }

    /// Whether this submit has the Snowflake idempotent resubmit contract.
    #[must_use]
    pub fn has_retry_contract(&self) -> bool {
        match self {
            Self::SubmitRetry { .. } => true,
            Self::SubmitWithQuery { query } => submit_query_has_retry_contract(query),
            Self::Submit | Self::Poll { .. } | Self::Partition { .. } | Self::Cancel { .. } => {
                false
            }
        }
    }

    /// Path and query for the SQL API route.
    #[must_use]
    pub fn path_and_query(&self) -> String {
        match self {
            Self::Submit => SQL_API_STATEMENTS_PATH.to_owned(),
            Self::SubmitWithQuery { query } => render_submit_query(query),
            Self::SubmitRetry { request_id } => {
                format!(
                    "{SQL_API_STATEMENTS_PATH}?requestId={}&retry=true",
                    percent_encode_query_component(request_id.as_str())
                )
            }
            Self::Poll { handle } => {
                format!(
                    "{SQL_API_STATEMENTS_PATH}/{}",
                    percent_encode_path_segment(handle.as_str())
                )
            }
            Self::Partition { handle, partition } => {
                format!(
                    "{SQL_API_STATEMENTS_PATH}/{}?partition={partition}",
                    percent_encode_path_segment(handle.as_str())
                )
            }
            Self::Cancel { handle } => {
                format!(
                    "{SQL_API_STATEMENTS_PATH}/{}/cancel",
                    percent_encode_path_segment(handle.as_str())
                )
            }
        }
    }
}

fn render_submit_query(query: &[(&'static str, String)]) -> String {
    if query.is_empty() {
        return SQL_API_STATEMENTS_PATH.to_owned();
    }

    let mut rendered = String::from(SQL_API_STATEMENTS_PATH);
    for (index, (key, value)) in query.iter().enumerate() {
        rendered.push(if index == 0 { '?' } else { '&' });
        rendered.push_str(&percent_encode_query_component(key));
        rendered.push('=');
        rendered.push_str(&percent_encode_query_component(value));
    }
    rendered
}

fn percent_encode_query_component(value: &str) -> String {
    let mut encoded = String::new();
    for byte in value.bytes() {
        if is_query_unreserved(byte) {
            encoded.push(char::from(byte));
        } else {
            encoded.push('%');
            encoded.push(hex_digit(byte >> 4));
            encoded.push(hex_digit(byte & 0x0f));
        }
    }
    encoded
}

fn percent_encode_path_segment(value: &str) -> String {
    percent_encode_query_component(value)
}

const fn is_query_unreserved(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
}

const fn hex_digit(nibble: u8) -> char {
    match nibble {
        0..=9 => (b'0' + nibble) as char,
        _ => (b'A' + (nibble - 10)) as char,
    }
}

fn submit_query_has_retry_contract(query: &[(&'static str, String)]) -> bool {
    query
        .iter()
        .any(|(key, value)| *key == "requestId" && !value.is_empty())
        && query
            .iter()
            .any(|(key, value)| *key == "retry" && value == "true")
}

/// Coarse transport route kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransportRouteKind {
    /// Submit statement.
    Submit,
    /// Poll statement handle.
    Poll,
    /// Fetch result partition.
    Partition,
    /// Cancel statement handle.
    Cancel,
}

impl TransportRouteKind {
    /// Stable string for logs and jitter seeds.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Submit => "submit",
            Self::Poll => "poll",
            Self::Partition => "partition",
            Self::Cancel => "cancel",
        }
    }

    /// HTTP method for this route kind.
    #[must_use]
    pub const fn method(self) -> Method {
        match self {
            Self::Submit | Self::Cancel => Method::Post,
            Self::Poll | Self::Partition => Method::Get,
        }
    }
}

/// Fully planned wire request.
#[derive(Clone, PartialEq, Eq)]
pub struct WireRequest {
    /// HTTP method.
    pub method: Method,
    /// Absolute URL.
    pub url: String,
    /// SQL API route.
    pub route: TransportRoute,
    /// Wire headers.
    pub headers: Vec<Header>,
    /// Request body bytes.
    pub body: Vec<u8>,
}

impl fmt::Debug for WireRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WireRequest")
            .field("method", &self.method)
            .field("url", &self.url)
            .field("route", &self.route)
            .field("headers", &self.headers)
            .field("body_len", &self.body.len())
            .finish()
    }
}

/// Status classification for Snowflake SQL API responses.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StatusClass {
    /// 200 completed.
    Completed,
    /// 202 accepted/still running.
    Running,
    /// 408 server statement timeout.
    StatementTimeout,
    /// 422 SQL/query failure.
    QueryFailure,
    /// 429 rate limited.
    RateLimited,
    /// Retryable 5xx.
    ServerErrorRetryable,
    /// 401: the bearer token was rejected (expired JWT, revoked key, bad PAT).
    /// The driver may re-sign once for the key-pair JWT lane and retry.
    Unauthorized,
    /// Any other unexpected status.
    Unexpected,
}

/// Classify Snowflake SQL API status codes without conflating 202 and 429.
#[must_use]
pub fn classify_status(status: StatusCode) -> StatusClass {
    match status.as_u16() {
        200 => StatusClass::Completed,
        202 => StatusClass::Running,
        401 => StatusClass::Unauthorized,
        408 => StatusClass::StatementTimeout,
        422 => StatusClass::QueryFailure,
        429 => StatusClass::RateLimited,
        500..=599 => StatusClass::ServerErrorRetryable,
        _ => StatusClass::Unexpected,
    }
}

/// Attempt-log event target schema.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttemptLogEvent {
    /// Schema id.
    pub schema: &'static str,
    /// Redacted or generated trace id.
    pub trace_id: String,
    /// Route kind.
    pub route: TransportRouteKind,
    /// HTTP method.
    pub method: String,
    /// 1-based attempt number.
    pub attempt: u32,
    /// Redacted request fingerprint.
    pub request_fingerprint: String,
    /// Optional hashed statement handle.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub statement_handle_hash: Option<String>,
    /// Optional partition index.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partition: Option<u32>,
    /// HTTP status if a response was received.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,
    /// Whether the outcome is retryable.
    pub retryable: bool,
    /// Retry-After value in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_ms: Option<u64>,
    /// Elapsed milliseconds.
    pub elapsed_ms: u64,
    /// Compressed bytes observed.
    pub compressed_bytes: u64,
    /// Uncompressed bytes observed.
    pub uncompressed_bytes: u64,
    /// `ok`, `error`, or `cancelled`.
    pub outcome: AttemptOutcome,
    /// Stable transport error code if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<TransportErrorCode>,
}

impl AttemptLogEvent {
    /// Schema identifier.
    pub const SCHEMA: &'static str = "franken_snowflake.transport_attempt.v1";
}

/// Attempt outcome.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AttemptOutcome {
    /// Request completed successfully.
    Ok,
    /// Request failed with a typed error.
    Error,
    /// Request was cancelled.
    Cancelled,
}

/// Compression metadata and decoded body.
#[derive(Clone, PartialEq, Eq)]
pub struct DecodedPartition {
    /// Partition index.
    pub partition: u32,
    /// Raw decoded bytes.
    pub body: Vec<u8>,
    /// Compression metadata.
    pub compression: CompressionEvidence,
}

impl fmt::Debug for DecodedPartition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DecodedPartition")
            .field("partition", &self.partition)
            .field("body_len", &self.body.len())
            .field("compression", &self.compression)
            .finish()
    }
}

/// Compression metadata captured for evidence.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CompressionEvidence {
    /// Original content encoding.
    pub content_encoding: ContentEncoding,
    /// Compressed bytes observed.
    pub compressed_bytes: u64,
    /// Uncompressed bytes observed.
    pub uncompressed_bytes: u64,
}

/// Supported content encodings.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContentEncoding {
    /// No content encoding header.
    Identity,
    /// Gzip-compressed response.
    Gzip,
}

impl ContentEncoding {
    /// Parse a content-encoding header.
    pub fn parse(raw: Option<&str>) -> Result<Self, TransportError> {
        match raw.map(str::trim).filter(|value| !value.is_empty()) {
            None => Ok(Self::Identity),
            Some(value) if value.eq_ignore_ascii_case("identity") => Ok(Self::Identity),
            Some(value) if value.eq_ignore_ascii_case("gzip") => Ok(Self::Gzip),
            Some(_) => Err(TransportError::new(
                TransportErrorCode::UnsupportedContentEncoding,
                "unsupported partition content-encoding",
            )),
        }
    }
}

struct DecodedPartitionResponse {
    status: StatusClass,
    body: Vec<u8>,
    compression: CompressionEvidence,
}

fn decode_partition_response(
    response: Response,
    limits: BodyLimits,
    partition: u32,
) -> Result<DecodedPartitionResponse, TransportError> {
    let encoding = ContentEncoding::parse(response_header(
        response.headers.as_slice(),
        HEADER_CONTENT_ENCODING,
    ))?;
    let compressed_bytes = response.body.len() as u64;
    limits.enforce_partition_sizes(compressed_bytes, 0)?;
    let max_uncompressed =
        usize::try_from(limits.max_partition_uncompressed_bytes).map_err(|_| {
            TransportError::new(
                TransportErrorCode::BodyLimitExceeded,
                "partition uncompressed limit exceeds local addressable memory",
            )
        })?;
    let mut decoded = Vec::new();
    let decode_result = match encoding {
        ContentEncoding::Identity => {
            let mut decompressor = IdentityDecompressor::new(Some(max_uncompressed));
            decompressor
                .decompress(response.body.as_slice(), &mut decoded)
                .and_then(|()| decompressor.finish(&mut decoded))
        }
        ContentEncoding::Gzip => {
            let mut decompressor = GzipDecompressor::new(Some(max_uncompressed));
            decompressor
                .decompress(response.body.as_slice(), &mut decoded)
                .and_then(|()| decompressor.finish(&mut decoded))
        }
    };
    if let Err(error) = decode_result {
        let code = match encoding {
            ContentEncoding::Identity => TransportErrorCode::BodyLimitExceeded,
            ContentEncoding::Gzip => TransportErrorCode::GzipDecodeFailed,
        };
        return Err(TransportError::new(
            code,
            format!("partition {partition} decode failed: {error}"),
        ));
    }
    let uncompressed_bytes = decoded.len() as u64;
    limits.enforce_partition_sizes(compressed_bytes, uncompressed_bytes)?;
    Ok(DecodedPartitionResponse {
        status: classify_status(StatusCode(response.status)),
        body: decoded,
        compression: CompressionEvidence {
            content_encoding: encoding,
            compressed_bytes,
            uncompressed_bytes,
        },
    })
}

fn response_header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(header_name, _)| header_name.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.as_str())
}

fn retry_after_ms(headers: &[(String, String)]) -> Option<u64> {
    let raw = response_header(headers, "Retry-After")?.trim();
    raw.parse::<u64>()
        .ok()
        .and_then(|seconds| seconds.checked_mul(1_000))
        .or_else(|| retry_after_http_date_ms(raw))
}

/// Convert an HTTP-date form `Retry-After` (RFC 7231) into a delay in
/// milliseconds.
///
/// The header names an absolute calendar instant, so the delay is
/// `target - now` measured on the real wall clock. `asupersync::time::wall_now()`
/// is **process-relative** (elapsed since process start), not Unix-epoch, so it
/// must not be used here: subtracting a tiny process uptime from an absolute
/// Unix instant yields a decades-long bogus delay that exceeds the retry budget
/// and aborts retries on the first attempt. `std::time::SystemTime` (std — not a
/// forbidden async-runtime dependency) is the correct absolute clock source.
fn retry_after_http_date_ms(raw: &str) -> Option<u64> {
    let target_seconds = parse_http_date_unix_seconds(raw)?;
    let now_unix_seconds = i64::try_from(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_secs(),
    )
    .ok()?;
    let delta_seconds = target_seconds.saturating_sub(now_unix_seconds);
    if delta_seconds <= 0 {
        return Some(0);
    }
    Some((delta_seconds as u64).saturating_mul(1_000))
}

fn parse_http_date_unix_seconds(raw: &str) -> Option<i64> {
    parse_imf_fixdate(raw)
        .or_else(|| parse_rfc850_date(raw))
        .or_else(|| parse_asctime_date(raw))
}

fn parse_imf_fixdate(raw: &str) -> Option<i64> {
    let (_, rest) = raw.split_once(", ")?;
    let mut parts = rest.split_ascii_whitespace();
    let day = parts.next()?.parse::<u32>().ok()?;
    let month = parse_http_month(parts.next()?)?;
    let year = parts.next()?.parse::<i32>().ok()?;
    let (hour, minute, second) = parse_http_time(parts.next()?)?;
    if parts.next()? != "GMT" || parts.next().is_some() {
        return None;
    }
    unix_seconds_utc(year, month, day, hour, minute, second)
}

fn parse_rfc850_date(raw: &str) -> Option<i64> {
    let (_, rest) = raw.split_once(", ")?;
    let mut parts = rest.split_ascii_whitespace();
    let date = parts.next()?;
    let mut date_parts = date.split('-');
    let day = date_parts.next()?.parse::<u32>().ok()?;
    let month = parse_http_month(date_parts.next()?)?;
    let year_two_digits = date_parts.next()?.parse::<u32>().ok()?;
    if date_parts.next().is_some() {
        return None;
    }
    let year = if year_two_digits >= 70 {
        1900 + i32::try_from(year_two_digits).ok()?
    } else {
        2000 + i32::try_from(year_two_digits).ok()?
    };
    let (hour, minute, second) = parse_http_time(parts.next()?)?;
    if parts.next()? != "GMT" || parts.next().is_some() {
        return None;
    }
    unix_seconds_utc(year, month, day, hour, minute, second)
}

fn parse_asctime_date(raw: &str) -> Option<i64> {
    let mut parts = raw.split_ascii_whitespace();
    let _weekday = parts.next()?;
    let month = parse_http_month(parts.next()?)?;
    let day = parts.next()?.parse::<u32>().ok()?;
    let (hour, minute, second) = parse_http_time(parts.next()?)?;
    let year = parts.next()?.parse::<i32>().ok()?;
    if parts.next().is_some() {
        return None;
    }
    unix_seconds_utc(year, month, day, hour, minute, second)
}

fn parse_http_month(month: &str) -> Option<u32> {
    match month {
        "Jan" => Some(1),
        "Feb" => Some(2),
        "Mar" => Some(3),
        "Apr" => Some(4),
        "May" => Some(5),
        "Jun" => Some(6),
        "Jul" => Some(7),
        "Aug" => Some(8),
        "Sep" => Some(9),
        "Oct" => Some(10),
        "Nov" => Some(11),
        "Dec" => Some(12),
        _ => None,
    }
}

fn parse_http_time(time: &str) -> Option<(u32, u32, u32)> {
    let mut parts = time.split(':');
    let hour = parts.next()?.parse::<u32>().ok()?;
    let minute = parts.next()?.parse::<u32>().ok()?;
    let second = parts.next()?.parse::<u32>().ok()?;
    if parts.next().is_some() || hour > 23 || minute > 59 || second > 60 {
        return None;
    }
    Some((hour, minute, second))
}

fn unix_seconds_utc(
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
    second: u32,
) -> Option<i64> {
    if !(1..=12).contains(&month)
        || day == 0
        || day > days_in_month(year, month)
        || hour > 23
        || minute > 59
        || second > 60
    {
        return None;
    }
    let second = second.min(59);
    days_from_civil(year, month, day)
        .checked_mul(86_400)?
        .checked_add(i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second))
}

fn days_in_month(year: i32, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 if is_leap_year(year) => 29,
        2 => 28,
        _ => 0,
    }
}

fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
    let mut year = i64::from(year);
    let month = i64::from(month);
    let day = i64::from(day);
    year -= i64::from(month <= 2);
    let era = if year >= 0 { year } else { year - 399 } / 400;
    let year_of_era = year - era * 400;
    let month_prime = month + if month > 2 { -3 } else { 9 };
    let day_of_year = (153 * month_prime + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
    era * 146_097 + day_of_era - 719_468
}

fn is_retryable_status(status: u16) -> bool {
    // A 408 StatementTimeout is terminal: the statement already exceeded its
    // server-side STATEMENT_TIMEOUT_IN_SECONDS, so retrying re-runs a query that
    // will time out again and burns the retry budget for nothing. Only transient
    // conditions (429 overload, 5xx) are retried. This matches the authoritative
    // `ResponseClass::is_retryable` in franken-snowflake-sqlapi.
    matches!(
        classify_status(StatusCode(status)),
        StatusClass::RateLimited | StatusClass::ServerErrorRetryable
    )
}

fn route_allows_automatic_retry(route: &TransportRoute) -> bool {
    // Snowflake warns that ambiguous resubmission of a statement can execute
    // the SQL twice. Plain submit retry is allowed only when the URL carries
    // the documented requestId + retry=true contract recorded above. Poll,
    // partition, and cancel are idempotent transport follow-ups.
    route.has_retry_contract()
        || matches!(
            route,
            TransportRoute::Poll { .. }
                | TransportRoute::Partition { .. }
                | TransportRoute::Cancel { .. }
        )
}

fn cancel_reason_or(cx: &Cx, fallback: fn() -> CancelReason) -> CancelReason {
    cx.cancel_reason().unwrap_or_else(fallback)
}

async fn wait_retry_delay(cx: &Cx, delay: Duration) -> Result<(), CancelReason> {
    if cx.checkpoint().is_err() {
        return Err(cancel_reason_or(cx, CancelReason::parent_cancelled));
    }
    if asupersync::time::budget_sleep(cx, delay, cx.now_for_observability())
        .await
        .is_err()
    {
        return Err(cancel_reason_or(cx, CancelReason::deadline));
    }
    if cx.checkpoint().is_err() {
        return Err(cancel_reason_or(cx, CancelReason::parent_cancelled));
    }
    Ok(())
}

async fn run_with_cancellation_mask<T>(cx: &Cx, future: impl Future<Output = T>) -> T {
    let mut future = Box::pin(future);
    std::future::poll_fn(|task| cx.masked(|| future.as_mut().poll(task))).await
}

/// Async partition sink.
pub trait PartitionSink {
    /// Accept a decoded partition in order.
    fn accept(
        &mut self,
        cx: &Cx,
        partition: DecodedPartition,
    ) -> impl std::future::Future<Output = Result<(), TransportError>>;
}

/// Partition stream request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PartitionStreamRequest {
    /// Authorization for partition GETs and optional cleanup cancellation.
    pub auth: AuthorizationDescriptor,
    /// Statement handle.
    pub statement_handle: StatementHandle,
    /// First partition index to fetch.
    pub first_partition: u32,
    /// Exclusive end partition index.
    pub end_partition_exclusive: u32,
    /// Maximum concurrent fetches.
    pub max_concurrent_fetches: usize,
    /// Child budget meet-composed with the ambient query budget for each fetch.
    pub child_budget: Budget,
    /// Whether a local cancellation should attempt a remote statement cancel.
    pub remote_cancel_on_local_cancel: bool,
    /// Seed partitions already decoded, normally inline partition zero.
    pub seed_partitions: Vec<DecodedPartition>,
}

impl PartitionStreamRequest {
    /// Validate and summarize the streaming plan.
    pub fn plan(&self) -> Result<PartitionStreamSummary, TransportError> {
        if self.end_partition_exclusive < self.first_partition {
            return Err(TransportError::new(
                TransportErrorCode::InvalidPartitionPlan,
                "partition end must be greater than or equal to start",
            ));
        }
        if self.max_concurrent_fetches == 0 {
            return Err(TransportError::new(
                TransportErrorCode::InvalidPartitionPlan,
                "partition fetch concurrency must be at least one",
            ));
        }
        let mut previous_seed = None;
        for seed in &self.seed_partitions {
            if seed.partition >= self.first_partition {
                return Err(TransportError::new(
                    TransportErrorCode::InvalidPartitionPlan,
                    "seed partitions must precede the fetch range",
                ));
            }
            if previous_seed.is_some_and(|previous| seed.partition <= previous) {
                return Err(TransportError::new(
                    TransportErrorCode::InvalidPartitionPlan,
                    "seed partitions must be strictly increasing",
                ));
            }
            previous_seed = Some(seed.partition);
        }
        let accepted_seed_partitions = u32::try_from(self.seed_partitions.len()).map_err(|_| {
            TransportError::new(
                TransportErrorCode::InvalidPartitionPlan,
                "too many seed partitions",
            )
        })?;
        Ok(PartitionStreamSummary {
            statement_handle: self.statement_handle.clone(),
            planned_partitions: self.end_partition_exclusive - self.first_partition,
            accepted_seed_partitions,
            max_concurrent_fetches: self.max_concurrent_fetches,
        })
    }
}

/// Partition streaming summary.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartitionStreamSummary {
    /// Statement handle.
    pub statement_handle: StatementHandle,
    /// Number of non-seed partitions planned.
    pub planned_partitions: u32,
    /// Number of seed partitions pushed to the sink.
    pub accepted_seed_partitions: u32,
    /// Concurrency bound.
    pub max_concurrent_fetches: usize,
}

/// Request body wrapper for submit.
#[derive(Clone, PartialEq, Eq)]
pub struct SubmitHttpRequest {
    /// Submit route.
    pub route: TransportRoute,
    /// Authorization.
    pub auth: AuthorizationDescriptor,
    /// JSON body bytes owned by the SQL API crate.
    pub body: Vec<u8>,
    /// Whether this call is a retry/resubmit attempt.
    pub retry_resubmit: bool,
}

impl fmt::Debug for SubmitHttpRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubmitHttpRequest")
            .field("route", &self.route)
            .field("auth", &self.auth)
            .field("body_len", &self.body.len())
            .field("retry_resubmit", &self.retry_resubmit)
            .finish()
    }
}

/// Submit response body.
#[derive(Clone, PartialEq, Eq)]
pub struct SubmitHttpResponse {
    /// HTTP status class.
    pub status: StatusClass,
    /// Raw response body.
    pub body: Vec<u8>,
}

impl fmt::Debug for SubmitHttpResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SubmitHttpResponse")
            .field("status", &self.status)
            .field("body_len", &self.body.len())
            .finish()
    }
}

/// Poll request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PollHttpRequest {
    /// Authorization.
    pub auth: AuthorizationDescriptor,
    /// Statement handle.
    pub statement_handle: StatementHandle,
}

/// Poll response body.
#[derive(Clone, PartialEq, Eq)]
pub struct PollHttpResponse {
    /// HTTP status class.
    pub status: StatusClass,
    /// Raw response body.
    pub body: Vec<u8>,
}

impl fmt::Debug for PollHttpResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PollHttpResponse")
            .field("status", &self.status)
            .field("body_len", &self.body.len())
            .finish()
    }
}

/// Partition fetch request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PartitionHttpRequest {
    /// Authorization.
    pub auth: AuthorizationDescriptor,
    /// Statement handle.
    pub statement_handle: StatementHandle,
    /// Partition index.
    pub partition: u32,
}

/// Partition response body.
#[derive(Clone, PartialEq, Eq)]
pub struct PartitionBody {
    /// HTTP status class.
    pub status: StatusClass,
    /// Raw response body.
    pub body: Vec<u8>,
    /// Compression evidence from the wire response.
    pub compression: CompressionEvidence,
}

impl fmt::Debug for PartitionBody {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PartitionBody")
            .field("status", &self.status)
            .field("body_len", &self.body.len())
            .field("compression", &self.compression)
            .finish()
    }
}

/// Cancel request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CancelHttpRequest {
    /// Authorization.
    pub auth: AuthorizationDescriptor,
    /// Statement handle.
    pub statement_handle: StatementHandle,
    /// Cancellation reason kind.
    pub reason_kind: CancelKind,
}

/// Cancel response body.
#[derive(Clone, PartialEq, Eq)]
pub struct CancelHttpResponse {
    /// HTTP status class.
    pub status: StatusClass,
    /// Raw response body.
    pub body: Vec<u8>,
}

impl fmt::Debug for CancelHttpResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CancelHttpResponse")
            .field("status", &self.status)
            .field("body_len", &self.body.len())
            .finish()
    }
}

struct PlannedTransportRequest {
    route: TransportRoute,
    auth: AuthorizationDescriptor,
    body: Vec<u8>,
    retry_resubmit: bool,
    request_id: Option<RequestId>,
    partition: Option<u32>,
    budget: Budget,
}

impl PlannedTransportRequest {
    fn partition(
        auth: AuthorizationDescriptor,
        statement_handle: StatementHandle,
        partition: u32,
        budget: Budget,
    ) -> Self {
        Self {
            route: TransportRoute::Partition {
                handle: statement_handle,
                partition,
            },
            auth,
            body: Vec::new(),
            retry_resubmit: false,
            request_id: None,
            partition: Some(partition),
            budget,
        }
    }
}

impl From<SubmitHttpRequest> for PlannedTransportRequest {
    fn from(value: SubmitHttpRequest) -> Self {
        let request_id = match &value.route {
            TransportRoute::SubmitRetry { request_id } => Some(request_id.clone()),
            TransportRoute::SubmitWithQuery { query } => query
                .iter()
                .find_map(|(key, value)| (*key == "requestId").then(|| RequestId::new(value))),
            TransportRoute::Submit
            | TransportRoute::Poll { .. }
            | TransportRoute::Partition { .. }
            | TransportRoute::Cancel { .. } => None,
        };
        Self {
            route: value.route,
            auth: value.auth,
            body: value.body,
            retry_resubmit: value.retry_resubmit,
            request_id,
            partition: None,
            budget: Budget::unlimited(),
        }
    }
}

impl From<PollHttpRequest> for PlannedTransportRequest {
    fn from(value: PollHttpRequest) -> Self {
        Self {
            route: TransportRoute::Poll {
                handle: value.statement_handle,
            },
            auth: value.auth,
            body: Vec::new(),
            retry_resubmit: false,
            request_id: None,
            partition: None,
            budget: Budget::unlimited(),
        }
    }
}

impl From<PartitionHttpRequest> for PlannedTransportRequest {
    fn from(value: PartitionHttpRequest) -> Self {
        Self {
            route: TransportRoute::Partition {
                handle: value.statement_handle,
                partition: value.partition,
            },
            auth: value.auth,
            body: Vec::new(),
            retry_resubmit: false,
            request_id: None,
            partition: Some(value.partition),
            budget: Budget::unlimited(),
        }
    }
}

impl From<CancelHttpRequest> for PlannedTransportRequest {
    fn from(value: CancelHttpRequest) -> Self {
        Self {
            route: TransportRoute::Cancel {
                handle: value.statement_handle,
            },
            auth: value.auth,
            body: Vec::new(),
            retry_resubmit: false,
            request_id: None,
            partition: None,
            budget: Budget::unlimited(),
        }
    }
}

trait FromResponseBody: Sized {
    fn from_response(
        response: Response,
        limits: BodyLimits,
        partition: Option<u32>,
    ) -> Result<Self, TransportError>;
}

impl FromResponseBody for SubmitHttpResponse {
    fn from_response(
        response: Response,
        limits: BodyLimits,
        _partition: Option<u32>,
    ) -> Result<Self, TransportError> {
        limits.enforce_response_size(TransportRouteKind::Submit, response.body.len())?;
        Ok(Self {
            status: classify_status(StatusCode(response.status)),
            body: response.body,
        })
    }
}

impl FromResponseBody for PollHttpResponse {
    fn from_response(
        response: Response,
        limits: BodyLimits,
        _partition: Option<u32>,
    ) -> Result<Self, TransportError> {
        limits.enforce_response_size(TransportRouteKind::Poll, response.body.len())?;
        Ok(Self {
            status: classify_status(StatusCode(response.status)),
            body: response.body,
        })
    }
}

impl FromResponseBody for PartitionBody {
    fn from_response(
        response: Response,
        limits: BodyLimits,
        partition: Option<u32>,
    ) -> Result<Self, TransportError> {
        let decoded = decode_partition_response(response, limits, partition.unwrap_or_default())?;
        Ok(Self {
            status: decoded.status,
            body: decoded.body,
            compression: decoded.compression,
        })
    }
}

impl FromResponseBody for CancelHttpResponse {
    fn from_response(
        response: Response,
        limits: BodyLimits,
        _partition: Option<u32>,
    ) -> Result<Self, TransportError> {
        limits.enforce_response_size(TransportRouteKind::Cancel, response.body.len())?;
        Ok(Self {
            status: classify_status(StatusCode(response.status)),
            body: response.body,
        })
    }
}

/// Stable transport error codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransportErrorCode {
    /// TLS root policy refused.
    TlsRootPolicyRefused,
    /// Invalid Snowflake host or endpoint.
    InvalidSnowflakeHost,
    /// Body size limit exceeded.
    BodyLimitExceeded,
    /// Header failed validation.
    HeaderRejected,
    /// Retry budget exhausted.
    RetryBudgetExhausted,
    /// Cancelled during TCP connect or TLS handshake.
    CancelledDuringConnect,
    /// Remote cancel after submit failed.
    CancelAfterSubmitFailed,
    /// Unexpected HTTP status.
    HttpStatusUnexpected,
    /// Response decode failed.
    ResponseDecodeFailed,
    /// Gzip decode failed.
    GzipDecodeFailed,
    /// Unsupported content encoding.
    UnsupportedContentEncoding,
    /// Submit retry lacks the requestId + retry=true contract.
    NonIdempotentSubmitRetryRefused,
    /// Invalid partition streaming plan.
    InvalidPartitionPlan,
    /// Asupersync HTTP/network error.
    NetworkError,
}

/// Transport error with a stable code and redacted message.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransportError {
    /// Stable transport error code.
    pub code: TransportErrorCode,
    /// Redacted message.
    pub message: String,
}

impl TransportError {
    /// Create a transport error.
    #[must_use]
    pub fn new(code: TransportErrorCode, message: impl Into<String>) -> Self {
        let message = message.into();
        Self {
            code,
            message: redact(&message).into_owned(),
        }
    }

    /// Map to the shared connector error registry.
    #[must_use]
    pub fn into_snowflake_error(self) -> franken_snowflake_core::error::SnowflakeError {
        use franken_snowflake_core::error::{SnowflakeError, SnowflakeErrorCode};
        let code = match self.code {
            TransportErrorCode::RetryBudgetExhausted => SnowflakeErrorCode::RetryBudgetExhausted,
            TransportErrorCode::HttpStatusUnexpected | TransportErrorCode::ResponseDecodeFailed => {
                SnowflakeErrorCode::UpstreamError
            }
            TransportErrorCode::NetworkError
            | TransportErrorCode::TlsRootPolicyRefused
            | TransportErrorCode::InvalidSnowflakeHost
            | TransportErrorCode::CancelledDuringConnect
            | TransportErrorCode::CancelAfterSubmitFailed => SnowflakeErrorCode::NetworkError,
            TransportErrorCode::BodyLimitExceeded
            | TransportErrorCode::HeaderRejected
            | TransportErrorCode::GzipDecodeFailed
            | TransportErrorCode::UnsupportedContentEncoding
            | TransportErrorCode::NonIdempotentSubmitRetryRefused
            | TransportErrorCode::InvalidPartitionPlan => SnowflakeErrorCode::UsageError,
        };
        SnowflakeError::new(code, self.message)
    }
}

impl fmt::Display for TransportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}: {}", self.code, self.message)
    }
}

impl std::error::Error for TransportError {}

#[cfg(test)]
mod tests {
    use super::*;

    use std::cell::RefCell;
    use std::collections::VecDeque;

    fn endpoint() -> SnowflakeEndpoint {
        SnowflakeEndpoint::parse("https://xy12345.us-east-1.snowflakecomputing.com")
            .expect("valid endpoint")
    }

    fn auth() -> AuthorizationDescriptor {
        auth_with_token("secret-token")
    }

    fn auth_with_token(token: &str) -> AuthorizationDescriptor {
        AuthorizationDescriptor::bearer(
            SnowflakeAuthTokenType::ProgrammaticAccessToken,
            token,
            "sha256:abc123",
        )
    }

    fn header(name: &str, value: &str) -> Vec<(String, String)> {
        vec![(name.to_string(), value.to_string())]
    }

    #[test]
    fn endpoint_requires_https_and_rejects_credentials() {
        assert!(SnowflakeEndpoint::parse("http://xy123.snowflakecomputing.com").is_err());
        assert!(SnowflakeEndpoint::parse("https://user@xy123.snowflakecomputing.com").is_err());
        assert!(SnowflakeEndpoint::parse("https://xy123.snowflakecomputing.com?role=x").is_err());
        assert!(SnowflakeEndpoint::parse("https://xy123.snowflakecomputing.com/proxy").is_err());
        assert!(SnowflakeEndpoint::parse("https://attacker.example.com").is_err());
        let parsed = SnowflakeEndpoint::parse("https://xy123.snowflakecomputing.com/")
            .expect("valid endpoint");
        assert_eq!(parsed.base_url(), "https://xy123.snowflakecomputing.com");
    }

    #[test]
    fn route_urls_are_canonical() {
        let request_id = RequestId::new("req-123");
        let handle = StatementHandle::new("stmt-456");
        assert_eq!(
            endpoint().route_url(&TransportRoute::SubmitRetry { request_id }),
            "https://xy12345.us-east-1.snowflakecomputing.com/api/v2/statements?requestId=req-123&retry=true"
        );
        assert_eq!(
            endpoint().route_url(&TransportRoute::Partition {
                handle,
                partition: 7,
            }),
            "https://xy12345.us-east-1.snowflakecomputing.com/api/v2/statements/stmt-456?partition=7"
        );
    }

    #[test]
    fn route_components_are_percent_encoded() {
        let request_id = RequestId::new("req-123&retry=false");
        let handle = StatementHandle::new("stmt/456?partition=9#frag");

        assert_eq!(
            endpoint().route_url(&TransportRoute::SubmitRetry { request_id }),
            "https://xy12345.us-east-1.snowflakecomputing.com/api/v2/statements?requestId=req-123%26retry%3Dfalse&retry=true"
        );
        assert_eq!(
            endpoint().route_url(&TransportRoute::Poll {
                handle: handle.clone(),
            }),
            "https://xy12345.us-east-1.snowflakecomputing.com/api/v2/statements/stmt%2F456%3Fpartition%3D9%23frag"
        );
        assert_eq!(
            endpoint().route_url(&TransportRoute::Cancel { handle }),
            "https://xy12345.us-east-1.snowflakecomputing.com/api/v2/statements/stmt%2F456%3Fpartition%3D9%23frag/cancel"
        );
    }

    #[test]
    fn submit_query_values_are_percent_encoded() {
        let route = TransportRoute::SubmitWithQuery {
            query: vec![
                ("requestId", "req-123&retry=false".to_owned()),
                ("retry", "true".to_owned()),
                ("nullable", "false".to_owned()),
            ],
        };

        assert_eq!(
            endpoint().route_url(&route),
            "https://xy12345.us-east-1.snowflakecomputing.com/api/v2/statements?requestId=req-123%26retry%3Dfalse&retry=true&nullable=false"
        );
        assert!(route.has_retry_contract());
    }

    #[test]
    fn auth_debug_redacts_secret_bearer() {
        let rendered = format!("{:?}", auth());
        assert!(rendered.contains("sha256:abc123"));
        assert!(!rendered.contains("secret-token"));
    }

    #[test]
    fn auth_headers_wire_token_type_without_logging_secret() {
        let headers = auth().wire_headers().expect("headers");
        assert!(
            headers
                .iter()
                .any(|h| { h.name == HEADER_AUTHORIZATION && h.value == "Bearer secret-token" })
        );
        assert!(
            headers
                .iter()
                .any(|h| { h.name == HEADER_TOKEN_TYPE && h.value == "PROGRAMMATIC_ACCESS_TOKEN" })
        );
    }

    #[test]
    fn wire_request_and_header_debug_redact_authorization_bearer() {
        let token = "sfpat_http_debug_secret_123";
        let client = SnowflakeHttpClient::new(
            TransportConfig::new(endpoint()),
            AsupersyncHttpClient::new(),
        );
        let request = SubmitHttpRequest {
            route: TransportRoute::Submit,
            auth: auth_with_token(token),
            body: b"{}".to_vec(),
            retry_resubmit: false,
        };
        let plan = client.submit_plan(&request).expect("submit plan");
        let authorization = plan
            .headers
            .iter()
            .find(|header| header.name == HEADER_AUTHORIZATION)
            .expect("authorization header");

        assert_eq!(authorization.value, format!("Bearer {token}"));

        for rendered in [
            format!("{authorization:?}"),
            format!("{:?}", plan.headers),
            format!("{plan:?}"),
            serde_json::to_string(authorization).expect("header json"),
        ] {
            assert!(
                !rendered.contains(token),
                "diagnostic surface leaked bearer token: {rendered}"
            );
            assert!(rendered.contains(REDACTION_PLACEHOLDER));
        }
    }

    #[test]
    fn body_bearing_debug_surfaces_only_report_lengths() {
        let secret_body = b"sfpat_http_body_secret_123".to_vec();
        let decimal_secret_prefix = "115, 102, 112, 97, 116";
        let compression = CompressionEvidence {
            content_encoding: ContentEncoding::Identity,
            compressed_bytes: secret_body.len() as u64,
            uncompressed_bytes: secret_body.len() as u64,
        };
        let decoded = DecodedPartition {
            partition: 0,
            body: secret_body.clone(),
            compression,
        };
        let stream = PartitionStreamRequest {
            auth: auth(),
            statement_handle: StatementHandle::new("stmt-1"),
            first_partition: 1,
            end_partition_exclusive: 1,
            max_concurrent_fetches: 1,
            child_budget: Budget::unlimited(),
            remote_cancel_on_local_cancel: false,
            seed_partitions: vec![decoded.clone()],
        };

        for rendered in [
            format!(
                "{:?}",
                SubmitHttpRequest {
                    route: TransportRoute::Submit,
                    auth: auth(),
                    body: secret_body.clone(),
                    retry_resubmit: false,
                }
            ),
            format!(
                "{:?}",
                SubmitHttpResponse {
                    status: StatusClass::Completed,
                    body: secret_body.clone(),
                }
            ),
            format!(
                "{:?}",
                PollHttpResponse {
                    status: StatusClass::Running,
                    body: secret_body.clone(),
                }
            ),
            format!(
                "{:?}",
                PartitionBody {
                    status: StatusClass::Completed,
                    body: secret_body.clone(),
                    compression,
                }
            ),
            format!(
                "{:?}",
                CancelHttpResponse {
                    status: StatusClass::Completed,
                    body: secret_body.clone(),
                }
            ),
            format!("{decoded:?}"),
            format!("{stream:?}"),
        ] {
            assert!(
                !rendered.contains("sfpat_http_body_secret_123"),
                "debug surface leaked body as text: {rendered}"
            );
            assert!(
                !rendered.contains(decimal_secret_prefix),
                "debug surface leaked body as reconstructable bytes: {rendered}"
            );
            assert!(rendered.contains("body_len"));
        }
    }

    #[test]
    fn transport_error_constructor_redacts_secret_shaped_messages() {
        let token = "ghp_httpTransportSecret0123";
        let error = TransportError::new(
            TransportErrorCode::NetworkError,
            format!("connect failed with token={token}"),
        );

        for rendered in [
            error.message.clone(),
            error.to_string(),
            serde_json::to_string(&error).expect("error json"),
            format!("{error:?}"),
        ] {
            assert!(
                !rendered.contains(token),
                "transport error leaked secret-shaped token: {rendered}"
            );
            assert!(rendered.contains(REDACTION_PLACEHOLDER));
        }
    }

    #[test]
    fn body_limits_refuse_oversize_submit_request() {
        let limits = BodyLimits {
            max_submit_request_bytes: 3,
            ..BodyLimits::default()
        };
        assert!(limits.enforce(TransportRouteKind::Submit, 4).is_err());
        assert!(limits.enforce(TransportRouteKind::Poll, 4).is_ok());
    }

    #[test]
    fn partition_limits_count_both_compressed_and_uncompressed() {
        let limits = BodyLimits {
            max_partition_compressed_bytes: 10,
            max_partition_uncompressed_bytes: 20,
            ..BodyLimits::default()
        };
        assert!(limits.enforce_partition_sizes(10, 20).is_ok());
        assert!(limits.enforce_partition_sizes(11, 20).is_err());
        assert!(limits.enforce_partition_sizes(10, 21).is_err());
    }

    #[test]
    fn retry_after_wins_before_exponential_jitter() {
        let policy = RetryPolicy::default();
        let request_id = RequestId::new("req-123");
        assert_eq!(
            policy.delay_for(Some(&request_id), TransportRouteKind::Poll, 1, Some(500), 0),
            Some(Duration::from_millis(500))
        );
        let exponential = policy
            .delay_for(Some(&request_id), TransportRouteKind::Poll, 2, None, 0)
            .expect("delay");
        assert!(exponential >= Duration::from_millis(200));
        assert!(exponential <= Duration::from_millis(230));
    }

    #[test]
    fn retry_after_delta_seconds_form_is_clock_independent() {
        assert_eq!(retry_after_ms(&header("Retry-After", "5")), Some(5_000));
        assert_eq!(retry_after_ms(&header("Retry-After", "0")), Some(0));
        assert_eq!(retry_after_ms(&header("Retry-After", "not-a-value")), None);
    }

    #[test]
    fn retry_after_http_date_formats_parse_to_unix_seconds() {
        // All three RFC 7231 date forms denote 2015-10-21T07:28:00Z. Parsing is a
        // pure function (no clock) and must accept IMF-fixdate, RFC-850, and
        // asctime forms identically.
        for raw in [
            "Wed, 21 Oct 2015 07:28:00 GMT",
            "Wednesday, 21-Oct-15 07:28:00 GMT",
            "Wed Oct 21 07:28:00 2015",
        ] {
            assert_eq!(parse_http_date_unix_seconds(raw), Some(1_445_412_480));
        }
    }

    #[test]
    fn retry_after_http_date_is_measured_against_absolute_wall_clock() {
        // Regression: an HTTP-date `Retry-After` must be differenced against
        // absolute Unix time, not asupersync's process-relative `wall_now()`. A
        // date already in the past yields a zero delay. Under the old
        // process-relative clock (≈ seconds since process start) the same past
        // date produced a ~decades-long bogus delay that blew the retry budget and
        // aborted retries on the first attempt — so this would have returned a huge
        // value, not `Some(0)`.
        for raw in [
            "Wed, 21 Oct 2015 07:28:00 GMT",
            "Wednesday, 21-Oct-15 07:28:00 GMT",
            "Wed Oct 21 07:28:00 2015",
        ] {
            assert_eq!(retry_after_ms(&header("Retry-After", raw)), Some(0));
        }

        // A clearly-future date yields a positive (non-zero) delay rather than the
        // saturated-to-zero past case, confirming the sign of the difference is
        // correct.
        let delay = retry_after_ms(&header("Retry-After", "Fri, 31 Dec 2100 23:59:59 GMT"))
            .expect("future date delay");
        assert!(
            delay > 0,
            "future date must yield a positive delay, got {delay}"
        );
    }

    #[test]
    fn retry_budget_stops_before_sleeping_past_total_budget() {
        let policy = RetryPolicy {
            total_budget_ms: 50,
            ..RetryPolicy::default()
        };
        assert_eq!(
            policy.delay_for(None, TransportRouteKind::Poll, 1, Some(100), 0),
            None
        );
    }

    #[test]
    fn retry_decision_charges_each_delay_once() {
        let policy = RetryPolicy {
            max_attempts: 4,
            base_delay_ms: 25,
            max_delay_ms: 100,
            total_budget_ms: 75,
            respect_retry_after: false,
            deterministic_jitter: false,
        };
        let first = policy
            .next_retry(None, TransportRouteKind::Poll, 1, None, 0)
            .expect("first retry");
        assert_eq!(first.delay, Duration::from_millis(25));
        assert_eq!(first.spent_after_ms, 25);

        let second = policy
            .next_retry(
                None,
                TransportRouteKind::Poll,
                2,
                None,
                first.spent_after_ms,
            )
            .expect("second retry");
        assert_eq!(second.delay, Duration::from_millis(50));
        assert_eq!(second.spent_after_ms, 75);

        assert_eq!(
            policy.next_retry(
                None,
                TransportRouteKind::Poll,
                3,
                None,
                second.spent_after_ms
            ),
            None
        );
    }

    #[test]
    fn attempt_budget_meets_parent_child_and_attempt_quota_once() {
        let parent = Budget::new()
            .with_deadline(Time::from_secs(30))
            .with_poll_quota(10)
            .with_cost_quota(100)
            .with_priority(1);
        let child = Budget::new()
            .with_deadline(Time::from_secs(20))
            .with_poll_quota(8)
            .with_cost_quota(50)
            .with_priority(9);
        let policy = RetryPolicy {
            max_attempts: 4,
            ..RetryPolicy::default()
        };

        let effective = policy.attempt_budget(parent, child, 2);
        let expected = parent
            .meet(child)
            .meet(Budget::new().with_poll_quota(3).with_priority(0));

        assert_eq!(effective, expected);
        assert_eq!(effective.deadline, Some(Time::from_secs(20)));
        assert_eq!(effective.poll_quota, 3);
        assert_eq!(effective.cost_quota, Some(50));
        assert_eq!(effective.priority, 9);
    }

    #[test]
    fn partition_stream_child_budget_flows_to_internal_partition_plan() {
        let parent = Budget::new().with_poll_quota(10).with_cost_quota(100);
        let child = Budget::new().with_poll_quota(2).with_cost_quota(40);
        let planned =
            PlannedTransportRequest::partition(auth(), StatementHandle::new("stmt-1"), 7, child);

        assert_eq!(planned.partition, Some(7));
        assert_eq!(planned.budget, child);
        assert_eq!(
            RetryPolicy::default().attempt_budget(parent, planned.budget, 1),
            parent
                .meet(child)
                .meet(Budget::new().with_poll_quota(RetryPolicy::default().max_attempts))
        );
    }

    #[test]
    fn effective_budget_drives_timeout_and_exhaustion_reason() {
        let now = Time::from_secs(10);
        let bounded = Budget::new().with_deadline(Time::from_secs(12));
        assert_eq!(
            budget_timeout_at(bounded, now),
            Some(Duration::from_secs(2))
        );
        assert!(
            budget_exhaustion_reason_at(Budget::new().with_deadline(Time::from_secs(10)), now)
                .expect("deadline exhausted")
                .is_kind(CancelKind::Deadline)
        );
        assert!(
            budget_exhaustion_reason_at(Budget::new().with_poll_quota(0), now)
                .expect("poll quota exhausted")
                .is_kind(CancelKind::PollQuota)
        );
        assert!(
            budget_exhaustion_reason_at(Budget::new().with_cost_quota(0), now)
                .expect("cost budget exhausted")
                .is_kind(CancelKind::CostBudget)
        );
    }

    #[test]
    fn status_classification_keeps_202_and_429_distinct() {
        assert_eq!(classify_status(StatusCode(200)), StatusClass::Completed);
        assert_eq!(classify_status(StatusCode(202)), StatusClass::Running);
        assert_eq!(classify_status(StatusCode(401)), StatusClass::Unauthorized);
        assert_eq!(classify_status(StatusCode(403)), StatusClass::Unexpected);
        assert_eq!(
            classify_status(StatusCode(408)),
            StatusClass::StatementTimeout
        );
        assert_eq!(classify_status(StatusCode(422)), StatusClass::QueryFailure);
        assert_eq!(classify_status(StatusCode(429)), StatusClass::RateLimited);
        assert_eq!(
            classify_status(StatusCode(503)),
            StatusClass::ServerErrorRetryable
        );
    }

    #[test]
    fn statement_timeout_408_is_not_retried() {
        // Regression: a 408 statement timeout is terminal, never retried — it
        // would just time out again. Only transient overload/5xx retry. Matches
        // the authoritative sqlapi ResponseClass::is_retryable.
        assert!(!is_retryable_status(408));
        assert!(is_retryable_status(429));
        assert!(is_retryable_status(500));
        assert!(is_retryable_status(503));
        // Terminal/success statuses are never retried.
        assert!(!is_retryable_status(200));
        assert!(!is_retryable_status(422));
        assert!(!is_retryable_status(404));
    }

    #[test]
    fn content_encoding_fails_closed() {
        assert_eq!(
            ContentEncoding::parse(None).expect("identity"),
            ContentEncoding::Identity
        );
        assert_eq!(
            ContentEncoding::parse(Some("gzip")).expect("gzip"),
            ContentEncoding::Gzip
        );
        assert!(ContentEncoding::parse(Some("br")).is_err());
    }

    #[test]
    fn submit_retry_requires_idempotency_contract() {
        let client = SnowflakeHttpClient::new(
            TransportConfig::new(endpoint()),
            AsupersyncHttpClient::new(),
        );
        let request = SubmitHttpRequest {
            route: TransportRoute::Submit,
            auth: auth(),
            body: b"{}".to_vec(),
            retry_resubmit: true,
        };
        assert!(client.submit_plan(&request).is_err());
        let request = SubmitHttpRequest {
            route: TransportRoute::SubmitRetry {
                request_id: RequestId::new("req-123"),
            },
            auth: auth(),
            body: b"{}".to_vec(),
            retry_resubmit: true,
        };
        assert!(client.submit_plan(&request).is_ok());
    }

    #[test]
    fn plain_submit_post_is_not_blindly_retried_but_cancel_is_retry_safe() {
        assert_eq!(SNOWFLAKE_SQL_API_RESUBMIT_DOC_CONSULTED, "2026-06-25");
        assert!(
            SNOWFLAKE_SQL_API_RESUBMIT_DOC_URL
                .contains("/developer-guide/sql-api/submitting-requests")
        );
        assert!(is_retryable_status(503));
        assert!(is_retryable_status(429));

        assert!(!route_allows_automatic_retry(&TransportRoute::Submit));
        assert!(route_allows_automatic_retry(&TransportRoute::SubmitRetry {
            request_id: RequestId::new("req-123")
        }));
        assert!(route_allows_automatic_retry(&TransportRoute::Poll {
            handle: StatementHandle::new("stmt-1")
        }));
        assert!(route_allows_automatic_retry(&TransportRoute::Partition {
            handle: StatementHandle::new("stmt-1"),
            partition: 1,
        }));
        assert!(route_allows_automatic_retry(&TransportRoute::Cancel {
            handle: StatementHandle::new("stmt-1")
        }));
    }

    #[test]
    fn wire_plan_adds_json_headers() {
        let client = SnowflakeHttpClient::new(
            TransportConfig::new(endpoint()),
            AsupersyncHttpClient::new(),
        );
        let request = SubmitHttpRequest {
            route: TransportRoute::Submit,
            auth: auth(),
            body: b"{}".to_vec(),
            retry_resubmit: false,
        };
        let plan = client.submit_plan(&request).expect("submit plan");
        assert_eq!(plan.method, Method::Post);
        assert!(plan.headers.iter().any(|h| h.name == HEADER_ACCEPT));
        assert!(plan.headers.iter().any(|h| h.name == HEADER_CONTENT_TYPE));
    }

    #[test]
    fn partition_wire_plan_advertises_gzip() {
        let client = SnowflakeHttpClient::new(
            TransportConfig::new(endpoint()),
            AsupersyncHttpClient::new(),
        );
        let request = PartitionHttpRequest {
            auth: auth(),
            statement_handle: StatementHandle::new("stmt-1"),
            partition: 2,
        };
        let plan = client.partition_plan(&request).expect("partition plan");
        assert!(
            plan.headers
                .iter()
                .any(|h| h.name == HEADER_ACCEPT_ENCODING && h.value == PARTITION_ACCEPT_ENCODING)
        );
    }

    #[test]
    fn gzip_partition_response_is_decoded_with_evidence() {
        use asupersync::http::compress::{Compressor, GzipCompressor};

        let mut compressed = Vec::new();
        let mut compressor = GzipCompressor::new();
        compressor
            .compress(br#"{"data":[["one"]]}"#, &mut compressed)
            .expect("compress");
        compressor.finish(&mut compressed).expect("finish");

        let response =
            Response::new(200, "OK", compressed.clone()).with_header("content-encoding", "gzip");
        let body =
            PartitionBody::from_response(response, BodyLimits::default(), Some(1)).expect("decode");
        assert_eq!(body.body, br#"{"data":[["one"]]}"#);
        assert_eq!(body.compression.content_encoding, ContentEncoding::Gzip);
        assert_eq!(body.compression.compressed_bytes, compressed.len() as u64);
        assert_eq!(
            body.compression.uncompressed_bytes,
            br#"{"data":[["one"]]}"#.len() as u64
        );
    }

    #[test]
    fn compressed_partition_limit_is_checked_before_gzip_decode() {
        let response = Response::new(200, "OK", b"not a valid gzip body".to_vec())
            .with_header("content-encoding", "gzip");
        let limits = BodyLimits {
            max_partition_compressed_bytes: 3,
            ..BodyLimits::default()
        };

        let error = PartitionBody::from_response(response, limits, Some(1))
            .expect_err("compressed limit should fail before gzip decode");

        assert_eq!(error.code, TransportErrorCode::BodyLimitExceeded);
        assert!(error.message.contains("compressed partition"));
    }

    /// A scripted raw transport: answers each `send` from a queue and records
    /// every request the retry loop actually issued.
    struct ScriptedRaw {
        responses: RefCell<VecDeque<Result<Response, AsupersyncClientError>>>,
        requests: RefCell<Vec<RecordedRequest>>,
        /// Cancel this context from inside `send` (an in-flight cancellation).
        cancel_in_flight: Option<Cx>,
    }

    #[derive(Clone, Debug)]
    struct RecordedRequest {
        method: Method,
        url: String,
        headers: Vec<(String, String)>,
        body: Vec<u8>,
        timeout: Option<Duration>,
    }

    impl ScriptedRaw {
        fn new(responses: Vec<Result<Response, AsupersyncClientError>>) -> Self {
            Self {
                responses: RefCell::new(responses.into()),
                requests: RefCell::new(Vec::new()),
                cancel_in_flight: None,
            }
        }

        fn requests(&self) -> Vec<RecordedRequest> {
            self.requests.borrow().clone()
        }
    }

    impl RawHttp for ScriptedRaw {
        async fn send(
            &self,
            _cx: &Cx,
            method: Method,
            url: String,
            headers: Vec<(String, String)>,
            body: Vec<u8>,
            timeout: Option<Duration>,
        ) -> Result<Response, AsupersyncClientError> {
            self.requests.borrow_mut().push(RecordedRequest {
                method,
                url,
                headers,
                body,
                timeout,
            });
            if let Some(cx) = &self.cancel_in_flight {
                cx.cancel_with(
                    CancelKind::User,
                    Some("cancelled while the request was in flight"),
                );
            }
            self.responses.borrow_mut().pop_front().unwrap_or_else(|| {
                Err(AsupersyncClientError::Io(std::io::Error::other(
                    "scripted transport exhausted",
                )))
            })
        }
    }

    fn fast_retry_config(max_attempts: u32) -> TransportConfig {
        TransportConfig {
            retry: RetryPolicy {
                max_attempts,
                base_delay_ms: 1,
                max_delay_ms: 1,
                total_budget_ms: 1_000,
                respect_retry_after: true,
                deterministic_jitter: true,
            },
            ..TransportConfig::new(endpoint())
        }
    }

    fn scripted_client(
        max_attempts: u32,
        responses: Vec<Result<Response, AsupersyncClientError>>,
    ) -> SnowflakeHttpClient<ScriptedRaw> {
        SnowflakeHttpClient::new(fast_retry_config(max_attempts), ScriptedRaw::new(responses))
    }

    fn ok_json(status: u16, body: &str) -> Result<Response, AsupersyncClientError> {
        Ok(Response::new(status, "scripted", body.as_bytes().to_vec())
            .with_header("content-type", "application/json"))
    }

    fn network_error() -> Result<Response, AsupersyncClientError> {
        Err(AsupersyncClientError::Io(std::io::Error::other(
            "connection reset by peer",
        )))
    }

    fn retry_submit(request_id: &str) -> SubmitHttpRequest {
        SubmitHttpRequest {
            route: TransportRoute::SubmitRetry {
                request_id: RequestId::new(request_id),
            },
            auth: auth(),
            body: b"{\"statement\":\"select 1\"}".to_vec(),
            retry_resubmit: true,
        }
    }

    fn poll_request() -> PollHttpRequest {
        PollHttpRequest {
            auth: auth(),
            statement_handle: StatementHandle::new("stmt-poll-1"),
        }
    }

    #[test]
    fn execute_retries_a_429_by_resubmitting_the_same_request_id_with_retry_true() {
        asupersync::test_utils::run_test(|| async {
            let client = scripted_client(
                4,
                vec![
                    Ok(Response::new(429, "Too Many Requests", Vec::new())
                        .with_header("Retry-After", "0")),
                    ok_json(202, "{\"statementHandle\":\"h1\"}"),
                ],
            );
            let cx = Cx::for_testing();
            let outcome = client
                .submit_statement(&cx, retry_submit("req-idem-1"))
                .await;
            let TransportOutcome::Ok(response) = outcome else {
                panic!("expected a submit response, got {outcome:?}");
            };
            assert_eq!(response.status, StatusClass::Running);
            let requests = client.client.requests();
            assert_eq!(requests.len(), 2, "one 429 then one resubmit");
            for request in &requests {
                assert_eq!(request.method, Method::Post);
                assert!(
                    request.url.contains("requestId=req-idem-1"),
                    "{}",
                    request.url
                );
                assert!(request.url.contains("retry=true"), "{}", request.url);
                assert!(
                    request.headers.iter().any(
                        |(name, value)| name == "Authorization" && value.starts_with("Bearer ")
                    ),
                    "bearer header present on every attempt"
                );
            }
            // The resubmit is byte-identical to the original: same URL, same body,
            // and with an unlimited budget neither attempt carries a timeout.
            assert_eq!(requests[0].url, requests[1].url);
            assert_eq!(requests[0].body, requests[1].body);
            assert!(requests.iter().all(|request| request.timeout.is_none()));
        });
    }

    #[test]
    fn execute_refuses_to_auto_retry_a_bare_submit_on_a_retryable_status() {
        asupersync::test_utils::run_test(|| async {
            let client = scripted_client(
                4,
                vec![Ok(Response::new(503, "Service Unavailable", Vec::new()))],
            );
            let cx = Cx::for_testing();
            let outcome = client
                .submit_statement(
                    &cx,
                    SubmitHttpRequest {
                        route: TransportRoute::Submit,
                        auth: auth(),
                        body: b"{}".to_vec(),
                        retry_resubmit: false,
                    },
                )
                .await;
            let TransportOutcome::Err(error) = outcome else {
                panic!("expected a typed refusal, got {outcome:?}");
            };
            assert!(
                error.message.contains("requestId plus retry=true"),
                "{}",
                error.message
            );
            assert_eq!(
                client.client.requests().len(),
                1,
                "no second attempt was sent"
            );
        });
    }

    #[test]
    fn execute_exhausts_the_retry_budget_after_max_attempts() {
        asupersync::test_utils::run_test(|| async {
            let client = scripted_client(
                3,
                vec![
                    Ok(Response::new(503, "Service Unavailable", Vec::new())),
                    Ok(Response::new(503, "Service Unavailable", Vec::new())),
                    Ok(Response::new(503, "Service Unavailable", Vec::new())),
                    ok_json(200, "{}"),
                ],
            );
            let cx = Cx::for_testing();
            let outcome = client.poll_statement(&cx, poll_request()).await;
            let TransportOutcome::Err(error) = outcome else {
                panic!("expected retry exhaustion, got {outcome:?}");
            };
            assert!(
                error
                    .message
                    .contains("exhausted retry budget after 3 attempts"),
                "{}",
                error.message
            );
            assert_eq!(client.client.requests().len(), 3);
        });
    }

    #[test]
    fn execute_retries_a_network_error_on_a_poll_route_then_succeeds() {
        asupersync::test_utils::run_test(|| async {
            let client = scripted_client(
                4,
                vec![
                    network_error(),
                    ok_json(202, "{\"statementHandle\":\"h1\"}"),
                ],
            );
            let cx = Cx::for_testing();
            let outcome = client.poll_statement(&cx, poll_request()).await;
            let TransportOutcome::Ok(response) = outcome else {
                panic!("expected a poll response, got {outcome:?}");
            };
            assert_eq!(response.status, StatusClass::Running);
            let requests = client.client.requests();
            assert_eq!(requests.len(), 2);
            assert!(
                requests[1].url.ends_with("/api/v2/statements/stmt-poll-1"),
                "{}",
                requests[1].url
            );
            assert_eq!(requests[1].method, Method::Get);
        });
    }

    #[test]
    fn execute_maps_a_client_deadline_to_a_deadline_cancel() {
        asupersync::test_utils::run_test(|| async {
            let client = scripted_client(4, vec![Err(AsupersyncClientError::DeadlineExceeded)]);
            let cx = Cx::for_testing();
            let outcome = client.poll_statement(&cx, poll_request()).await;
            let TransportOutcome::Cancelled(reason) = outcome else {
                panic!("expected a deadline cancel, got {outcome:?}");
            };
            assert_eq!(reason.kind, CancelKind::Deadline);
            assert_eq!(client.client.requests().len(), 1);
        });
    }

    #[test]
    fn execute_reports_an_in_flight_user_cancel_and_the_masked_cleanup_still_sends_the_remote_cancel()
     {
        asupersync::test_utils::run_test(|| async {
            let cx = Cx::for_testing();
            let mut raw = ScriptedRaw::new(vec![
                Err(AsupersyncClientError::Cancelled),
                ok_json(200, "{\"status\":\"cancelled\"}"),
            ]);
            raw.cancel_in_flight = Some(cx.clone());
            let client = SnowflakeHttpClient::new(fast_retry_config(4), raw);

            let outcome = client.poll_statement(&cx, poll_request()).await;
            let TransportOutcome::Cancelled(reason) = outcome else {
                panic!("expected a cancellation, got {outcome:?}");
            };
            assert_eq!(reason.kind, CancelKind::User);

            // The cleanup runs on the same (now cancelled) context and must still
            // reach the cancel endpoint: that is what the cancellation mask is for.
            let cleanup = client
                .cancel_after_local_cancel(&cx, auth(), StatementHandle::new("stmt-poll-1"), reason)
                .await;
            // The transport reports the cancel endpoint's own outcome (the driver
            // is what turns the statement into a local `Cancelled`).
            assert!(
                matches!(cleanup, TransportOutcome::Ok(_)),
                "the masked cleanup must reach the endpoint and be acknowledged: {cleanup:?}"
            );
            let requests = client.client.requests();
            assert_eq!(requests.len(), 2, "poll + remote cancel");
            assert_eq!(requests[1].method, Method::Post);
            assert!(
                requests[1]
                    .url
                    .ends_with("/api/v2/statements/stmt-poll-1/cancel"),
                "{}",
                requests[1].url
            );
        });
    }

    #[test]
    fn execute_short_circuits_on_an_already_cancelled_context() {
        asupersync::test_utils::run_test(|| async {
            let client = scripted_client(4, vec![ok_json(202, "{}")]);
            let cx = Cx::for_testing();
            cx.cancel_with(CancelKind::User, Some("operator hit ctrl-c"));
            let outcome = client.poll_statement(&cx, poll_request()).await;
            assert!(
                matches!(outcome, TransportOutcome::Cancelled(_)),
                "{outcome:?}"
            );
            assert!(
                client.client.requests().is_empty(),
                "nothing is sent after a cancel"
            );
        });
    }

    #[test]
    fn execute_decodes_a_gzip_partition_end_to_end_and_asks_for_gzip() {
        use asupersync::http::compress::{Compressor, GzipCompressor};
        asupersync::test_utils::run_test(|| async {
            let plain = br#"{"data":[["1","alpha"]]}"#;
            let mut compressed = Vec::new();
            let mut compressor = GzipCompressor::new();
            compressor
                .compress(plain, &mut compressed)
                .expect("compress");
            compressor.finish(&mut compressed).expect("finish");
            let client = scripted_client(
                4,
                vec![Ok(Response::new(200, "OK", compressed.clone())
                    .with_header("content-encoding", "gzip"))],
            );
            let cx = Cx::for_testing();
            let outcome = client
                .fetch_partition(
                    &cx,
                    PartitionHttpRequest {
                        auth: auth(),
                        statement_handle: StatementHandle::new("stmt-1"),
                        partition: 3,
                    },
                )
                .await;
            let TransportOutcome::Ok(body) = outcome else {
                panic!("expected a decoded partition, got {outcome:?}");
            };
            assert_eq!(body.body, plain);
            assert_eq!(body.compression.content_encoding, ContentEncoding::Gzip);
            assert_eq!(body.compression.compressed_bytes, compressed.len() as u64);
            let requests = client.client.requests();
            assert_eq!(requests.len(), 1);
            assert!(
                requests[0]
                    .url
                    .ends_with("/api/v2/statements/stmt-1?partition=3"),
                "{}",
                requests[0].url
            );
            assert!(
                requests[0]
                    .headers
                    .iter()
                    .any(|(name, value)| name == HEADER_ACCEPT_ENCODING
                        && value == PARTITION_ACCEPT_ENCODING),
                "partition fetches advertise gzip"
            );
        });
    }

    fn poll_ready<F: Future>(future: F) -> F::Output {
        let waker = std::task::Waker::noop();
        let mut task = std::task::Context::from_waker(waker);
        let mut future = std::pin::pin!(future);
        match future.as_mut().poll(&mut task) {
            std::task::Poll::Ready(output) => output,
            std::task::Poll::Pending => unreachable!("test future unexpectedly pending"),
        }
    }

    #[test]
    fn cancellation_mask_defers_cleanup_checkpoint() {
        let cx = Cx::for_testing();
        cx.cancel_with(CancelKind::User, Some("cleanup"));

        let checkpoint_ok = poll_ready(run_with_cancellation_mask(&cx, async {
            cx.checkpoint().is_ok()
        }));

        assert!(checkpoint_ok);
        assert!(cx.checkpoint().is_err());
    }

    #[test]
    fn stream_cancel_cleanup_success_still_reports_cancelled() {
        let reason = CancelReason::user("partition stream cancelled");
        let cleanup = TransportOutcome::ok(CancelHttpResponse {
            status: StatusClass::Completed,
            body: br#"{"code":"090001"}"#.to_vec(),
        });

        let outcome = stream_cancel_cleanup_outcome(cleanup, reason.clone());

        match outcome {
            TransportOutcome::Cancelled(actual) => assert_eq!(actual.kind, reason.kind),
            TransportOutcome::Ok(_) | TransportOutcome::Err(_) | TransportOutcome::Panicked(_) => {
                panic!("cancelled stream cleanup must not report success")
            }
        }
    }

    struct CancellingSink {
        cx: Cx,
        accepted: u32,
    }

    impl PartitionSink for CancellingSink {
        fn accept(
            &mut self,
            _cx: &Cx,
            _partition: DecodedPartition,
        ) -> impl Future<Output = Result<(), TransportError>> {
            self.accepted = self.accepted.saturating_add(1);
            self.cx
                .cancel_with(CancelKind::User, Some("partition sink cancelled"));
            std::future::ready(Ok(()))
        }
    }

    #[test]
    fn partition_stream_observes_cancel_after_seed_accept() {
        let cx = Cx::for_testing();
        let client = SnowflakeHttpClient::new(
            TransportConfig::new(endpoint()),
            AsupersyncHttpClient::new(),
        );
        let request = PartitionStreamRequest {
            auth: auth(),
            statement_handle: StatementHandle::new("stmt-1"),
            first_partition: 1,
            end_partition_exclusive: 1,
            max_concurrent_fetches: 1,
            child_budget: Budget::unlimited(),
            remote_cancel_on_local_cancel: false,
            seed_partitions: vec![DecodedPartition {
                partition: 0,
                body: b"[]".to_vec(),
                compression: CompressionEvidence {
                    content_encoding: ContentEncoding::Identity,
                    compressed_bytes: 2,
                    uncompressed_bytes: 2,
                },
            }],
        };
        let mut sink = CancellingSink {
            cx: cx.clone(),
            accepted: 0,
        };

        let outcome = poll_ready(client.stream_partitions(&cx, request, &mut sink));
        let cancel_kind = match outcome {
            TransportOutcome::Cancelled(reason) => Some(reason.kind),
            TransportOutcome::Ok(_) | TransportOutcome::Err(_) | TransportOutcome::Panicked(_) => {
                None
            }
        };

        assert_eq!(sink.accepted, 1);
        assert_eq!(cancel_kind, Some(CancelKind::User));
    }

    #[test]
    fn partition_stream_plan_validates_concurrency() {
        let request = PartitionStreamRequest {
            auth: auth(),
            statement_handle: StatementHandle::new("stmt-1"),
            first_partition: 1,
            end_partition_exclusive: 3,
            max_concurrent_fetches: 2,
            child_budget: Budget::unlimited(),
            remote_cancel_on_local_cancel: true,
            seed_partitions: Vec::new(),
        };
        assert_eq!(request.plan().expect("plan").planned_partitions, 2);

        let invalid = PartitionStreamRequest {
            max_concurrent_fetches: 0,
            ..request
        };
        assert!(invalid.plan().is_err());
    }

    #[test]
    fn partition_stream_plan_rejects_seed_overlap_and_reordering() {
        let request = PartitionStreamRequest {
            auth: auth(),
            statement_handle: StatementHandle::new("stmt-1"),
            first_partition: 2,
            end_partition_exclusive: 4,
            max_concurrent_fetches: 2,
            child_budget: Budget::unlimited(),
            remote_cancel_on_local_cancel: true,
            seed_partitions: vec![decoded_partition(0), decoded_partition(1)],
        };
        let summary = request.plan().expect("valid seeds before fetch range");
        assert_eq!(summary.accepted_seed_partitions, 2);

        let overlaps = PartitionStreamRequest {
            first_partition: 1,
            seed_partitions: vec![decoded_partition(1)],
            ..request.clone()
        };
        assert!(overlaps.plan().is_err());

        let duplicate = PartitionStreamRequest {
            seed_partitions: vec![decoded_partition(0), decoded_partition(0)],
            ..request.clone()
        };
        assert!(duplicate.plan().is_err());

        let out_of_order = PartitionStreamRequest {
            seed_partitions: vec![decoded_partition(1), decoded_partition(0)],
            ..request
        };
        assert!(out_of_order.plan().is_err());
    }

    fn decoded_partition(partition: u32) -> DecodedPartition {
        DecodedPartition {
            partition,
            body: b"[]".to_vec(),
            compression: CompressionEvidence {
                content_encoding: ContentEncoding::Identity,
                compressed_bytes: 2,
                uncompressed_bytes: 2,
            },
        }
    }
}