azure_data_cosmos_driver 0.5.0

Core implementation layer for Azure Cosmos DB - provides transport, routing, and protocol handling for cross-language SDK reuse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Operation pipeline: the core loop for executing Cosmos DB operations.
//!
//! Implements the 7-stage operation loop with multi-region failover,
//! session retry, endpoint unavailability tracking, partition-level failover
//! (PPAF/PPCB), and deadline enforcement.

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

use azure_core::http::headers::{AsHeaders, HeaderName, HeaderValue};
use futures::future::{pending, select, Either, Future};

use crate::{
    diagnostics::{DiagnosticsContextBuilder, ExecutionContext, PipelineType, TransportSecurity},
    driver::{
        routing::{
            can_circuit_breaker_trigger_failover, is_eligible_for_ppaf, is_eligible_for_ppcb,
            partition_endpoint_state::HealthStatus, partition_key_range_id::PartitionKeyRangeId,
            remove_probe_succeeded_entry, session_manager::SessionManager, AccountEndpointState,
            CosmosEndpoint, LocationEffect, LocationSnapshot, LocationStateStore,
        },
        transport::CosmosTransport,
    },
    models::{
        cosmos_headers::QUERY_CONTENT_TYPE, request_header_names, AccountEndpoint, ActivityId,
        CosmosOperation, CosmosResponse, Credential, DefaultConsistencyLevel,
        EffectivePartitionKey, OperationType, SessionToken, SubStatusCode,
    },
    options::{
        HedgeThreshold, OperationOptionsView, ReadConsistencyStrategy, Region,
        ResolvedThroughputControl,
    },
};

use super::{
    components::{
        OperationAction, OperationRetryState, RoutingDecision, TransportMode, TransportOutcome,
        TransportRequest, TransportResult, DEFAULT_MAX_THROTTLE_ATTEMPTS,
        DEFAULT_MAX_THROTTLE_WAIT,
    },
    hedging_diagnostics::{HedgeDiagnostics, HedgingStrategyConfig},
    hedging_eligibility::evaluate_hedge_eligibility,
    retry_evaluation::{
        build_service_error, evaluate_hedge_leg_effects, evaluate_transport_result,
        is_region_confirming_status, partition_effects_for_deferral,
    },
};

use crate::driver::transport::{
    transport_pipeline::{execute_transport_pipeline, TransportPipelineContext},
    AuthorizationContext,
};

/// Per-request overrides that take precedence over values from [`CosmosOperation`].
///
/// Used by the dataflow pipeline to inject routing and pagination state that
/// varies per physical partition or per page, without mutating the shared
/// `CosmosOperation`. Each field, when `Some`, emits the corresponding request
/// header in [`OperationOverrides::apply_headers`].
#[derive(Debug, Clone, Default)]
pub(crate) struct OperationOverrides {
    /// Feed range to constrain the request to (emits `x-ms-start-epk` / `x-ms-end-epk`).
    pub feed_range: Option<crate::models::FeedRange>,

    /// Physical partition key range ID (emits `x-ms-documentdb-partitionkeyrangeid`).
    pub partition_key_range_id: Option<String>,

    /// Logical partition key (emits `x-ms-documentdb-partitionkey`).
    pub partition_key: Option<crate::models::PartitionKey>,

    /// Continuation token for pagination (emits `x-ms-continuation`).
    pub continuation: Option<String>,
}

impl OperationOverrides {
    /// Applies the override headers to the given header map.
    ///
    /// Headers set here take precedence over any previously-set values for
    /// the same header name (they overwrite on conflict).
    pub fn apply_headers(
        &self,
        headers: &mut azure_core::http::headers::Headers,
    ) -> crate::error::Result<()> {
        if let Some(feed_range) = &self.feed_range {
            if feed_range.min_inclusive() != &EffectivePartitionKey::MIN {
                headers.insert(
                    HeaderName::from_static(request_header_names::START_EPK),
                    HeaderValue::from(feed_range.min_inclusive().as_str().to_owned()),
                );
            }
            if feed_range.max_exclusive() != &EffectivePartitionKey::MAX {
                headers.insert(
                    HeaderName::from_static(request_header_names::END_EPK),
                    HeaderValue::from(feed_range.max_exclusive().as_str().to_owned()),
                );
            }
            headers.insert(
                HeaderName::from_static(request_header_names::READ_FEED_KEY_TYPE),
                HeaderValue::from_static("EffectivePartitionKey"),
            );
        }

        if let Some(pk_range_id) = &self.partition_key_range_id {
            headers.insert(
                HeaderName::from_static(request_header_names::PARTITION_KEY_RANGE_ID),
                HeaderValue::from(pk_range_id.clone()),
            );
        }

        if let Some(pk) = &self.partition_key {
            let pk_headers = pk.as_headers()?;
            for (name, value) in pk_headers {
                headers.insert(name, value);
            }
        }

        if let Some(continuation) = &self.continuation {
            headers.insert(
                HeaderName::from_static(request_header_names::CONTINUATION),
                HeaderValue::from(continuation.clone()),
            );
        }

        Ok(())
    }
}

/// Executes a Cosmos DB operation through the new pipeline architecture.
///
/// This is the entry point called by `CosmosDriver::execute_operation`.
/// It orchestrates the 7-stage operation loop.
///
/// When `pre_resolved_pk_range_id` is `Some`, it is used to seed the
/// `OperationRetryState` so that partition-level failover overrides (PPAF/PPCB)
/// can take effect from the very first attempt.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn execute_operation_pipeline(
    operation: &CosmosOperation,
    overrides: OperationOverrides,
    options: &OperationOptionsView<'_>,
    custom_headers: Option<&std::collections::HashMap<HeaderName, HeaderValue>>,
    location_state_store: &LocationStateStore,
    transport: &CosmosTransport,
    account_endpoint: &AccountEndpoint,
    credential: &Credential,
    user_agent: &azure_core::http::headers::HeaderValue,
    activity_id: &ActivityId,
    pipeline_type: PipelineType,
    transport_security: TransportSecurity,
    diagnostics: DiagnosticsContextBuilder,
    session_manager: &SessionManager,
    account_default_consistency: DefaultConsistencyLevel,
    throughput_control: Option<ResolvedThroughputControl>,
    pre_resolved_pk_range_id: Option<PartitionKeyRangeId>,
) -> crate::error::Result<CosmosResponse> {
    let mut diagnostics = diagnostics;
    let location_snapshot = location_state_store.snapshot();
    let max_failover_retries = options.max_failover_retry_count().copied().unwrap_or(3);

    // Throttle (HTTP 429) retry limits, resolved from the effective operation
    // options. These are the analogs of the .NET SDK's
    // `MaxRetryAttemptsOnRateLimitedRequests` /
    // `MaxRetryWaitTimeOnRateLimitedRequests`. They are forwarded to the
    // transport pipeline, which owns the 429 retry loop. `0` attempts disables
    // throttle retries.
    //
    // **Scope note**: each value is forwarded as a *per-transport-pipeline*
    // budget — `execute_transport_pipeline` is invoked once per attempt that
    // this operation pipeline makes (e.g., per region during failover or per
    // leg during hedging), and each invocation starts with a fresh
    // throttle-retry budget. Total wall-clock cost across an operation is
    // bounded by `end_to_end_latency_policy` (see the per-attempt deadline
    // wiring below), not by these knobs in aggregate.
    let throttling_retry_options = options.throttling_retry_options();
    let max_throttle_attempts = throttling_retry_options
        .max_retry_count()
        .copied()
        .unwrap_or(DEFAULT_MAX_THROTTLE_ATTEMPTS);
    let max_throttle_wait_time = throttling_retry_options
        .max_retry_wait_time()
        .copied()
        .unwrap_or(DEFAULT_MAX_THROTTLE_WAIT);

    // Determine if session consistency is active for this operation.
    let session_capturing_disabled = options
        .session_capturing_disabled()
        .copied()
        .unwrap_or(false);
    let read_consistency_strategy = options
        .read_consistency_strategy()
        .copied()
        .unwrap_or(ReadConsistencyStrategy::Default);
    let session_consistency_active = !session_capturing_disabled
        && read_consistency_strategy.is_session_effective(account_default_consistency);
    let max_session_retries = options
        .max_session_retry_count()
        .copied()
        .unwrap_or_else(|| {
            // Java SDK parity: 2 for single-write, endpoints.len() for multi-write.
            // Uses the original endpoint count (before unavailability filtering).
            if location_snapshot.account.multiple_write_locations_enabled {
                let endpoints_len = location_snapshot
                    .account
                    .preferred_endpoints(operation.is_read_only())
                    .len();
                endpoints_len as u32
            } else {
                2
            }
        });

    let mut retry_state = OperationRetryState::initial(
        location_snapshot.account.generation,
        location_snapshot.account.multiple_write_locations_enabled,
        options
            .excluded_regions()
            .map(|r| r.0.clone())
            .unwrap_or_default(),
        max_failover_retries,
        max_session_retries,
    );

    // Seed the partition key range ID from pre-resolution (PK range cache).
    // This enables PPAF/PPCB partition-level overrides from the very first attempt
    // instead of only after the first retry captures it from response headers.
    retry_state.partition_key_range_id = pre_resolved_pk_range_id;

    // PPAF write-retry: on single-master accounts with per-partition automatic
    // failover enabled, only PPAF-eligible operations (partitioned writes) may
    // be retried to a different region for write region discovery. This avoids
    // enabling unsafe retries for non-partitioned writes such as database or
    // container creates.
    retry_state.ppaf_write_retry_allowed = location_snapshot
        .partitions
        .per_partition_automatic_failover_enabled
        && !location_snapshot.account.multiple_write_locations_enabled
        && operation
            .resource_type()
            .is_partitioned(operation.operation_type());

    // PPCB: when circuit breaker is enabled, partition-level thresholds
    // drive failover instead of marking the whole endpoint unavailable.
    retry_state.ppcb_active = location_snapshot
        .partitions
        .per_partition_circuit_breaker_enabled
        && location_snapshot.account.preferred_read_endpoints.len() > 1;

    // HUB_REGION_PROCESSING_HEADER_SPEC.md §1.5: gate the
    // `x-ms-cosmos-hub-region-processing-only` latch on data-plane scope
    // so metadata-pipeline operations (which ride the same
    // `execute_operation_pipeline`) never emit the header.
    //
    // Use the `PipelineType::is_data_plane()` accessor — NOT `==` matching
    // — because `PipelineType` is `#[non_exhaustive]` and a future variant
    // would silently bypass an equality gate. Equivalently
    // `!pipeline_type.is_metadata()` (the metadata pipeline is the only
    // current variant that is out of spec scope).
    retry_state.is_dataplane = pipeline_type.is_data_plane();

    // The hedge threshold is `min(1000ms, request_timeout / 2)` where
    // `request_timeout` is the **configured** end-to-end latency budget,
    // not the time remaining until the deadline. We compute the
    // configured timeout once here and pass it (not the remaining
    // duration) into `evaluate_hedge_eligibility` / `maybe_upgrade_to_hedge`
    // below so the threshold stays stable across retry-driven upgrades.
    let configured_request_timeout = options.end_to_end_latency_policy().map(|p| p.timeout());
    let deadline = configured_request_timeout.map(|t| Instant::now() + t);

    loop {
        // ── STAGE 1: Acquire LocationSnapshot ──────────────────────────
        let location = location_state_store.snapshot();

        // ── STAGE 2: Resolve endpoint ──────────────────────────────────
        let routing = resolve_endpoint(
            operation,
            &retry_state,
            &location,
            pipeline_type.is_data_plane(),
            location_state_store.endpoint_unavailability_ttl(),
        );

        // Emit one structured debug record per attempt with the chosen
        // routing decision. Tests and SREs filter on this to verify which
        // region/endpoint each operation actually went to. Keep the field
        // name (`routing_decision`) and message (`routing decision made`)
        // stable -- `azure_data_cosmos`'s multi-write integration tests grep
        // for them.
        tracing::debug!(routing_decision = %routing, "routing decision made");

        // ── STAGE 2b: Pre-attempt hedging dispatch ─────────────────────
        // On the **first** attempt of a hedge-eligible operation, race
        // the primary against the threshold timer from t=0 rather than
        // running it to completion and post-classifying. A slow-but-
        // eventually-successful primary still loses to a fast alternate,
        // and a successful primary that finishes pre-threshold still gets
        // `HedgeDiagnostics::primary_only` attached.
        //
        // Falls through to STAGE 3 (sequential execute-then-classify) on:
        //
        // * **Subsequent retries** (`failover_retry_count > 0` or
        //   `session_token_retry_count > 0`). A retry has already consumed
        //   region budget and the next attempt is to a different region;
        //   re-racing it makes no sense. The post-attempt
        //   `maybe_upgrade_to_hedge` at STAGE 5b is the safety net for the
        //   rare "first attempt non-eligible, later retry became eligible"
        //   case.
        // * **Non-hedge-eligible operations** — writes, single-region
        //   accounts, operations whose user `ExcludeRegions` leaves < 2
        //   applicable read endpoints, env-disabled hedging, or per-op
        //   `AvailabilityStrategy::Disabled`. All gated by
        //   [`evaluate_hedge_eligibility`].
        if retry_state.failover_retry_count == 0 && retry_state.session_token_retry_count == 0 {
            if let Some(upgrade) = evaluate_hedge_eligibility(
                operation,
                options,
                &location.account,
                &routing,
                configured_request_timeout,
            ) {
                let attempt_ctx = AttemptContext {
                    operation,
                    overrides: &overrides,
                    custom_headers,
                    transport,
                    account_endpoint,
                    credential,
                    user_agent,
                    activity_id,
                    pipeline_type,
                    transport_security,
                    session_manager,
                    session_consistency_active,
                    options,
                    throughput_control,
                    deadline,
                    configured_request_timeout,
                    can_use_multiple_write_locations: retry_state.can_use_multiple_write_locations,
                    // First attempt: no 1002 has been observed yet, so the
                    // per-state latch is `false`. The shared
                    // `Arc<AtomicBool>` is constructed inside
                    // `execute_hedged` only if the threshold elapses and a
                    // secondary spawns, preserving the zero-overhead
                    // happy path.
                    hub_region_processing_only_initial: retry_state.hub_region_processing_only,
                    // First attempt: no response has been captured yet, so
                    // PK range ID is unknown. PPCB feedback is correctly
                    // gated to no-op on `None` (`record_hedge_outcome`).
                    partition_key_range_id: retry_state.partition_key_range_id.clone(),
                    location_state_store,
                };
                // Latch the one-race-per-operation cap before dispatch
                // so the post-`BothTransient` fallback iteration's
                // STAGE 5b suppresses a second hedge upgrade. The
                // `BothTransient` handler below preserves this flag
                // since it mutates only `partition_key_range_id`,
                // `failover_retry_count`, and `location` on
                // `retry_state` — see [`OperationRetryState`].
                retry_state.hedge_already_fired = true;
                match execute_hedged(
                    &attempt_ctx,
                    &routing,
                    &upgrade.secondary_routing,
                    upgrade.threshold,
                    upgrade.strategy_config,
                    diagnostics,
                    &retry_state,
                )
                .await
                {
                    HedgedRaceResult::Terminal(result) => return result,
                    HedgedRaceResult::BothTransient {
                        primary_region,
                        secondary_region,
                        strategy_config,
                        primary_region_for_diag,
                        secondary_region_for_diag,
                        last_error,
                        diagnostics: returned_diagnostics,
                        partition_key_range_id: race_pk_range_id,
                        observed_session_unavailable: race_observed_1002,
                    } => {
                        // Both legs failed with retriable errors; fall back
                        // into the failover loop against the untried regions.
                        tracing::warn!(
                            activity_id = %activity_id,
                            primary_region = ?primary_region.as_ref().map(crate::options::Region::as_str),
                            secondary_region = ?secondary_region.as_ref().map(crate::options::Region::as_str),
                            "hedge race: both transient on STAGE 2b; attempting failover fallback",
                        );
                        diagnostics = returned_diagnostics;
                        // Fold race-observed PK-range-id and 1002 latch back
                        // into retry_state so the fallback behaves like a
                        // non-hedged attempt that saw the same conditions.
                        if retry_state.partition_key_range_id.is_none() {
                            retry_state.partition_key_range_id = race_pk_range_id;
                        }
                        propagate_hedge_session_unavailable(&mut retry_state, race_observed_1002);
                        if let Err(e) = try_advance_after_both_transient(
                            &mut retry_state,
                            &location,
                            operation.is_read_only(),
                            primary_region.as_ref(),
                            secondary_region.as_ref(),
                            last_error,
                        ) {
                            // Budget exhausted: the race is the terminal
                            // outcome, so stamp the both-transient result
                            // before grafting diagnostics onto the error.
                            // `deadline_elapsed = false`: the budget, not
                            // the deadline, ended the race.
                            diagnostics.set_hedge_diagnostics(HedgeDiagnostics::both_transient(
                                strategy_config,
                                primary_region_for_diag,
                                secondary_region_for_diag,
                                false,
                            ));
                            let diagnostics_ctx = Arc::new(diagnostics.complete());
                            return Err(crate::error::CosmosErrorBuilder::from_error(e)
                                .with_diagnostics(diagnostics_ctx)
                                .build());
                        }
                        diagnostics = enforce_deadline_or_timeout(deadline, options, diagnostics)?;
                        continue;
                    }
                }
            }
        }

        // ── STAGE 3: Build transport request ───────────────────────────
        let execution_context = compute_execution_context(&retry_state);

        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id,
            execution_context,
            deadline,
            resolved_session_token: session_consistency_active
                .then(|| {
                    session_manager.resolve_session_token(
                        operation,
                        operation.request_headers().session_token.as_ref(),
                    )
                })
                .flatten(),
            throughput_control,
        };
        let mut transport_request =
            build_transport_request(operation, &overrides, custom_headers, &ctx)?;

        // HUB_REGION_PROCESSING_HEADER_SPEC.md §3 / public-spec §3.4:
        // Emit the `x-ms-cosmos-hub-region-processing-only: True` header
        // when the latch is set. The latch is flipped in
        // `try_handle_read_session_not_available` on the first 1002 of a
        // single-master data-plane operation, and is sticky for the
        // remainder of the operation's transport attempts (AC-1, AC-2).
        apply_hub_region_header(&mut transport_request, &retry_state);

        apply_tentative_writes_header(
            &mut transport_request,
            operation,
            location.account.multiple_write_locations_enabled,
        );

        apply_optional_request_headers(&mut transport_request, operation, options);

        tracing::trace!(
            method = ?transport_request.method,
            url = %transport_request.url,
            "transport request created");

        let selected_transport = match pipeline_type {
            PipelineType::DataPlane => {
                transport.get_dataplane_transport(account_endpoint, routing.transport_mode)?
            }
            PipelineType::Metadata => transport.get_metadata_transport(account_endpoint)?,
        };

        // ── STAGE 4: Execute via transport pipeline ────────────────────

        let result = execute_transport_pipeline(
            transport_request,
            &TransportPipelineContext {
                transport: &selected_transport,
                allow_sent_transport_retry: operation.is_read_only() || operation.is_idempotent(),
                credential,
                user_agent,
                pipeline_type,
                transport_security,
                endpoint_key: routing.endpoint.endpoint_key(),
                max_throttle_attempts,
                max_throttle_wait_time,
            },
            &mut diagnostics,
        )
        .await;

        // Capture partition key range ID from response headers (first time only).
        if retry_state.partition_key_range_id.is_none() {
            if let Some(headers) = result.cosmos_headers() {
                if let Some(pk_range_id) = headers.partition_key_range_id.as_deref() {
                    retry_state.partition_key_range_id =
                        Some(PartitionKeyRangeId::from(pk_range_id.to_owned()));
                }
            }
        }

        // ── STAGE 4b: Capture session token ─────────────────────────────
        // Capture session tokens from both successful and certain error
        // responses (409 Conflict, 412 Precondition Failed, 404 non-1002).
        // The server advances the session token even on these errors, so
        // not capturing would break read-your-writes guarantees.
        //
        // This runs BEFORE evaluate_transport_result so that tokens are
        // captured regardless of whether the response maps to Complete,
        // Abort, or a retry action. 409/412 map to Abort, and the Abort
        // variant does not carry headers — capturing after evaluation
        // would silently drop tokens from those responses.
        if session_consistency_active {
            if let Some(cosmos_headers) = result.cosmos_headers() {
                if should_capture_session_token_from_status(
                    cosmos_headers.substatus.as_ref(),
                    &result.outcome,
                ) {
                    session_manager.capture_session_token(operation, cosmos_headers);
                }
            }
        }

        // ── STAGE 5: Evaluate result → action ──────────────────────────
        let (action, effects) =
            evaluate_transport_result(operation, &routing.endpoint, result, &retry_state);

        // ── STAGE 5b: Optional hedging upgrade ─────────────────────────
        // When the just-classified action would have advanced to a
        // different region anyway (FailoverRetry / SessionRetry) and the
        // operation is eligible for cross-region hedging with a strategy
        // resolved, replace it with `OperationAction::Hedge` so STAGE 7
        // races primary and secondary in parallel via `execute_hedged()`.
        // If no upgrade applies the original action passes through
        // unchanged — preserving today's sequential-failover semantics
        // for non-hedgeable operations, single-region accounts,
        // env-disabled hedging, and explicit `AvailabilityStrategy::Disabled`.
        //
        // Cap to one hedge race per operation: once a race has been
        // dispatched (via STAGE 2b or a prior STAGE 7 Hedge arm), do
        // not upgrade again. Each race already burns two regions of RU
        // even on the `BothTransient` fallback path; allowing
        // back-to-back upgrades would compound RU consumption without
        // letting the surrounding failover loop make sequential
        // progress against the remaining regions.
        let action = if retry_state.hedge_already_fired {
            action
        } else {
            maybe_upgrade_to_hedge(
                action,
                operation,
                options,
                &location.account,
                &routing,
                configured_request_timeout,
            )
        };

        // ── STAGE 6: Apply location effects ────────────────────────────
        // Single-master write effects are deferred into
        // `retry_state.pending_write_effects` instead of being applied
        // immediately. They are flushed only when the write definitively
        // reaches a region (Complete, or Abort with a region-confirming
        // status such as 409 Conflict). This prevents transient retry
        // failures from polluting the routing state with unverified
        // partition or endpoint outages — critical for PPAF on single-master
        // accounts where prematurely marking the only known write region
        // unavailable would force an unnecessary cross-region failover.
        // Read-path and multi-master write effects are applied immediately
        // so PPCB counters can drive threshold-based failover.
        let (immediate_effects, deferred_effects) = partition_effects_for_deferral(
            operation.is_read_only(),
            retry_state.can_use_multiple_write_locations,
            retry_state.ppaf_write_retry_allowed,
            effects,
        );
        retry_state.pending_write_effects.extend(deferred_effects);
        location_state_store.apply(&immediate_effects).await;

        // ── STAGE 7: Act on the control-flow decision ──────────────────
        match action {
            OperationAction::Complete(result) => {
                // Flush any deferred write-path effects now that the write
                // has definitively succeeded. The current region is proven
                // healthy, so the previously-failed regions can be safely
                // marked unavailable for this partition (and endpoint, when
                // PPAF is active).
                flush_pending_write_effects(&mut retry_state, location_state_store).await;

                // If a PPCB probe request succeeded, remove the ProbeCandidate entry.
                try_cleanup_probe_candidate(&retry_state, location_state_store);

                return build_cosmos_response(result, diagnostics);
            }
            OperationAction::FailoverRetry { new_state, delay } => {
                tracing::debug!(
                    activity_id = %activity_id,
                    failover_attempt = new_state.failover_retry_count,
                    delay = ?delay,
                    effects = ?immediate_effects,
                    deferred_effects = retry_state.pending_write_effects.len(),
                    "failover retry triggered",
                );
                apply_failover_delay(delay).await;
                advance_to_next_attempt(
                    &mut retry_state,
                    new_state,
                    location_state_store,
                    operation.is_read_only(),
                );
                diagnostics = enforce_deadline_or_timeout(deadline, options, diagnostics)?;
            }
            OperationAction::SessionRetry { new_state } => {
                // Retry to a different region — the 404/1002 is likely a
                // transient replica lag. Session tokens are intentionally
                // preserved; clearing them would break read-your-writes
                // guarantees. Container-recreation (RID change) handling
                // will be addressed via deterministic RID comparison in
                // a future change.
                advance_to_next_attempt(
                    &mut retry_state,
                    new_state,
                    location_state_store,
                    operation.is_read_only(),
                );
                diagnostics = enforce_deadline_or_timeout(deadline, options, diagnostics)?;
            }
            OperationAction::Abort { error } => {
                // Flush deferred write-path effects if the abort status
                // confirms the region processed the request (e.g., 409
                // Conflict, 412 Precondition Failed). On non-confirming
                // aborts (503/429-3092/410/408/403-3/transport error/deadline)
                // the buffered effects are discarded — we never proved any
                // region was actually healthy, so polluting routing state
                // would be wrong.
                let cosmos_status = error.status();
                let confirming = is_region_confirming_status(&cosmos_status);
                if confirming {
                    flush_pending_write_effects(&mut retry_state, location_state_store).await;
                } else {
                    retry_state.pending_write_effects.clear();
                }

                tracing::error!(
                    activity_id = %activity_id,
                    status = ?cosmos_status,
                    error = %error,
                    operation_type = ?operation.operation_type(),
                    resource_type = ?operation.resource_type(),
                    is_read_only = operation.is_read_only(),
                    is_idempotent = operation.is_idempotent(),
                    failover_retries = retry_state.failover_retry_count,
                    session_retries = retry_state.session_token_retry_count,
                    pk_range_id = ?retry_state.partition_key_range_id,
                    "operation aborted",
                );
                diagnostics
                    .set_operation_status(cosmos_status.status_code(), cosmos_status.sub_status());
                // Graft the completed operation diagnostics (retry history,
                // region attempts, per-request events) onto the error before
                // returning. Without this, callers reading
                // `error.diagnostics()` would see `None` on every aborted
                // operation even though the pipeline tracked everything —
                // the only path that attaches diagnostics in the
                // non-aborted case is `build_cosmos_response`.
                let diagnostics_ctx = Arc::new(diagnostics.complete());
                return Err(crate::error::CosmosErrorBuilder::from_error(error)
                    .with_diagnostics(diagnostics_ctx)
                    .build());
            }
            OperationAction::Hedge {
                secondary_routing: _pre_advance_secondary,
                threshold,
                strategy_config,
                new_state,
            } => {
                // Race the primary attempt against a single cross-region
                // secondary via `execute_hedged`. Returns either a
                // terminal result (return it directly) or a
                // both-transient outcome that we fold back into the
                // failover loop with the next region.
                //
                // We move `diagnostics` into `execute_hedged` because the
                // function takes ownership of the parent builder to merge
                // each hedge attempt's sub-builder back into it and finalize
                // the response (mirroring the `Complete` arm's
                // `build_cosmos_response(result, diagnostics)` shape).
                //
                // Apply `new_state` before building `AttemptContext` so
                // the race inherits the post-transition exclusions, latch,
                // and counters — see `OperationAction::Hedge::new_state`.
                advance_to_next_attempt(
                    &mut retry_state,
                    new_state,
                    location_state_store,
                    operation.is_read_only(),
                );
                // Re-resolve the primary routing against the advanced
                // retry_state and freshly snapshotted location. The
                // pre-advance `routing` referenced the failed region that
                // triggered the upgrade — racing it again as the hedge's
                // primary would double-pay RU on a known-bad region.
                let location = location_state_store.snapshot();
                let primary_routing = resolve_endpoint(
                    operation,
                    &retry_state,
                    &location,
                    pipeline_type.is_data_plane(),
                    location_state_store.endpoint_unavailability_ttl(),
                );
                // Re-evaluate hedge eligibility against the *post-advance*
                // primary. After `advance_to_next_attempt` rotates the
                // LocationIndex, the new primary may coincide with the
                // pre-selected `_pre_advance_secondary`, which would race
                // both legs in the same region (zero benefit, 2× RU). If
                // no distinct alternate remains, fall back to non-hedged
                // dispatch via `continue` — we intentionally do NOT set
                // `hedge_already_fired` since no race actually started.
                let secondary_routing = match evaluate_hedge_eligibility(
                    operation,
                    options,
                    &location.account,
                    &primary_routing,
                    configured_request_timeout,
                ) {
                    Some(upgrade) => upgrade.secondary_routing,
                    None => {
                        tracing::debug!(
                            activity_id = %activity_id,
                            "STAGE 7 hedge upgrade: no distinct alternate region after \
                             advance_to_next_attempt; falling back to non-hedged dispatch",
                        );
                        continue;
                    }
                };
                let attempt_ctx = AttemptContext {
                    operation,
                    overrides: &overrides,
                    custom_headers,
                    transport,
                    account_endpoint,
                    credential,
                    user_agent,
                    activity_id,
                    pipeline_type,
                    transport_security,
                    session_manager,
                    session_consistency_active,
                    options,
                    throughput_control,
                    deadline,
                    configured_request_timeout,
                    can_use_multiple_write_locations: retry_state.can_use_multiple_write_locations,
                    hub_region_processing_only_initial: retry_state.hub_region_processing_only,
                    partition_key_range_id: retry_state.partition_key_range_id.clone(),
                    location_state_store,
                };
                // Same one-race-per-operation latch as STAGE 2b. Set
                // *after* `advance_to_next_attempt` because the latter
                // replaces `retry_state` from `new_state` (which carries
                // `hedge_already_fired = false`).
                retry_state.hedge_already_fired = true;
                match execute_hedged(
                    &attempt_ctx,
                    &primary_routing,
                    &secondary_routing,
                    threshold,
                    strategy_config,
                    diagnostics,
                    &retry_state,
                )
                .await
                {
                    HedgedRaceResult::Terminal(result) => return result,
                    HedgedRaceResult::BothTransient {
                        primary_region,
                        secondary_region,
                        strategy_config,
                        primary_region_for_diag,
                        secondary_region_for_diag,
                        last_error,
                        diagnostics: returned_diagnostics,
                        partition_key_range_id: race_pk_range_id,
                        observed_session_unavailable: race_observed_1002,
                    } => {
                        // Both legs returned a retriable failure with
                        // budget remaining — fall back into the failover
                        // loop (same shape as the STAGE 2b post-race
                        // fallback earlier in this function).
                        tracing::warn!(
                            activity_id = %activity_id,
                            primary_region = ?primary_region.as_ref().map(crate::options::Region::as_str),
                            secondary_region = ?secondary_region.as_ref().map(crate::options::Region::as_str),
                            "hedge race: both transient on STAGE 7; attempting failover fallback",
                        );
                        diagnostics = returned_diagnostics;
                        // Same fold-back as the STAGE 2b handler above.
                        if retry_state.partition_key_range_id.is_none() {
                            retry_state.partition_key_range_id = race_pk_range_id;
                        }
                        propagate_hedge_session_unavailable(&mut retry_state, race_observed_1002);
                        if let Err(e) = try_advance_after_both_transient(
                            &mut retry_state,
                            &location,
                            operation.is_read_only(),
                            primary_region.as_ref(),
                            secondary_region.as_ref(),
                            last_error,
                        ) {
                            // Budget exhausted: stamp the both-transient
                            // result before grafting diagnostics onto the
                            // error (see STAGE 2b). `deadline_elapsed =
                            // false`: the budget, not the deadline, ended it.
                            diagnostics.set_hedge_diagnostics(HedgeDiagnostics::both_transient(
                                strategy_config,
                                primary_region_for_diag,
                                secondary_region_for_diag,
                                false,
                            ));
                            let diagnostics_ctx = Arc::new(diagnostics.complete());
                            return Err(crate::error::CosmosErrorBuilder::from_error(e)
                                .with_diagnostics(diagnostics_ctx)
                                .build());
                        }
                        diagnostics = enforce_deadline_or_timeout(deadline, options, diagnostics)?;
                        continue;
                    }
                }
            }
        }
    }
}

/// Drains `retry_state.pending_write_effects` and applies the subset that is
/// not already reflected in the current routing state.
///
/// Called when a write definitively reaches a region — either a successful
/// completion (HTTP 2xx) or a region-confirming abort (e.g., 409 Conflict).
/// At that point the previously-failed regions are proven to have been the
/// unhealthy ones, and their accumulated effects (partition marks for all
/// writes; endpoint marks too for PPAF on single-master) should be applied.
///
/// Once an override has been established for a partition (PPAF entry exists
/// with the failed region rotated past) or an endpoint has already been
/// marked unavailable, re-applying the same effect is a no-op semantically
/// but still costs a CAS-loop clone of `PartitionEndpointState` /
/// `AccountEndpointState`. We skip such effects here so the steady-state
/// cost of a successful write that retried converges to a single snapshot
/// read.
async fn flush_pending_write_effects(
    retry_state: &mut OperationRetryState,
    location_state_store: &LocationStateStore,
) {
    if retry_state.pending_write_effects.is_empty() {
        return;
    }
    let pending = std::mem::take(&mut retry_state.pending_write_effects);
    let snapshot = location_state_store.snapshot();
    let effects: Vec<LocationEffect> = pending
        .into_iter()
        .filter(|effect| !is_effect_already_applied(effect, &snapshot))
        .collect();
    if effects.is_empty() {
        return;
    }
    location_state_store.apply(&effects).await;
}

/// Returns `true` when the given location effect would be a no-op against the
/// current snapshot — i.e., the routing state has already converged on it.
///
/// This is a conservative check: false negatives (returning `false` when the
/// effect is in fact a no-op) are safe (we just pay the redundant CAS once
/// more). False positives (skipping an effect that would actually mutate
/// state) would be a correctness bug.
fn is_effect_already_applied(effect: &LocationEffect, snapshot: &LocationSnapshot) -> bool {
    match effect {
        LocationEffect::MarkEndpointUnavailable { endpoint, .. } => snapshot
            .account
            .unavailable_endpoints
            .contains_key(endpoint.url()),
        LocationEffect::MarkPartitionUnavailable(partition) => {
            // Without a partition_key_range_id we cannot register an override
            // anyway, so apply() would skip it — treat as already-applied.
            let Some(pk_range_id) = partition.partition_key_range_id.as_ref() else {
                return true;
            };
            let Some(failed_region) = partition.region.as_ref() else {
                return false;
            };
            let partitions = snapshot.partitions.as_ref();
            // Check both override maps. If an entry exists for this partition
            // and its current_endpoint is already a different region than the
            // failed one, the failover has already moved past — re-applying
            // would just bump last_failure_time without changing routing.
            let already_moved = |entry: &crate::driver::routing::partition_endpoint_state::PartitionFailoverEntry| -> bool {
                entry
                    .current_endpoint
                    .region()
                    .is_some_and(|r| r != failed_region)
            };
            partitions
                .failover_overrides
                .get(pk_range_id.as_str())
                .is_some_and(already_moved)
                || partitions
                    .circuit_breaker_overrides
                    .get(pk_range_id.as_str())
                    .is_some_and(already_moved)
        }
        // RefreshAccountProperties is internally rate-limited by
        // `refresh_account_properties_if_due` — let the store decide.
        LocationEffect::RefreshAccountProperties => false,
    }
}

/// Resolves the endpoint for this attempt.
///
/// Uses `LocationSnapshot` and `AccountEndpointState` to select the best
/// available endpoint, respecting excluded regions and unavailability TTL.
fn resolve_endpoint(
    operation: &CosmosOperation,
    retry_state: &OperationRetryState,
    location: &LocationSnapshot,
    prefer_gateway20: bool,
    endpoint_unavailability_ttl: Duration,
) -> RoutingDecision {
    let account = location.account.as_ref();
    let read_only = operation.is_read_only();
    // Build an in-flight skip set from effects deferred during this
    // operation. On retries this skips regions we've already failed against
    // so the next attempt picks a different region. Both kinds of deferred
    // effects contribute regions:
    //   * `MarkPartitionUnavailable` — partition-level failure with a region
    //   * `MarkEndpointUnavailable`  — endpoint-level failure (PPAF SM only)
    //
    // Multi-write retries rotate via `LocationIndex`; PPAF single-master writes
    // use the read endpoint list to discover the current write region.
    let in_flight_failed: Vec<&Region> = if !read_only {
        retry_state
            .pending_write_effects
            .iter()
            .filter_map(|e| match e {
                LocationEffect::MarkPartitionUnavailable(p) => p.region.as_ref(),
                LocationEffect::MarkEndpointUnavailable { endpoint, .. } => endpoint.region(),
                LocationEffect::RefreshAccountProperties => None,
            })
            .collect()
    } else {
        Vec::new()
    };

    let primary = preferred_endpoints_for_attempt(account, retry_state, read_only);
    let selected = try_select_endpoint(
        operation,
        retry_state,
        account,
        primary,
        &in_flight_failed,
        endpoint_unavailability_ttl,
    );

    // If every region in the primary list has been attempted (or excluded),
    // fall back to the standard selection ignoring the in-flight skip set so
    // we always have an endpoint to call.
    let selected = selected.unwrap_or_else(|| {
        try_select_endpoint(
            operation,
            retry_state,
            account,
            primary,
            &[],
            endpoint_unavailability_ttl,
        )
        .unwrap_or_else(|| {
            // Last-resort fallback for both data-plane and pipeline-routed
            // metadata operations (Database/Container/Offer/etc. CRUD) when
            // `try_select_endpoint` returned `None` from both passes. The
            // hub regional endpoint is the canonical landing site: it is
            // the only region with guaranteed-fresh state for metadata
            // writes, and it is the most authoritative single region for
            // data-plane operations.
            //
            // When does this fire? Only when EVERY preferred region was
            // excluded by `OperationOptions::excluded_regions`. Note that
            // `excluded_regions` is a hard per-region filter inside
            // `try_select_endpoint` above: excluded regions are
            // unconditionally skipped in both passes and are not even
            // eligible to be returned as a deprioritized `first_unavailable`
            // fallback. So excluding the hub keeps requests out of the hub
            // region as long as at least one other region remains preferred
            // — see the test
            // `resolve_endpoint_dataplane_isolated_region_unavailable_retries_same_region`
            // which pins that behavior.
            //
            // This site is reserved for the degenerate "everything is
            // excluded" configuration. Rather than fail the operation
            // outright we make a single best-effort attempt against the
            // hub regional endpoint, because failing on exhaustion would
            // surprise callers more than landing on the most authoritative
            // region. If we ever need to add an opt-in "strict / fail on
            // exhaustion" routing mode, this is the site to gate it on.
            //
            // The only requests that legitimately target the global
            // endpoint are account-topology fetches (initial bootstrap,
            // periodic refresh, and `LocationEffect::RefreshAccountProperties`),
            // all of which go through
            // `CosmosDriver::fetch_account_properties_with_transport` and
            // bypass this routing path entirely.
            //
            // `preferred_write_endpoints` is guaranteed non-empty by
            // `build_account_endpoint_state`. During normal operation it
            // contains regional endpoints; during initial bootstrap (before
            // account metadata is fetched) it may contain the global
            // default endpoint, but no pipeline operation should run before
            // topology discovery completes. The `debug_assert!` below
            // guards that invariant.
            account
                .preferred_write_endpoints
                .first()
                .expect("preferred_write_endpoints is always non-empty")
                .clone()
        })
    });
    debug_assert!(
        !selected.is_global(),
        "pipeline operation resolved to global endpoint; \
         this should never happen — only account-topology fetches \
         (which bypass this routing path) may use the global endpoint"
    );
    let use_gateway20 = selected.uses_gateway20(prefer_gateway20);
    let transport_mode = if use_gateway20 {
        TransportMode::Gateway20
    } else {
        TransportMode::Gateway
    };

    // Check for partition-level override (PPAF/PPCB).
    if let Some(pk_range_id) = &retry_state.partition_key_range_id {
        let partitions = location.partitions.as_ref();
        let is_read = operation.is_read_only();
        let is_partitioned = operation
            .resource_type()
            .is_partitioned(operation.operation_type());

        // Helper: build a RoutingDecision from a partition override endpoint.
        let make_partition_routing = |ep: CosmosEndpoint| -> RoutingDecision {
            let ep_use_gw20 = ep.uses_gateway20(prefer_gateway20);
            RoutingDecision {
                selected_url: ep.selected_url(ep_use_gw20).clone(),
                transport_mode: if ep_use_gw20 {
                    TransportMode::Gateway20
                } else {
                    TransportMode::Gateway
                },
                endpoint: ep,
            }
        };

        // PPCB skips stale/excluded/unavailable overrides; PPAF skips only
        // in-flight failures because it targets the single current write region.
        let now = Instant::now();
        let region_in_flight_failed =
            |ep: &CosmosEndpoint| ep.region().is_some_and(|r| in_flight_failed.contains(&r));
        // Topology refresh does not prune partition overrides; stale PPCB
        // targets must fall through to refreshed preferred endpoints.
        let region_not_in_topology = |ep: &CosmosEndpoint| -> bool {
            let Some(region) = ep.region() else {
                return false; // global / hub endpoint stays valid
            };
            !account
                .preferred_read_endpoints
                .iter()
                .chain(account.preferred_write_endpoints.iter())
                .any(|known| known.region() == Some(region))
        };
        let ppcb_should_skip = |ep: &CosmosEndpoint| -> bool {
            if region_in_flight_failed(ep) {
                return true;
            }
            if region_not_in_topology(ep) {
                return true;
            }
            let region = ep.region();
            let excluded =
                region.is_some_and(|r| retry_state.excluded_regions.iter().any(|e| e == r));
            if excluded {
                return true;
            }
            !endpoint_is_available(operation, ep, account, now, endpoint_unavailability_ttl)
        };
        let ppaf_should_skip = region_in_flight_failed;

        if is_eligible_for_ppcb(partitions, account, is_read, is_partitioned) {
            if let Some(entry) = partitions.circuit_breaker_overrides.get(pk_range_id) {
                if entry.health_status == HealthStatus::ProbeCandidate
                    && !ppcb_should_skip(&entry.first_failed_endpoint)
                {
                    // Route probe request to the original (first failed) endpoint.
                    return make_partition_routing(entry.first_failed_endpoint.clone());
                }
                if can_circuit_breaker_trigger_failover(entry, is_read, &partitions.config)
                    && !ppcb_should_skip(&entry.current_endpoint)
                {
                    return make_partition_routing(entry.current_endpoint.clone());
                }
            }
        } else if is_eligible_for_ppaf(partitions, account, is_read, is_partitioned) {
            if let Some(entry) = partitions.failover_overrides.get(pk_range_id) {
                // PPAF overrides do not use probe-based failback (no ProbeCandidate
                // handling). The override persists until the backend signals a change.
                //
                // PPAF defers marks until success, so skip only override targets
                // already failed by this operation.
                if !ppaf_should_skip(&entry.current_endpoint) {
                    return make_partition_routing(entry.current_endpoint.clone());
                }
            }
        }
    }

    RoutingDecision {
        selected_url: selected.selected_url(use_gateway20).clone(),
        endpoint: selected,
        transport_mode,
    }
}

fn preferred_endpoints_for_attempt<'a>(
    account: &'a AccountEndpointState,
    retry_state: &OperationRetryState,
    read_only: bool,
) -> &'a [CosmosEndpoint] {
    if read_only && retry_state.route_reads_to_write_endpoints() {
        &account.preferred_write_endpoints
    } else if !read_only && retry_state.ppaf_write_retry_allowed {
        // PPAF on single-master accounts: writes iterate over the full read
        // endpoint list (all regions in preferred order) so the client can
        // probe other regions to discover the current write region after a
        // backend-side failover. preferred_write_endpoints contains only the
        // currently known write region, which would prevent cross-region
        // write retry.
        &account.preferred_read_endpoints
    } else {
        account.preferred_endpoints(read_only)
    }
}

/// Walks `endpoints` starting at the retry-state base index and returns the
/// first endpoint that is not excluded, not in `skip_regions`, and currently
/// available. Falls back to the first unavailable-but-not-skipped endpoint
/// (mirrors SDK pattern: [available] → [unavailable regional]).
///
/// Returns `None` only when every endpoint is either excluded or in the
/// skip set — the caller decides the next fallback list.
fn try_select_endpoint(
    operation: &CosmosOperation,
    retry_state: &OperationRetryState,
    account: &AccountEndpointState,
    endpoints: &[CosmosEndpoint],
    skip_regions: &[&Region],
    endpoint_unavailability_ttl: Duration,
) -> Option<CosmosEndpoint> {
    if endpoints.is_empty() {
        return None;
    }
    let base_index = if retry_state.location.is_current(account.generation) {
        retry_state.location.index()
    } else {
        0
    };
    let now = Instant::now();
    let len = endpoints.len();
    let mut first_unavailable = None;
    for i in 0..len {
        let candidate = &endpoints[(base_index + i) % len];
        let candidate_region = candidate.region();
        let excluded =
            candidate_region.is_some_and(|r| retry_state.excluded_regions.iter().any(|e| e == r));
        if excluded {
            continue;
        }
        let in_skip_set = candidate_region.is_some_and(|r| skip_regions.contains(&r));
        if in_skip_set {
            continue;
        }
        if endpoint_is_available(
            operation,
            candidate,
            account,
            now,
            endpoint_unavailability_ttl,
        ) {
            return Some(candidate.clone());
        }
        if first_unavailable.is_none() {
            first_unavailable = Some(candidate.clone());
        }
    }
    first_unavailable
}

fn endpoint_is_available(
    operation: &CosmosOperation,
    endpoint: &CosmosEndpoint,
    account: &AccountEndpointState,
    now: Instant,
    endpoint_unavailability_ttl: Duration,
) -> bool {
    !account
        .unavailable_endpoints
        .get(endpoint.url())
        .is_some_and(|(marked_at, reason)| {
            if operation.is_read_only()
                && matches!(
                    reason,
                    crate::driver::routing::UnavailableReason::WriteForbidden
                )
            {
                return false;
            }

            now.saturating_duration_since(*marked_at) < endpoint_unavailability_ttl
        })
}

/// Parameters resolved per-attempt for building a transport request.
///
/// Groups per-attempt state that varies across retries and failovers,
/// reducing the number of arguments passed to `build_transport_request`.
struct TransportRequestContext<'a> {
    routing: &'a RoutingDecision,
    activity_id: &'a ActivityId,
    execution_context: ExecutionContext,
    deadline: Option<Instant>,
    resolved_session_token: Option<SessionToken>,
    throughput_control: Option<ResolvedThroughputControl>,
}

/// Builds a `TransportRequest` from the operation and routing decision.
///
/// If `resolved_session_token` is provided, it is added to the request headers.
/// Override headers from `overrides` are applied after operation headers, so they
/// take precedence.
fn build_transport_request(
    operation: &CosmosOperation,
    overrides: &OperationOverrides,
    custom_headers: Option<&std::collections::HashMap<HeaderName, HeaderValue>>,
    ctx: &TransportRequestContext<'_>,
) -> crate::error::Result<TransportRequest> {
    let paths = operation.compute_resource_paths();
    let url = {
        let mut base = ctx.routing.selected_url.clone();
        let request_path = paths.request_path();
        let normalized = if request_path.starts_with('/') {
            request_path.to_string()
        } else if request_path.is_empty() {
            String::new()
        } else {
            format!("/{}", request_path)
        };
        base.set_path(&normalized);
        base
    };

    let method = operation.operation_type().http_method();
    let resource_type = operation.resource_type();
    // Move `paths` into AuthorizationContext so the signing link is a zero-copy
    // sub-slice of the path buffer — no additional string allocation needed.
    let auth_context = AuthorizationContext::from_paths(method, resource_type, paths);

    // Build headers from the operation.
    // Custom headers are inserted first so that SDK-set headers below always
    // take precedence on conflicts (matching the SDK's ItemOptions::apply_headers
    // pattern where custom headers are added before SDK headers).
    let mut headers = azure_core::http::headers::Headers::new();
    if let Some(custom) = custom_headers {
        for (name, value) in custom {
            headers.insert(name.clone(), value.clone());
        }
    }
    operation.request_headers().write_to_headers(&mut headers);

    // Add activity ID if not already set by the operation
    if operation.request_headers().activity_id.is_none() {
        headers.insert(
            HeaderName::from_static("x-ms-activity-id"),
            HeaderValue::from(ctx.activity_id.as_str().to_owned()),
        );
    }

    // Apply operation type-specific headers.
    match operation.operation_type() {
        OperationType::Upsert => {
            headers.insert(
                HeaderName::from_static(request_header_names::IS_UPSERT),
                HeaderValue::from_static("true"),
            );
        }
        OperationType::Batch => {
            headers.insert(
                HeaderName::from_static(request_header_names::IS_BATCH_REQUEST),
                HeaderValue::from_static("True"),
            );
            headers.insert(
                HeaderName::from_static(request_header_names::BATCH_ATOMIC),
                HeaderValue::from_static("True"),
            );
            headers.insert(
                HeaderName::from_static(request_header_names::BATCH_CONTINUE_ON_ERROR),
                HeaderValue::from_static("False"),
            );
        }
        OperationType::Query | OperationType::SqlQuery => {
            headers.insert(
                HeaderName::from_static(request_header_names::IS_QUERY),
                HeaderValue::from_static("True"),
            );
            headers.insert(
                azure_core::http::headers::CONTENT_TYPE,
                HeaderValue::from_static(QUERY_CONTENT_TYPE),
            );
        }
        OperationType::QueryPlan => {
            headers.insert(
                HeaderName::from_static(request_header_names::IS_QUERY),
                HeaderValue::from_static("True"),
            );
            headers.insert(
                azure_core::http::headers::CONTENT_TYPE,
                HeaderValue::from_static(QUERY_CONTENT_TYPE),
            );
            headers.insert(
                HeaderName::from_static(request_header_names::IS_QUERY_PLAN_REQUEST),
                HeaderValue::from_static("True"),
            );
        }
        _ => {}
    }

    // Add operation type header for fault injection rule matching
    #[cfg(feature = "fault_injection")]
    {
        if let Some(fault_op) =
            crate::fault_injection::FaultOperationType::from_operation_and_resource(
                &operation.operation_type(),
                &operation.resource_type(),
            )
        {
            crate::driver::transport::cosmos_headers::apply_fault_injection_operation_tag(
                &mut headers,
                fault_op,
            );
        }
    }

    // Apply overrides — these take precedence over operation-level headers
    // (e.g., an override partition key replaces the operation's partition key).
    overrides.apply_headers(&mut headers)?;

    // Add resolved session token
    if let Some(token) = &ctx.resolved_session_token {
        headers.insert(
            request_header_names::SESSION_TOKEN,
            HeaderValue::from(token.as_str().to_owned()),
        );
    }

    // Add throughput control headers, if any layer (direct override or
    // resolved group) produced a value.
    if let Some(throughput_control) = ctx.throughput_control {
        if let Some(priority) = throughput_control.priority_level {
            headers.insert(
                request_header_names::PRIORITY_LEVEL,
                HeaderValue::from(priority.as_str().to_owned()),
            );
        }
        if let Some(bucket) = throughput_control.throughput_bucket {
            headers.insert(
                request_header_names::THROUGHPUT_BUCKET,
                HeaderValue::from(bucket.to_string()),
            );
        }
    }

    Ok(TransportRequest {
        method,
        endpoint: ctx.routing.endpoint.clone(),
        url,
        headers,
        body: operation.body().map(azure_core::Bytes::copy_from_slice),
        auth_context,
        execution_context: ctx.execution_context,
        deadline: ctx.deadline,
    })
}

/// Builds a `CosmosResponse` from a successful `TransportResult`.
fn build_cosmos_response(
    result: Box<TransportResult>,
    mut diagnostics: DiagnosticsContextBuilder,
) -> crate::error::Result<CosmosResponse> {
    match result.outcome {
        TransportOutcome::Success {
            status,
            cosmos_headers,
            body,
        } => {
            diagnostics.set_operation_status(status.status_code(), status.sub_status());

            let diagnostics_ctx = Arc::new(diagnostics.complete());

            Ok(CosmosResponse::new(
                body,
                cosmos_headers,
                status,
                diagnostics_ctx,
            ))
        }
        _ => {
            // This should only be called with a Complete(Success) result.
            // Treat as a programmer-error invariant violation.
            Err(crate::error::CosmosError::builder()
                .with_status(crate::error::CosmosStatus::CLIENT_BUILD_RESPONSE_INVOKED_ON_FAILURE)
                .with_message("build_cosmos_response called with non-success result")
                .build())
        }
    }
}

/// Determines whether a session token should be captured from this response.
///
/// Follows Java/.NET patterns: capture on success (2xx), and on error responses
/// where the server still advanced the session token:
/// - 409 Conflict
/// - 412 Precondition Failed
/// - 404 when substatus is NOT ReadSessionNotAvailable (1002)
///
/// Does NOT capture on 404/1002 (that's the trigger for session retry/clear).
fn should_capture_session_token_from_status(
    substatus: Option<&SubStatusCode>,
    outcome: &TransportOutcome,
) -> bool {
    match outcome {
        TransportOutcome::Success { .. } => true,
        TransportOutcome::HttpError { status, .. } => {
            let code = status.status_code();
            if code == azure_core::http::StatusCode::Conflict
                || code == azure_core::http::StatusCode::PreconditionFailed
            {
                return true;
            }
            if code == azure_core::http::StatusCode::NotFound {
                // Capture on 404 unless substatus is ReadSessionNotAvailable (1002)
                return substatus != Some(&SubStatusCode::READ_SESSION_NOT_AVAILABLE);
            }
            false
        }
        _ => false,
    }
}

// ── Pipeline stage helpers ────────────────────────────────────────────
//
// These pure (or narrowly-scoped) helpers carry the per-stage logic for
// `execute_operation_pipeline` so the main loop body stays readable and
// each stage can be unit-tested in isolation.

/// Maps the current retry counts to the `ExecutionContext` value that the
/// transport pipeline expects for diagnostics annotation.
///
/// - First attempt (no failover, no session retry) → `Initial`
/// - Any session retry in progress → `Retry`
/// - Otherwise (a failover retry) → `RegionFailover`
///
/// Session-retry takes precedence over failover-retry because in the rare
/// case where both counters are non-zero, the most recent advance was the
/// session retry (failover counters are not reset on session retry, but the
/// session retry happens later in the loop).
fn compute_execution_context(retry_state: &OperationRetryState) -> ExecutionContext {
    if retry_state.failover_retry_count == 0 && retry_state.session_token_retry_count == 0 {
        ExecutionContext::Initial
    } else if retry_state.session_token_retry_count > 0 {
        ExecutionContext::Retry
    } else {
        ExecutionContext::RegionFailover
    }
}

/// Conditionally emits the `x-ms-cosmos-hub-region-processing-only: True`
/// header on the outbound transport request when the latch on
/// `retry_state` is set.
///
/// Extracted as a free function (rather than left inline at the call site
/// in `execute_operation_pipeline`) so that the emission rule can be
/// exercised by unit tests without spinning up the full pipeline. The
/// production call site is the loop iteration after `build_transport_request`
/// and before `apply_optional_request_headers`.
///
/// See `try_handle_read_session_not_available` for the latch trigger.
/// When a hedge race is in flight, the per-state latch is OR'd against
/// the cross-hedge `shared_hub_region_latch` so all hedge legs emit the
/// header once any one of them has observed a 1002.
fn apply_hub_region_header(
    transport_request: &mut TransportRequest,
    retry_state: &OperationRetryState,
) {
    if should_emit_hub_region_header(
        retry_state.hub_region_processing_only,
        retry_state.shared_hub_region_latch.as_ref(),
    ) {
        transport_request.headers.insert(
            HeaderName::from_static(request_header_names::HUB_REGION_PROCESSING_ONLY),
            HeaderValue::from_static("True"),
        );
    }
}

/// Returns `true` when the `x-ms-cosmos-hub-region-processing-only`
/// header should be emitted on a transport request.
///
/// Emission is the OR of the per-state latch (set by
/// `build_session_retry_state` on the first 1002 of a single-master
/// data-plane operation) and the shared latch (set by any sibling
/// hedge inside the same `execute_hedged` fan-out). The shared latch
/// is read with `Acquire` ordering, pairing with the `Release` store
/// in `build_session_retry_state`. When the shared latch is absent
/// (`None` — the non-hedged pipeline and the zero-overhead happy
/// path), the rule collapses to the per-state behavior.
fn should_emit_hub_region_header(
    per_state_latched: bool,
    shared_latch: Option<&Arc<AtomicBool>>,
) -> bool {
    per_state_latched || shared_latch.is_some_and(|s| s.load(Ordering::Acquire))
}

/// Returns `true` when [`execute_hedged`] should construct an
/// `Arc<AtomicBool>` shared hub-region-processing-only latch for the
/// hedge fan-out.
///
/// The latch only matters when both:
///
/// 1. **Data-plane scope** — metadata operations are scoped out,
///    mirroring the per-state latch's `is_dataplane` trigger gate.
/// 2. **Single-master account** — multi-master accounts never emit the
///    `x-ms-cosmos-hub-region-processing-only` header; a latch on a
///    multi-master hedge would be inert and would waste an `Arc`
///    allocation.
///
/// Construction at the call site is further gated on the threshold
/// having elapsed, so the zero-overhead happy path (primary wins
/// pre-threshold) is preserved.
fn should_build_shared_hub_region_latch(
    pipeline_type: PipelineType,
    can_use_multiple_write_locations: bool,
) -> bool {
    pipeline_type.is_data_plane() && !can_use_multiple_write_locations
}

/// Emits `x-ms-cosmos-allow-tentative-writes: true` on writes when the account
/// is multi-write. Without this header, satellite write regions reject writes
/// with `403 / 3 (WriteForbidden)` because the request is treated as
/// single-master traffic to a non-primary region. The header is gated on
/// `enableMultipleWriteLocations` from the account metadata.
fn apply_tentative_writes_header(
    transport_request: &mut TransportRequest,
    operation: &CosmosOperation,
    multiple_write_locations_enabled: bool,
) {
    if multiple_write_locations_enabled && !operation.is_read_only() {
        transport_request.headers.insert(
            HeaderName::from_static(request_header_names::ALLOW_TENTATIVE_WRITES),
            HeaderValue::from_static("true"),
        );
    }
}

/// Applies operation-options-driven request headers that are only known
/// after the request has been built by `build_transport_request`.
///
/// Two concerns are layered here, in this order:
///
/// 1. **content-response-on-write**: For non-read operations whose
///    `content_response_on_write` is `None` (default) or `Disabled`,
///    inject `Prefer: return=minimal` so the service suppresses the
///    response body. Reads always need the body and are unaffected.
/// 2. **custom_headers**: Pass-through of caller-supplied headers, but
///    only when no SDK-set header with the same name already exists —
///    SDK headers always take precedence.
fn apply_optional_request_headers(
    transport_request: &mut TransportRequest,
    operation: &CosmosOperation,
    options: &OperationOptionsView<'_>,
) {
    if !operation.operation_type().is_read_only()
        && !matches!(
            options.content_response_on_write(),
            Some(&crate::options::ContentResponseOnWrite::Enabled)
        )
    {
        transport_request.headers.insert(
            request_header_names::PREFER,
            HeaderValue::from_static("return=minimal"),
        );
    }

    if let Some(custom_headers) = options.custom_headers() {
        for (name, value) in custom_headers {
            if !transport_request.headers.iter().any(|(n, _)| n == name) {
                transport_request
                    .headers
                    .insert(name.clone(), value.clone());
            }
        }
    }
}

/// Sleeps for the failover-retry delay if one was requested.
///
/// Treats `None` and zero-duration delays as no-ops so callers don't have
/// to repeat that guard themselves. Conversion to `azure_core::time::Duration`
/// is performed once; if it fails (e.g., overflow) the sleep is silently
/// skipped because a too-large delay is no worse than no delay at all.
async fn apply_failover_delay(delay: Option<Duration>) {
    let Some(delay) = delay else {
        return;
    };
    if delay.is_zero() {
        return;
    }
    if let Ok(duration) = azure_core::time::Duration::try_from(delay) {
        azure_core::sleep(duration).await;
    }
}

/// Advances `retry_state`, preserving deferred write effects across the snapshot swap.
///
/// Note: a generation bump can rebase to position 1 and retry the just-failed region once.
fn advance_to_next_attempt(
    retry_state: &mut OperationRetryState,
    new_state: OperationRetryState,
    location_state_store: &LocationStateStore,
    is_read_only: bool,
) {
    let next_location = location_state_store.snapshot();
    let endpoints_len =
        preferred_endpoints_for_attempt(next_location.account.as_ref(), &new_state, is_read_only)
            .len();
    let pending = std::mem::take(&mut retry_state.pending_write_effects);
    *retry_state = new_state.advance_location(endpoints_len, next_location.account.generation);
    retry_state.pending_write_effects = pending;
}

/// Returns `Err` with a `RequestTimeout`-coded error if the end-to-end
/// deadline has been reached, otherwise `Ok(())`.
///
/// On timeout, the diagnostics builder is updated with
/// `RequestTimeout` + `CLIENT_OPERATION_TIMEOUT` so downstream telemetry
/// Enforces the operation's end-to-end deadline, surfacing a typed
/// `408 / CLIENT_OPERATION_TIMEOUT` error when exceeded so callers
/// can distinguish a client-side end-to-end timeout from a service 408.
///
/// Takes the [`DiagnosticsContextBuilder`] by value so the timeout-error
/// path can finalize diagnostics and graft them onto the synthesized
/// error in one step (without that graft, callers reading
/// `error.diagnostics()` would see `None` on every end-to-end-timeout
/// outcome even though the pipeline tracked every attempt). The builder
/// is returned unchanged on the happy path so the caller can keep
/// mutating it on subsequent iterations.
fn enforce_deadline_or_timeout(
    deadline: Option<Instant>,
    options: &OperationOptionsView<'_>,
    mut diagnostics: DiagnosticsContextBuilder,
) -> Result<DiagnosticsContextBuilder, crate::error::CosmosError> {
    let Some(d) = deadline else {
        return Ok(diagnostics);
    };
    if Instant::now() < d {
        return Ok(diagnostics);
    }

    let timeout_duration = options
        .end_to_end_latency_policy()
        .map(|p| p.timeout())
        .unwrap_or_default();

    diagnostics.set_operation_status(
        azure_core::http::StatusCode::RequestTimeout,
        Some(SubStatusCode::CLIENT_OPERATION_TIMEOUT),
    );
    let diagnostics_ctx = Arc::new(diagnostics.complete());
    Err(crate::error::CosmosError::builder()
        .with_status(crate::models::CosmosStatus::from_parts(
            azure_core::http::StatusCode::RequestTimeout,
            Some(SubStatusCode::CLIENT_OPERATION_TIMEOUT),
        ))
        .with_message(format!(
            "end-to-end operation timeout exceeded ({timeout_duration:?})"
        ))
        .with_diagnostics(diagnostics_ctx)
        .build())
}

/// On a successful PPCB probe request, removes the `ProbeCandidate` entry
/// for this partition so subsequent requests resume default routing.
///
/// Only PPCB circuit-breaker overrides use probe-based failback. PPAF
/// overrides persist until the backend signals a change organically, so
/// this function is a no-op for them.
///
/// **Fast path**: skips the CAS loop entirely when no `ProbeCandidate`
/// entry exists for this partition, avoiding an expensive full-state
/// clone on every successful request (the overwhelmingly common case).
///
/// **TOCTOU guard**: re-checks the `ProbeCandidate` status inside the CAS
/// closure. If another thread transitions the entry to `Unhealthy` between
/// the snapshot check and the CAS, the unhealthy entry must not be removed.
fn try_cleanup_probe_candidate(
    retry_state: &OperationRetryState,
    location_state_store: &LocationStateStore,
) {
    let Some(pk_range_id) = &retry_state.partition_key_range_id else {
        return;
    };

    let snapshot = location_state_store.snapshot();
    let needs_cleanup = snapshot
        .partitions
        .circuit_breaker_overrides
        .get(pk_range_id.as_str())
        .is_some_and(|e| e.health_status == HealthStatus::ProbeCandidate);
    if !needs_cleanup {
        return;
    }

    location_state_store.apply_partition(|current| {
        let is_probe = current
            .circuit_breaker_overrides
            .get(pk_range_id.as_str())
            .is_some_and(|e| e.health_status == HealthStatus::ProbeCandidate);
        if is_probe {
            remove_probe_succeeded_entry(current, pk_range_id)
        } else {
            current.clone()
        }
    });
}

// ── Hedging dispatch (Part 4b) ────────────────────────────────────────
//
// `maybe_upgrade_to_hedge` + `AttemptContext` + `perform_single_attempt`
// + `execute_hedged` together implement the cross-region hedging race:
//
//  1. After `evaluate_transport_result` returns a per-attempt action,
//     `maybe_upgrade_to_hedge` rewrites a same-pipeline retry into
//     `OperationAction::Hedge` when the operation is hedge-eligible.
//  2. The STAGE 7 `Hedge` arm bundles the per-operation shared state
//     into `AttemptContext` and calls `execute_hedged`.
//  3. `execute_hedged` fires the primary attempt immediately, races it
//     against the threshold timer (zero-overhead happy path when the
//     primary completes first), then spawns the secondary and races
//     primary vs secondary. The first final result wins; a retriable
//     failure on either side keeps the other side racing.
//
// Diagnostics: each hedge attempt records into its own sub-builder
// cloned from the parent via `clone_for_hedge_attempt`. After the race
// resolves the surviving sub-builders are merged back into the parent
// via `merge_hedge_attempt`, and the winning side's `HedgeDiagnostics`
// is attached via `set_hedge_diagnostics`. Loser futures dropped by the
// race never merge — their request diagnostics are intentionally
// discarded.

/// Dispatches a hedge-race outcome to the [`LocationStateStore`]'s
/// PPCB-feedback counters.
///
/// Feedback is keyed by `(partition, primary_region)`. When the
/// operation never resolved a partition key range ID (first attempt
/// against an unresolved item) the call is a no-op: there is no key to
/// attribute feedback against. The same gating applies to both
/// alternate-wins and primary-wins so the reset only fires on pairs
/// that could ever accumulate a count in the first place.
fn record_hedge_outcome(
    location_state_store: &LocationStateStore,
    outcome: HedgeOutcome,
    partition: Option<&PartitionKeyRangeId>,
    primary_region: Option<&Region>,
) {
    let Some(partition) = partition else {
        return;
    };
    match outcome {
        HedgeOutcome::AlternateWin => {
            location_state_store.record_consecutive_hedge_win(partition, primary_region)
        }
        HedgeOutcome::PrimaryWin => {
            location_state_store.record_primary_win(partition, primary_region)
        }
    }
}

/// Hedge race outcome reported to [`record_hedge_outcome`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HedgeOutcome {
    /// The primary attempt produced the operation result (whether
    /// pre-threshold in the zero-overhead happy path or post-threshold
    /// after racing the secondary).
    PrimaryWin,
    /// The alternate (secondary) attempt produced the operation result.
    AlternateWin,
}

/// Per-operation context shared across hedge attempts.
///
/// Bundles the read-only references that every per-attempt transport
/// invocation needs.
struct AttemptContext<'a> {
    operation: &'a CosmosOperation,
    /// Per-operation header/body overrides applied by
    /// [`build_transport_request`] (e.g., PK-range-id targeting for
    /// query/feed operations dispatched against a specific partition).
    /// Carried so hedge legs in [`execute_hedged`] / [`perform_single_attempt`]
    /// rebuild the request identically to the main pipeline's STAGE 3.
    overrides: &'a OperationOverrides,
    custom_headers: Option<&'a std::collections::HashMap<HeaderName, HeaderValue>>,
    transport: &'a CosmosTransport,
    account_endpoint: &'a AccountEndpoint,
    credential: &'a Credential,
    user_agent: &'a azure_core::http::headers::HeaderValue,
    activity_id: &'a ActivityId,
    pipeline_type: PipelineType,
    transport_security: TransportSecurity,
    session_manager: &'a SessionManager,
    /// Whether session consistency is in effect for this operation
    /// (drives session-token resolve/capture inside the attempt).
    session_consistency_active: bool,
    options: &'a OperationOptionsView<'a>,
    throughput_control: Option<ResolvedThroughputControl>,
    /// End-to-end deadline (operation timeout) — passed through to each
    /// per-attempt transport invocation.
    deadline: Option<Instant>,
    /// Original configured timeout (the value used to derive `deadline`).
    /// Carried so [`execute_hedged`] can compute the effective harvest
    /// window via [`effective_harvest_window`].
    configured_request_timeout: Option<Duration>,
    /// Whether this operation runs against a multi-master account.
    /// Used by [`execute_hedged`] to gate construction of the shared
    /// hub-region-processing-only latch (the latch is only meaningful
    /// on single-master data-plane operations).
    can_use_multiple_write_locations: bool,
    /// Current value of the per-state `hub_region_processing_only`
    /// latch at the moment hedging upgraded from `FailoverRetry` /
    /// `SessionRetry`. Used by [`execute_hedged`] to seed the shared
    /// `Arc<AtomicBool>` so a 1002 already discovered by the main
    /// pipeline before hedging fired carries forward into both hedge
    /// attempts.
    hub_region_processing_only_initial: bool,
    /// Identifies the physical partition serving this operation. Used by
    /// [`execute_hedged`] to attribute hedge-win signals back to the
    /// `(partition, primary_region)` pair consumed by PPCB feedback.
    /// `None` for operations dispatched before any response captured the
    /// partition key range ID (first attempt of an unresolved item) —
    /// in that case no feedback can be attributed and the recorder calls
    /// become no-ops.
    partition_key_range_id: Option<PartitionKeyRangeId>,
    /// Sink for hedge-outcome feedback (PPCB counters keyed by
    /// `(partition, primary_region)`). Held as a borrow so
    /// [`execute_hedged`] can hand it through [`record_hedge_outcome`]
    /// at each of the four race-outcome branches without cloning the
    /// `Arc` on every operation.
    location_state_store: &'a LocationStateStore,
}

/// Result classification used by [`execute_hedged`] to decide whether a
/// completed hedge attempt terminates the race or keeps the other side
/// running.
///
/// `Final` carries the [`TransportResult`] that becomes the operation's
/// outcome (success or final-classified HTTP error). `Transient`
/// indicates the attempt should be ignored in favor of the other side
/// (5xx / 429 / 408 / 410 / 404-1002 / 403-with-sub / transport error /
/// deadline) — when both sides land retriable, the most recent error
/// is surfaced as the operation error.
enum HedgeClass {
    Final(Box<TransportResult>),
    Transient,
}

/// Pure classifier for a per-attempt result.
///
/// `Err` (e.g. failure constructing the request) and any non-final
/// TransportOutcome map to `Transient`. A `Success` is always final; an
/// `HttpError` is final iff [`CosmosStatus::is_final_result`] returns `true` for its
/// status.
fn classify_hedge_result(result: crate::error::Result<TransportResult>) -> HedgeClass {
    match result {
        Ok(tr) => match &tr.outcome {
            TransportOutcome::Success { .. } => HedgeClass::Final(Box::new(tr)),
            TransportOutcome::HttpError { status, .. } => {
                if status.is_final_result() {
                    HedgeClass::Final(Box::new(tr))
                } else {
                    HedgeClass::Transient
                }
            }
            TransportOutcome::TransportError { .. } | TransportOutcome::DeadlineExceeded { .. } => {
                HedgeClass::Transient
            }
        },
        Err(_) => HedgeClass::Transient,
    }
}

/// Non-consuming version of [`classify_hedge_result`] for the
/// pre-threshold primary-completion branch, where the caller still
/// needs the original `TransportResult` to surface the response via
/// [`finalize_hedge_attempt`] but only wants to know whether the
/// primary's outcome was `Final` for [`record_hedge_outcome`] gating.
///
/// Returns `true` iff a `Success` or an `HttpError` whose status passes
/// [`CosmosStatus::is_final_result`]. Mirrors `classify_hedge_result` exactly — keep
/// the two in lockstep.
fn result_is_final(tr: &TransportResult) -> bool {
    match &tr.outcome {
        TransportOutcome::Success { .. } => true,
        TransportOutcome::HttpError { status, .. } => status.is_final_result(),
        TransportOutcome::TransportError { .. } | TransportOutcome::DeadlineExceeded { .. } => {
            false
        }
    }
}

/// Peeks at a hedge-leg's [`TransportResult`] for the partition-key-range-id
/// header without consuming the result.
///
/// The non-hedged STAGE 4 captures this id on first observation by
/// pulling it out of `result.cosmos_headers()` and stashing it on
/// `OperationRetryState::partition_key_range_id`. Hedge legs never
/// performed the equivalent capture, so when [`execute_hedged`] returned
/// [`HedgedRaceResult::BothTransient`] the surrounding loop re-entered
/// with `retry_state.partition_key_range_id = None` even though one or
/// both legs had received responses that carried the id. Subsequent
/// PPCB feedback then short-circuited (`record_hedge_outcome` no-ops on
/// `partition.is_none()`) and partition-level overrides could not be
/// installed for later failures.
///
/// Called at each `classify_hedge_result` site in [`execute_hedged`] to
/// accumulate the first non-`None` id observed across either leg, which
/// is then surfaced via
/// [`HedgedRaceResult::BothTransient::partition_key_range_id`] for the
/// caller to write back into `retry_state` before the loop re-enters.
fn pk_range_id_from_result(
    result: &crate::error::Result<TransportResult>,
) -> Option<PartitionKeyRangeId> {
    result
        .as_ref()
        .ok()
        .and_then(|tr| tr.cosmos_headers())
        .and_then(|headers| headers.partition_key_range_id.as_deref())
        .map(|s| PartitionKeyRangeId::from(s.to_owned()))
}

/// Converts a final-classified [`TransportResult`] (success or final HTTP
/// error) into the response shape that `execute_operation_pipeline` would
/// otherwise return from STAGE 7's `Complete` or `Abort` arms.
///
/// `Success` flows through [`build_cosmos_response`] exactly like the
/// non-hedged happy path. A final `HttpError` (e.g. 409 Conflict) is
/// converted to an `azure_core::Error` via the same `build_http_error`
/// the evaluator uses for the non-hedged `Abort` path, so callers cannot
/// observe a behavioral difference between hedged and non-hedged final
/// HTTP errors. Transient outcomes are converted to a generic error —
/// reaching this function with a transient outcome would be a programmer
/// error in `execute_hedged` (the race loop only calls this on `Final`
/// classifications and on the "both transient" fallback where the diff
/// between calling and not is one branch).
///
/// # Diagnostics-on-error
///
/// Every `Err`-producing arm grafts the operation's
/// `DiagnosticsContextBuilder` onto the returned error via
/// `CosmosErrorBuilder::from_error(...).with_diagnostics(...)` so
/// callers reading `error.diagnostics()` see the full
/// per-attempt request chain — operators investigating "why didn't
/// hedging save me?" need the diagnostics on hedge-terminal errors
/// even more than the non-hedged path, because the operator paid
/// for two regions of requests on a final error.
fn finalize_hedge_attempt(
    result: Box<TransportResult>,
    diagnostics: DiagnosticsContextBuilder,
) -> crate::error::Result<CosmosResponse> {
    match result.outcome {
        outcome @ TransportOutcome::Success { .. } => {
            build_cosmos_response(Box::new(TransportResult { outcome }), diagnostics)
        }
        TransportOutcome::HttpError {
            status,
            cosmos_headers,
            body,
            ..
        } => {
            tracing::warn!(
                activity_id = %diagnostics.activity_id(),
                request_count = diagnostics.request_count(),
                http_status = u16::from(status.status_code()),
                sub_status = ?status.sub_status(),
                "cosmos.hedge.terminal_http_error",
            );
            let diagnostics_ctx = Arc::new(diagnostics.complete());
            let base = build_service_error(&status, &cosmos_headers, &body);
            Err(crate::error::CosmosErrorBuilder::from_error(base)
                .with_diagnostics(diagnostics_ctx)
                .build())
        }
        TransportOutcome::TransportError { error, .. } => {
            tracing::warn!(
                activity_id = %diagnostics.activity_id(),
                request_count = diagnostics.request_count(),
                error = %error,
                "cosmos.hedge.terminal_transport_error",
            );
            let diagnostics_ctx = Arc::new(diagnostics.complete());
            Err(crate::error::CosmosErrorBuilder::from_error(error)
                .with_diagnostics(diagnostics_ctx)
                .build())
        }
        TransportOutcome::DeadlineExceeded { .. } => {
            tracing::warn!(
                activity_id = %diagnostics.activity_id(),
                request_count = diagnostics.request_count(),
                "cosmos.hedge.terminal_deadline_exceeded",
            );
            // Typed status (408 + CLIENT_OPERATION_TIMEOUT) mirrors
            // `enforce_deadline_or_timeout` so retry-evaluation and
            // telemetry treat hedged deadline-exceeded identically to
            // non-hedged.
            let mut diagnostics = diagnostics;
            diagnostics.set_operation_status(
                azure_core::http::StatusCode::RequestTimeout,
                Some(SubStatusCode::CLIENT_OPERATION_TIMEOUT),
            );
            let diagnostics_ctx = Arc::new(diagnostics.complete());
            Err(crate::error::CosmosError::builder()
                .with_status(crate::models::CosmosStatus::from_parts(
                    azure_core::http::StatusCode::RequestTimeout,
                    Some(SubStatusCode::CLIENT_OPERATION_TIMEOUT),
                ))
                .with_message("deadline exceeded during hedged attempt")
                .with_diagnostics(diagnostics_ctx)
                .build())
        }
    }
}

/// If `action` is a same-pipeline retry and the operation is eligible
/// for cross-region hedging, rewrites it to `OperationAction::Hedge`.
/// Otherwise returns `action` unchanged.
///
/// Only `FailoverRetry` and `SessionRetry` are eligible for upgrade —
/// `Complete` is the operation's terminal success path, and `Abort`
/// already signals a non-retryable error. `request_timeout` is passed to
/// [`evaluate_hedge_eligibility`] so it can compute the driver default
/// threshold (`min(1000ms, request_timeout / 2)`).
///
/// Forwards the incoming variant's `new_state` into the rewritten
/// `Hedge` variant so STAGE 7 can apply it to the live `retry_state`
/// before building `AttemptContext` — see
/// `OperationAction::Hedge::new_state`.
fn maybe_upgrade_to_hedge(
    action: OperationAction,
    operation: &CosmosOperation,
    options: &OperationOptionsView<'_>,
    account_state: &AccountEndpointState,
    primary: &RoutingDecision,
    request_timeout: Option<Duration>,
) -> OperationAction {
    // Extract `new_state` from the retry-upgrade-eligible variants;
    // return everything else unchanged.
    let new_state = match &action {
        OperationAction::FailoverRetry { new_state, .. } => new_state.clone(),
        OperationAction::SessionRetry { new_state } => new_state.clone(),
        _ => return action,
    };

    match evaluate_hedge_eligibility(operation, options, account_state, primary, request_timeout) {
        Some(upgrade) => {
            // Hedge consumes two failover-budget slots on the race
            // (primary + secondary) and a third on BothTransient
            // advance. If fewer than two slots remain, stay on the
            // non-hedged path so the remaining budget is spent on
            // sequential failovers.
            if new_state.failover_retry_count.saturating_add(2) > new_state.max_failover_retries {
                tracing::debug!(
                    failover_retry_count = new_state.failover_retry_count,
                    max_failover_retries = new_state.max_failover_retries,
                    "cosmos.hedge.budget_exhausted_skipping_upgrade",
                );
                return action;
            }
            // Emit a structured event when an operation is upgraded
            // into the hedge race. Fields mirror the inputs that drove
            // the eligibility decision so operators can correlate
            // threshold tuning with observed upgrades.
            tracing::debug!(
                threshold_ms = upgrade.threshold.get().as_millis() as u64,
                primary_region = ?primary.endpoint.region().map(crate::options::Region::as_str),
                secondary_region = ?upgrade.secondary_routing.endpoint.region().map(crate::options::Region::as_str),
                hub_region_processing_only = new_state.hub_region_processing_only,
                "cosmos.hedge.enabled_for_operation",
            );
            OperationAction::Hedge {
                secondary_routing: upgrade.secondary_routing,
                threshold: upgrade.threshold,
                strategy_config: upgrade.strategy_config,
                new_state,
            }
        }
        None => action,
    }
}

/// Runs a single transport attempt against `routing` and returns the raw
/// [`TransportResult`]. Mirrors STAGE 3 + STAGE 4 + STAGE 4b of the main
/// operation loop, but operates on a pre-built routing so the call site
/// (`execute_hedged`) can use the same code path for both primary and
/// secondary hedge attempts.
///
/// Not invoked by the main pipeline loop today — the loop body inlines
/// the same STAGE 3/4/4b code for compatibility and to keep the
/// hedging diff focused. A follow-up refactor may collapse the
/// duplication.
///
/// Differences from the inline loop body:
///
/// - **No per-state `hub_region_processing_only` latch.** Each hedge
///   today runs a single transport attempt with no retry loop, so the
///   per-state latch has nothing to drive. The cross-hedge shared
///   latch is plumbed through `shared_hub_region_latch` instead — the
///   secondary reads it on its first request so a 1002 latched by the
///   main pipeline (before hedging upgraded) immediately gets the
///   `x-ms-cosmos-hub-region-processing-only` header.
/// - **No `partition_key_range_id` capture.** The PK range ID is already
///   known to the surrounding `execute_operation_pipeline` (the
///   triggering attempt populated it) and is read-only inside a hedge.
async fn perform_single_attempt(
    ctx: &AttemptContext<'_>,
    routing: &RoutingDecision,
    execution_context: ExecutionContext,
    shared_hub_region_latch: Option<&Arc<AtomicBool>>,
    diagnostics: &mut DiagnosticsContextBuilder,
) -> crate::error::Result<TransportResult> {
    // Resolve session token using the same precedence the main loop uses.
    let resolved_session_token = ctx
        .session_consistency_active
        .then(|| {
            ctx.session_manager.resolve_session_token(
                ctx.operation,
                ctx.operation.request_headers().session_token.as_ref(),
            )
        })
        .flatten();

    let request_ctx = TransportRequestContext {
        routing,
        activity_id: ctx.activity_id,
        execution_context,
        deadline: ctx.deadline,
        resolved_session_token,
        throughput_control: ctx.throughput_control,
    };

    let mut transport_request = build_transport_request(
        ctx.operation,
        ctx.overrides,
        ctx.custom_headers,
        &request_ctx,
    )?;
    // Hedging attempts have no per-state latch to consult — the only
    // signal is the cross-hedge shared latch.
    if should_emit_hub_region_header(false, shared_hub_region_latch) {
        transport_request.headers.insert(
            HeaderName::from_static(request_header_names::HUB_REGION_PROCESSING_ONLY),
            HeaderValue::from_static("True"),
        );
    }
    apply_optional_request_headers(&mut transport_request, ctx.operation, ctx.options);

    let selected_transport = match ctx.pipeline_type {
        PipelineType::DataPlane => ctx
            .transport
            .get_dataplane_transport(ctx.account_endpoint, routing.transport_mode)?,
        PipelineType::Metadata => ctx.transport.get_metadata_transport(ctx.account_endpoint)?,
    };

    // Resolve the per-leg throttle (429) retry budget from the same effective
    // options the main pipeline uses, so a hedge leg honors the configured
    // `ThrottlingRetryOptions` identically to a non-hedged attempt. Each leg
    // enters the transport pipeline once and starts with a fresh budget.
    let throttling_retry_options = ctx.options.throttling_retry_options();
    let max_throttle_attempts = throttling_retry_options
        .max_retry_count()
        .copied()
        .unwrap_or(DEFAULT_MAX_THROTTLE_ATTEMPTS);
    let max_throttle_wait_time = throttling_retry_options
        .max_retry_wait_time()
        .copied()
        .unwrap_or(DEFAULT_MAX_THROTTLE_WAIT);

    let result = execute_transport_pipeline(
        transport_request,
        &TransportPipelineContext {
            transport: &selected_transport,
            allow_sent_transport_retry: ctx.operation.is_read_only()
                || ctx.operation.is_idempotent(),
            credential: ctx.credential,
            user_agent: ctx.user_agent,
            pipeline_type: ctx.pipeline_type,
            transport_security: ctx.transport_security,
            endpoint_key: routing.endpoint.endpoint_key(),
            max_throttle_attempts,
            max_throttle_wait_time,
        },
        diagnostics,
    )
    .await;

    // Session-token capture deliberately deferred to the winning
    // branch in `execute_hedged`. Capturing here would advance the
    // session token off the *losing* leg's response on every race,
    // which can leak stale state from a region whose mutation the
    // caller never observes. See `capture_session_token_for_winner`.
    Ok(result)
}

/// Captures the session token from a hedge race's **winning** leg's
/// response, mirroring the non-hedged STAGE 4b logic without the inline
/// capture that `perform_single_attempt` used to perform.
///
/// Called from each terminal "winner" branch in [`execute_hedged`] (the
/// pre-threshold primary win, the post-threshold primary win, and the
/// two alternate-win branches). The loser's headers are intentionally
/// discarded — advancing the operation's session token from a region
/// whose response the caller never observes would leak stale state and
/// violate read-your-writes against the winning region.
fn capture_session_token_for_winner(ctx: &AttemptContext<'_>, result: &TransportResult) {
    if !ctx.session_consistency_active {
        return;
    }
    if let Some(cosmos_headers) = result.cosmos_headers() {
        if should_capture_session_token_from_status(
            cosmos_headers.substatus.as_ref(),
            &result.outcome,
        ) {
            ctx.session_manager
                .capture_session_token(ctx.operation, cosmos_headers);
        }
    }
}

/// Upper bound on how long [`execute_hedged`] waits for in-flight hedge
/// attempts to land their diagnostics after the application-cancel
/// deadline fires. The Rust hedge path deliberately bounds this — .NET
/// v3 awaits the most-recently-completed task with no timeout, but the
/// Rust path trades slightly less-rich diagnostics-on-cancel for
/// predictable user-visible cancel latency when a transport future is
/// stuck. The effective window is further capped by
/// [`effective_harvest_window`] for callers with aggressive timeouts.
const HARVEST_WINDOW: Duration = Duration::from_millis(50);

/// Lower bound on the harvest window so an already-completed `Ready`
/// future still resolves before the timer fires on typical OSes.
const HARVEST_WINDOW_FLOOR: Duration = Duration::from_millis(1);

/// Effective harvest window for a given operation timeout:
/// `min(HARVEST_WINDOW, request_timeout / 10)`, clamped at
/// [`HARVEST_WINDOW_FLOOR`]. Returns [`HARVEST_WINDOW`] when no timeout
/// is configured. Aggressive callers (e.g. `request_timeout = 100ms`)
/// avoid a fixed 50ms cancel-latency tax.
fn effective_harvest_window(configured_request_timeout: Option<Duration>) -> Duration {
    match configured_request_timeout {
        Some(t) => HARVEST_WINDOW.min(t / 10).max(HARVEST_WINDOW_FLOOR),
        None => HARVEST_WINDOW,
    }
}

/// Discriminator returned by the Stage-2 threshold-vs-deadline nested
/// race so the outer `select` against the primary can branch cleanly
/// without unwrapping a nested [`Either`].
enum TimerEvent {
    /// The hedge threshold elapsed first — Stage 3 should launch the
    /// secondary.
    ThresholdElapsed,
    /// The end-to-end deadline elapsed first — [`execute_hedged`] should
    /// harvest the still-pending primary within [`HARVEST_WINDOW`] and
    /// re-raise an [`application_cancelled_error`].
    DeadlineFired,
}

/// Builds a future that resolves when the supplied `deadline` elapses,
/// or never resolves when `deadline` is `None`. Used by [`execute_hedged`]
/// to layer end-to-end-deadline observation onto its `select`-based
/// races without changing those races' shapes when no deadline is set.
fn deadline_signal(deadline: Option<Instant>) -> Pin<Box<dyn Future<Output = ()> + Send>> {
    let Some(d) = deadline else {
        return Box::pin(pending::<()>());
    };
    let remaining_std = d.saturating_duration_since(Instant::now());
    match azure_core::time::Duration::try_from(remaining_std) {
        Ok(remaining) => Box::pin(azure_core::sleep(remaining)),
        Err(_) => Box::pin(futures::future::ready(())),
    }
}

/// Races `attempt` against [`HARVEST_WINDOW`] and, if `attempt` completes
/// within the window, merges its diagnostics into `parent` so the
/// returned [`application_cancelled_error`] carries the most-advanced
/// attempt's request trail. The result itself is discarded — once the
/// application cancellation has fired the operation outcome is the
/// cancellation error regardless of whether the in-flight pipeline
/// would have produced a final response.
async fn harvest_remaining_attempt<F>(
    attempt: F,
    parent: &mut DiagnosticsContextBuilder,
    harvest_window: Duration,
) where
    F: Future<
            Output = (
                crate::error::Result<TransportResult>,
                DiagnosticsContextBuilder,
            ),
        > + Unpin
        + Send,
{
    let window = match azure_core::time::Duration::try_from(harvest_window) {
        Ok(d) => d,
        Err(_) => return,
    };
    let timer = Box::pin(azure_core::sleep(window));
    if let Either::Left(((_result, diag), _timer)) = select(attempt, timer).await {
        parent.merge_hedge_attempt(diag);
    }
    // Timer arm: harvest window exceeded; loser future is dropped and its
    // Drop chain cancels the in-flight transport.
}

/// Synthetic operation error returned by [`execute_hedged`] when the
/// application-cancellation deadline fires while one or both hedge
/// attempts are still racing. Mirrors the .NET v3 cancellation behavior
/// and `enforce_deadline_or_timeout`'s typed-status pattern.
///
/// Takes the [`DiagnosticsContextBuilder`] by value so the cancel-error
/// path can finalize diagnostics and graft them onto the synthesized
/// error in one step — without that graft, callers reading
/// `error.diagnostics()` would see `None` on every hedge-cancel
/// outcome even though the pipeline tracked every attempt and harvested
/// the most-advanced in-flight leg within [`HARVEST_WINDOW`].
///
/// Status is set to `408 RequestTimeout` + `CLIENT_OPERATION_TIMEOUT`
/// (20008) so callers and telemetry can discriminate a client-side
/// hedge cancel from a service-returned 408.
fn application_cancelled_error(
    mut diagnostics: DiagnosticsContextBuilder,
) -> crate::error::CosmosError {
    diagnostics.set_operation_status(
        azure_core::http::StatusCode::RequestTimeout,
        Some(SubStatusCode::CLIENT_OPERATION_TIMEOUT),
    );
    let diagnostics_ctx = Arc::new(diagnostics.complete());
    crate::error::CosmosError::builder()
        .with_status(crate::models::CosmosStatus::from_parts(
            azure_core::http::StatusCode::RequestTimeout,
            Some(SubStatusCode::CLIENT_OPERATION_TIMEOUT),
        ))
        .with_message("operation cancelled by application deadline during cross-region hedging")
        .with_diagnostics(diagnostics_ctx)
        .build()
}

/// Races a still-pending hedge attempt against the end-to-end deadline.
/// Returns `Some(result)` when the attempt completes first (normal
/// path); returns `None` after harvesting the attempt's diagnostics
/// within [`HARVEST_WINDOW`] when the deadline wins.
///
/// Used by [`execute_hedged`] in Stage 4's transient-fallthrough
/// branches where one side has already classified as transient and the
/// loop is `.await`-ing the other side — without this wrap a stuck
/// transport future would block the operation past the deadline.
async fn await_attempt_or_deadline_harvest<F>(
    attempt: F,
    deadline: Option<Instant>,
    parent: &mut DiagnosticsContextBuilder,
    harvest_window: Duration,
) -> Option<(
    crate::error::Result<TransportResult>,
    DiagnosticsContextBuilder,
)>
where
    F: Future<
            Output = (
                crate::error::Result<TransportResult>,
                DiagnosticsContextBuilder,
            ),
        > + Unpin
        + Send,
{
    let deadline_fut = deadline_signal(deadline);
    match select(attempt, deadline_fut).await {
        Either::Left((result, _deadline)) => Some(result),
        Either::Right(((), remaining)) => {
            harvest_remaining_attempt(remaining, parent, harvest_window).await;
            None
        }
    }
}

/// Returns `true` when `deadline` has elapsed relative to "now". A
/// `None` deadline never elapses. Used by [`execute_hedged`]'s
/// terminal both-transient branches to choose between surfacing
/// [`application_cancelled_error`] (when the deadline drove the
/// outcome) and [`transient_outcome_error`] (genuine transport-side
/// transient failure on both regions).
fn deadline_elapsed(deadline: Option<Instant>) -> bool {
    deadline.is_some_and(|d| Instant::now() >= d)
}

/// Outcome of [`execute_hedged`] as observed by the surrounding
/// [`execute_operation_pipeline`] loop.
///
/// The race is structured around two qualitatively different outcomes:
///
/// - [`HedgedRaceResult::Terminal`] — the race produced a final result
///   (success, final HTTP error, or application-cancellation). The
///   operation pipeline must surface this directly to the caller. The
///   inner `Result` mirrors what the non-hedged
///   [`OperationAction::Complete`] / [`OperationAction::Abort`] arms
///   produce so STAGE 7 remains the canonical translation point.
/// - [`HedgedRaceResult::BothTransient`] — both legs returned transient
///   outcomes **and** the deadline has not elapsed. The operation
///   pipeline must consume the two regions used in the race against
///   [`OperationRetryState::failover_retry_count`] (incrementing by 2)
///   and re-enter the loop against the remaining regions. If the budget
///   is exhausted, `last_error` is surfaced as the operation's terminal
///   error.
///
/// Without this loop-fallback the hedge-eligible code path would be
/// strictly *less* resilient than the non-hedged path in multi-region
/// brown-outs: a 503 burst across the first two preferred regions of a
/// 3-region account would cause a non-hedged read to consume one
/// failover-retry slot per region and reach region 3 on the third
/// attempt, while a hedge-eligible read would burn both regions in a
/// single race and give up immediately.
#[derive(Debug)]
#[allow(
    clippy::large_enum_variant,
    reason = "single return value from an async function on a hot path; \
              boxing either variant would add a heap allocation per race \
              without enabling reuse — at most one `HedgedRaceResult` \
              exists at a time per operation."
)]
pub(crate) enum HedgedRaceResult {
    /// The race ended in a state the operation pipeline must surface
    /// directly to the caller.
    Terminal(crate::error::Result<CosmosResponse>),

    /// Both legs returned `Transient` outcomes without the deadline
    /// firing. The caller must:
    ///
    /// 1. Increment `failover_retry_count` by 2 (the race consumed two
    ///    regions).
    /// 2. If the budget is exhausted, return `last_error` as the
    ///    operation's terminal error.
    /// 3. Otherwise advance the [`LocationIndex`] past the two consumed
    ///    regions and `continue` the operation loop.
    ///
    /// `primary_region` / `secondary_region` are surfaced via tracing.
    /// `partition_key_range_id` and `observed_session_unavailable` carry
    /// state the race observed that the fallback folds back into
    /// `retry_state` before re-entering.
    ///
    /// `strategy_config` and the `*_for_diag` regions are carried so the
    /// fallback can stamp `HedgeDiagnostics::both_transient` only when the
    /// failover budget is exhausted (the terminal outcome). They are not
    /// stamped on the non-terminal path, where a later successful retry
    /// would otherwise carry a misleading `terminal_state = BothTransient`.
    BothTransient {
        primary_region: Option<Region>,
        secondary_region: Option<Region>,
        strategy_config: HedgingStrategyConfig,
        primary_region_for_diag: Region,
        secondary_region_for_diag: Region,
        last_error: crate::error::CosmosError,
        diagnostics: DiagnosticsContextBuilder,
        partition_key_range_id: Option<PartitionKeyRangeId>,
        observed_session_unavailable: bool,
    },
}

/// Applies one hedge leg's `LocationEffect`s to the shared
/// `LocationStateStore` and OR-accumulates its
/// `observed_session_unavailable` signal (also `Release`-storing the
/// shared latch on first trigger).
///
/// Called at every classify site in [`execute_hedged`] so the hedged
/// path's routing-state and hub-region-latch mutations stay symmetric
/// with the non-hedged `evaluate_transport_result` path.
async fn apply_hedge_leg_effects(
    ctx: &AttemptContext<'_>,
    retry_state_snapshot: &OperationRetryState,
    endpoint: &CosmosEndpoint,
    result: &crate::error::Result<TransportResult>,
    shared_hub_region_latch: Option<&Arc<AtomicBool>>,
    race_observed_session_unavailable: &mut bool,
) {
    // Pre-transport / request-build errors carry no `TransportResult`
    // and therefore no observable side effects to mirror — they fail
    // before the transport pipeline classifies any response.
    let Ok(transport_result) = result.as_ref() else {
        return;
    };
    let eval = evaluate_hedge_leg_effects(
        ctx.operation,
        endpoint,
        retry_state_snapshot,
        transport_result,
    );
    if !eval.effects.is_empty() {
        ctx.location_state_store.apply(&eval.effects).await;
    }
    if eval.observed_session_unavailable {
        *race_observed_session_unavailable = true;
        if let Some(latch) = shared_hub_region_latch {
            latch.store(true, Ordering::Release);
        }
    }
}

/// Races a primary attempt against a single cross-region secondary
/// attempt. Returns the first **final** result via
/// [`HedgedRaceResult::Terminal`]; surfaces a both-transient outcome via
/// [`HedgedRaceResult::BothTransient`] so the surrounding
/// [`execute_operation_pipeline`] loop can re-enter against the
/// remaining regions.
///
/// The implementation is structured as two `futures::future::select`
/// calls so the borrow checker can reclaim each sub-builder cleanly
/// as its owning future completes:
///
/// 1. **Threshold race.** The primary future is launched immediately
///    against an `azure_core::sleep(threshold)` timer. If the primary
///    completes first this is the zero-overhead happy path — no
///    secondary future is constructed, no extra diagnostics sub-builder
///    is cloned, no `Arc` allocations occur beyond what the single
///    primary attempt already needs.
/// 2. **Primary vs secondary race.** Once the timer fires we clone a
///    sub-builder for the secondary, launch it with
///    `ExecutionContext::Hedging`, and `select` against the still-pending
///    primary. The first side to land a `HedgeClass::Final` wins; a
///    transient on the first-to-complete side simply `.await`s the
///    other side. **Both legs transient** with the deadline still in
///    budget → returns [`HedgedRaceResult::BothTransient`] so the
///    caller loop can fall back against the remaining regions.
///
/// Application-cancellation (observed via [`AttemptContext::deadline`])
/// is layered onto both races: the deadline future is wrapped into a
/// 3-way `select` with the threshold timer (Stage 2) and the
/// primary/secondary pair (Stage 4). When the deadline wins,
/// [`harvest_remaining_attempt`] gives the most-advanced in-flight
/// pipeline up to `HARVEST_WINDOW` to complete so its diagnostics can
/// be attached to the returned [`application_cancelled_error`]. Loser
/// futures are dropped — structural cancellation propagates through
/// the transport pipeline.
///
/// PPCB feedback is wired here via [`record_hedge_outcome`]: every
/// Final outcome routed to either side is reported to the
/// [`LocationStateStore`] so the PPCB side can count consecutive
/// alternate-wins (and trip the partition at the configured threshold)
/// and reset the counter on primary-wins. The counter / partition-trip
/// machinery is fully implemented in
/// [`record_hedge_alternate_win`](crate::driver::routing) /
/// [`record_hedge_primary_win`](crate::driver::routing); the load-bearing
/// call sites are these branches.
///
/// Items NOT yet implemented:
///
/// - Operation-level retry inside each hedge; we rely on per-attempt
///   transport-pipeline retry only.
async fn execute_hedged(
    ctx: &AttemptContext<'_>,
    primary_routing: &RoutingDecision,
    secondary_routing: &RoutingDecision,
    threshold: HedgeThreshold,
    strategy_config: HedgingStrategyConfig,
    mut parent_diagnostics: DiagnosticsContextBuilder,
    // Borrowed snapshot read by `apply_hedge_leg_effects`; the race
    // never mutates the parent retry_state — STAGE 2b / STAGE 7 do
    // that post-race once `HedgedRaceResult` is destructured.
    retry_state_snapshot: &OperationRetryState,
) -> HedgedRaceResult {
    let primary_region = primary_routing.endpoint.region().cloned();
    let secondary_region = secondary_routing.endpoint.region().cloned();
    // `HedgeDiagnostics` is attached iff `execute_hedged` ran,
    // regardless of whether the routed endpoints carry a named region
    // (global-endpoint accounts do not). For diagnostics-construction
    // sites we substitute the public
    // [`HedgeDiagnostics::UNKNOWN_REGION_SENTINEL`] `Region` so the
    // attachment contract holds; PPCB recording paths below still use
    // the original `Option<Region>` so a `None` correctly attributes to
    // "no region" rather than collapsing all global-endpoint hedges
    // under a sentinel key.
    let primary_region_for_diag = primary_region
        .clone()
        .unwrap_or_else(|| Region::new(HedgeDiagnostics::UNKNOWN_REGION_SENTINEL));
    let secondary_region_for_diag = secondary_region
        .clone()
        .unwrap_or_else(|| Region::new(HedgeDiagnostics::UNKNOWN_REGION_SENTINEL));

    tracing::debug!(
        activity_id = %ctx.activity_id,
        threshold_ms = ?threshold.get().as_millis(),
        primary_region = ?primary_region.as_ref().map(|r| r.as_str()),
        secondary_region = ?secondary_region.as_ref().map(|r| r.as_str()),
        "execute_hedged: launching primary attempt",
    );

    // ── Stage 1: Build the primary future ─────────────────────────────
    // The diag clone is owned by the future and returned alongside the
    // result, so the borrow checker can reclaim it after `select` resolves.
    let primary_diag = parent_diagnostics.clone_for_hedge_attempt();
    let primary_attempt = Box::pin(async move {
        let mut diag = primary_diag;
        // Primary is launched before Stage 2 elapses, so no shared
        // hub-region latch can possibly exist yet — a `None` here
        // preserves the zero-overhead happy path (no `Arc` allocation
        // when the primary wins pre-threshold).
        let result = perform_single_attempt(
            ctx,
            primary_routing,
            ExecutionContext::Initial,
            None,
            &mut diag,
        )
        .await;
        (result, diag)
    });

    // ── Stage 2: Threshold race (zero-overhead happy path) ────────────
    // 3-way race: primary attempt vs threshold timer vs deadline. The
    // deadline arm enables the application-cancel path; when the
    // deadline has no value the deadline future never resolves and the
    // race collapses to the 2-way primary-vs-threshold semantics.
    let threshold_duration = match azure_core::time::Duration::try_from(threshold.get()) {
        Ok(d) => d,
        Err(_) => {
            // Programmer-error-class invariant violation: a hedge
            // threshold above `Duration::MAX` should be impossible by
            // construction (`HedgeThreshold::new` already guards this).
            // Synthesize the same typed status + diagnostics graft as
            // the other Terminal(Err) paths so operators inspecting
            // `error.diagnostics()` still see what the operation
            // attempted before bailing.
            parent_diagnostics.set_operation_status(
                azure_core::http::StatusCode::InternalServerError,
                Some(SubStatusCode::TRANSPORT_GENERATED_503),
            );
            let diagnostics_ctx = Arc::new(parent_diagnostics.complete());
            return HedgedRaceResult::Terminal(Err(crate::error::CosmosError::builder()
                .with_status(crate::models::CosmosStatus::TRANSPORT_GENERATED_503)
                .with_message("hedge threshold exceeds azure_core::time::Duration range")
                .with_diagnostics(diagnostics_ctx)
                .build()));
        }
    };
    let threshold_timer = Box::pin(azure_core::sleep(threshold_duration));
    let deadline_timer = deadline_signal(ctx.deadline);

    // Nest threshold-vs-deadline first so the outer select against the
    // primary returns a single tagged event.
    let timer_event = Box::pin(async move {
        match select(threshold_timer, deadline_timer).await {
            Either::Left(((), _)) => TimerEvent::ThresholdElapsed,
            Either::Right(((), _)) => TimerEvent::DeadlineFired,
        }
    });

    // The post-match value is the primary future the Stage 4 race will
    // consume. We unify the three possible future types (still-pending
    // primary, pre-resolved transient primary, deadline branch returns
    // early) by erasing to a boxed `dyn Future` trait object.
    type PrimaryAttemptFuture<'fut> = Pin<
        Box<
            dyn Future<
                    Output = (
                        crate::error::Result<TransportResult>,
                        DiagnosticsContextBuilder,
                    ),
                > + Send
                + 'fut,
        >,
    >;
    let primary_attempt: PrimaryAttemptFuture<'_> = match select(primary_attempt, timer_event).await
    {
        Either::Left(((result, diag), _timer)) => {
            // Primary resolved before either timer. Short-circuiting
            // the secondary launch is only safe when the primary's
            // outcome is **final** (HTTP success or application-classified
            // error per `CosmosStatus::is_final_result`). A *retriable* outcome
            // (5xx / 429 / 408 / 410 / 404-1002 / 403-with-sub /
            // transport error / deadline) must still race against the
            // secondary so a healthy alternate region can win —
            // otherwise hedging would actively suppress the
            // cross-region failover the operation pipeline would have
            // performed without the hedge upgrade.
            let primary_was_final = matches!(
                &result,
                Ok(tr) if result_is_final(tr),
            );
            if primary_was_final {
                // Zero-overhead happy path — no secondary attempt is
                // ever constructed.
                parent_diagnostics.merge_hedge_attempt(diag);
                parent_diagnostics.set_hedge_diagnostics(HedgeDiagnostics::primary_only(
                    strategy_config,
                    primary_region_for_diag.clone(),
                ));
                tracing::debug!(
                    activity_id = %ctx.activity_id,
                    "execute_hedged: primary won pre-threshold (zero-overhead happy path)",
                );
                // Structured win event. `was_hedge=false` distinguishes
                // the zero-overhead happy path from a post-threshold
                // primary win.
                tracing::debug!(
                    activity_id = %ctx.activity_id,
                    winner_region = ?primary_region.as_ref().map(crate::options::Region::as_str),
                    was_hedge = false,
                    "cosmos.hedge.winner_selected",
                );
                // Only a `Final` primary outcome resets the
                // consecutive-hedge-win counter on this
                // `(partition, primary_region)` pair. Recording for a
                // `Transient` outcome (a fast 503/449/transport-reset
                // that completes before the threshold) would silently
                // neutralize the PPCB signal for exactly the failure
                // mode it is designed to detect.
                //
                // Prefer the PK range ID parsed from the winning
                // response over `ctx.partition_key_range_id` (which is
                // the pre-race snapshot from the AttemptContext). On
                // the first attempt of an operation the snapshot is
                // `None`, so PPCB feedback would otherwise no-op even
                // though the response now carries the resolved range.
                let pk_range_id_for_feedback =
                    pk_range_id_from_result(&result).or_else(|| ctx.partition_key_range_id.clone());
                record_hedge_outcome(
                    ctx.location_state_store,
                    HedgeOutcome::PrimaryWin,
                    pk_range_id_for_feedback.as_ref(),
                    primary_region.as_ref(),
                );
                // result is Ok by the `primary_was_final` guard above.
                let tr = result.expect("Ok by primary_was_final guard");
                capture_session_token_for_winner(ctx, &tr);
                return HedgedRaceResult::Terminal(finalize_hedge_attempt(
                    Box::new(tr),
                    parent_diagnostics,
                ));
            }
            // Primary resolved pre-threshold but transient (or `Err`). Do
            // not merge diagnostics yet — fall through to Stage 3, wrap
            // the resolved primary into a `ready` future, and let the
            // Stage 4 race merge it on the winning-side path the same
            // way it merges a post-threshold primary completion.
            tracing::debug!(
                activity_id = %ctx.activity_id,
                "execute_hedged: primary completed pre-threshold transient; launching secondary",
            );
            Box::pin(futures::future::ready((result, diag)))
        }
        Either::Right((TimerEvent::ThresholdElapsed, remaining_primary)) => remaining_primary,
        Either::Right((TimerEvent::DeadlineFired, remaining_primary)) => {
            // App-cancel observed at Stage 2 — only the primary is
            // in-flight (no secondary was ever built). Harvest it
            // within HARVEST_WINDOW for diagnostics, then re-raise.
            // No leg produced a final response, so attach the
            // DeadlineExceededPreThreshold terminal state
            // (was_hedge=false) rather than primary_only — the
            // operation surfaces application_cancelled_error and hedge
            // win-rate metrics must not count this as a primary win.
            tracing::debug!(
                activity_id = %ctx.activity_id,
                "execute_hedged: deadline fired pre-threshold; harvesting primary",
            );
            harvest_remaining_attempt(
                remaining_primary,
                &mut parent_diagnostics,
                effective_harvest_window(ctx.configured_request_timeout),
            )
            .await;
            parent_diagnostics.set_hedge_diagnostics(
                HedgeDiagnostics::primary_only_deadline_exceeded(
                    strategy_config,
                    primary_region_for_diag.clone(),
                ),
            );
            return HedgedRaceResult::Terminal(Err(application_cancelled_error(
                parent_diagnostics,
            )));
        }
    };

    // ── Stage 3: Launch secondary ─────────────────────────────────────
    // The cross-hedge shared hub-region-processing-only latch is
    // constructed here — *after* the threshold elapses, so the
    // zero-overhead happy path never allocates the `Arc`. Gated on
    // the same predicates as the per-state latch trigger:
    // data-plane scope + single-master account. Seeded from whatever
    // value the main pipeline's per-state latch held at the moment
    // hedging upgraded, so a 1002 already discovered before hedging
    // fired carries forward into the secondary's first request.
    let shared_hub_region_latch = should_build_shared_hub_region_latch(
        ctx.pipeline_type,
        ctx.can_use_multiple_write_locations,
    )
    .then(|| Arc::new(AtomicBool::new(ctx.hub_region_processing_only_initial)));
    let secondary_shared_latch = shared_hub_region_latch.clone();
    let secondary_diag = parent_diagnostics.clone_for_hedge_attempt();
    let secondary_attempt = Box::pin(async move {
        let mut diag = secondary_diag;
        let result = perform_single_attempt(
            ctx,
            secondary_routing,
            ExecutionContext::Hedging,
            secondary_shared_latch.as_ref(),
            &mut diag,
        )
        .await;
        (result, diag)
    });

    tracing::debug!(
        activity_id = %ctx.activity_id,
        shared_hub_region_latch = shared_hub_region_latch.is_some(),
        "execute_hedged: threshold elapsed; secondary launched",
    );
    // Structured "alternate spawned" event distinct from the freeform
    // message above. Fields carry the race timing (threshold) and the
    // target region so operators can correlate spawn rate with observed
    // tail-latency improvements.
    tracing::debug!(
        activity_id = %ctx.activity_id,
        threshold_ms = threshold.get().as_millis() as u64,
        secondary_region = ?secondary_region.as_ref().map(crate::options::Region::as_str),
        "cosmos.hedge.alternate_spawned",
    );

    // ── Stage 4: Primary vs secondary race ────────────────────────────
    // Per-attempt deadline observation lives inside the transport
    // pipeline — when the end-to-end deadline fires while an
    // attempt is in flight, the transport returns `DeadlineExceeded`
    // which classifies as transient. The two `.await` calls in the
    // transient-fallthrough branches below are wrapped with
    // [`await_attempt_or_deadline_harvest`] so a deadline that fires
    // while we're waiting on the still-pending side triggers the
    // harvest path instead of blocking. The both-transient
    // terminal branches inspect the deadline to choose between
    // [`application_cancelled_error`] and [`transient_outcome_error`].
    //
    // Per-leg signals threaded into `BothTransient` so the failover-loop
    // fallback can rehydrate `retry_state` with what the race observed
    // — see `pk_range_id_from_result` and `apply_hedge_leg_effects`.
    let mut captured_pk_range_id: Option<PartitionKeyRangeId> = None;
    let mut race_observed_session_unavailable = false;
    match select(primary_attempt, secondary_attempt).await {
        Either::Left(((primary_result, primary_diag), secondary_remaining)) => {
            parent_diagnostics.merge_hedge_attempt(primary_diag);
            captured_pk_range_id =
                captured_pk_range_id.or_else(|| pk_range_id_from_result(&primary_result));
            apply_hedge_leg_effects(
                ctx,
                retry_state_snapshot,
                &primary_routing.endpoint,
                &primary_result,
                shared_hub_region_latch.as_ref(),
                &mut race_observed_session_unavailable,
            )
            .await;
            match classify_hedge_result(primary_result) {
                HedgeClass::Final(tr) => {
                    // Primary won post-threshold; drop secondary.
                    parent_diagnostics.set_hedge_diagnostics(
                        HedgeDiagnostics::primary_won_after_hedge(
                            strategy_config,
                            primary_region_for_diag.clone(),
                            secondary_region_for_diag.clone(),
                        ),
                    );
                    tracing::debug!(
                        activity_id = %ctx.activity_id,
                        "execute_hedged: primary won after threshold",
                    );
                    // Secondary attempt was dropped structurally when
                    // this branch was taken.
                    tracing::debug!(
                        activity_id = %ctx.activity_id,
                        which = "secondary",
                        target_region = ?secondary_region.as_ref().map(crate::options::Region::as_str),
                        reason = "primary_won_post_threshold",
                        "cosmos.hedge.canceled",
                    );
                    tracing::debug!(
                        activity_id = %ctx.activity_id,
                        winner_region = ?primary_region.as_ref().map(crate::options::Region::as_str),
                        was_hedge = true,
                        "cosmos.hedge.winner_selected",
                    );
                    record_hedge_outcome(
                        ctx.location_state_store,
                        HedgeOutcome::PrimaryWin,
                        captured_pk_range_id
                            .as_ref()
                            .or(ctx.partition_key_range_id.as_ref()),
                        primary_region.as_ref(),
                    );
                    capture_session_token_for_winner(ctx, &tr);
                    HedgedRaceResult::Terminal(finalize_hedge_attempt(tr, parent_diagnostics))
                }
                HedgeClass::Transient => {
                    // Primary transient — wait for secondary (observing deadline).
                    let Some((secondary_result, secondary_diag)) =
                        await_attempt_or_deadline_harvest(
                            secondary_remaining,
                            ctx.deadline,
                            &mut parent_diagnostics,
                            effective_harvest_window(ctx.configured_request_timeout),
                        )
                        .await
                    else {
                        tracing::debug!(
                            activity_id = %ctx.activity_id,
                            "execute_hedged: deadline fired awaiting secondary after primary transient",
                        );
                        // No leg produced a final response — attach
                        // CancelledAwaitingPartner terminal state
                        // (was_hedge=false) so hedge win-rate metrics
                        // do not count this as an alternate win.
                        parent_diagnostics.set_hedge_diagnostics(
                            HedgeDiagnostics::cancelled_awaiting_partner(
                                strategy_config,
                                primary_region_for_diag.clone(),
                                secondary_region_for_diag.clone(),
                            ),
                        );
                        return HedgedRaceResult::Terminal(Err(application_cancelled_error(
                            parent_diagnostics,
                        )));
                    };
                    parent_diagnostics.merge_hedge_attempt(secondary_diag);
                    captured_pk_range_id =
                        captured_pk_range_id.or_else(|| pk_range_id_from_result(&secondary_result));
                    apply_hedge_leg_effects(
                        ctx,
                        retry_state_snapshot,
                        &secondary_routing.endpoint,
                        &secondary_result,
                        shared_hub_region_latch.as_ref(),
                        &mut race_observed_session_unavailable,
                    )
                    .await;
                    match classify_hedge_result(secondary_result) {
                        HedgeClass::Final(tr) => {
                            parent_diagnostics.set_hedge_diagnostics(HedgeDiagnostics::hedge_won(
                                strategy_config,
                                primary_region_for_diag.clone(),
                                secondary_region_for_diag.clone(),
                            ));
                            tracing::debug!(
                                activity_id = %ctx.activity_id,
                                "execute_hedged: secondary won after primary transient",
                            );
                            tracing::debug!(
                                activity_id = %ctx.activity_id,
                                winner_region = ?secondary_region.as_ref().map(crate::options::Region::as_str),
                                was_hedge = true,
                                "cosmos.hedge.winner_selected",
                            );
                            record_hedge_outcome(
                                ctx.location_state_store,
                                HedgeOutcome::AlternateWin,
                                captured_pk_range_id
                                    .as_ref()
                                    .or(ctx.partition_key_range_id.as_ref()),
                                primary_region.as_ref(),
                            );
                            capture_session_token_for_winner(ctx, &tr);
                            HedgedRaceResult::Terminal(finalize_hedge_attempt(
                                tr,
                                parent_diagnostics,
                            ))
                        }
                        HedgeClass::Transient => {
                            // Both legs transient. Delegate to the helper
                            // so the diagnostics-attachment + tracing +
                            // outcome classification stay in one place.
                            // When the deadline has NOT elapsed this
                            // returns `BothTransient` so the operation
                            // pipeline can re-enter the failover loop
                            // against the remaining regions.
                            finalize_both_transient(
                                ctx.activity_id,
                                ctx.deadline,
                                strategy_config,
                                primary_region,
                                secondary_region,
                                primary_region_for_diag.clone(),
                                secondary_region_for_diag.clone(),
                                parent_diagnostics,
                                captured_pk_range_id,
                                race_observed_session_unavailable,
                            )
                        }
                    }
                }
            }
        }
        Either::Right(((secondary_result, secondary_diag), primary_remaining)) => {
            parent_diagnostics.merge_hedge_attempt(secondary_diag);
            captured_pk_range_id =
                captured_pk_range_id.or_else(|| pk_range_id_from_result(&secondary_result));
            apply_hedge_leg_effects(
                ctx,
                retry_state_snapshot,
                &secondary_routing.endpoint,
                &secondary_result,
                shared_hub_region_latch.as_ref(),
                &mut race_observed_session_unavailable,
            )
            .await;
            match classify_hedge_result(secondary_result) {
                HedgeClass::Final(tr) => {
                    parent_diagnostics.set_hedge_diagnostics(HedgeDiagnostics::hedge_won(
                        strategy_config,
                        primary_region_for_diag.clone(),
                        secondary_region_for_diag.clone(),
                    ));
                    tracing::debug!(
                        activity_id = %ctx.activity_id,
                        "execute_hedged: secondary won race",
                    );
                    // Primary attempt was dropped structurally when
                    // secondary won the race.
                    tracing::debug!(
                        activity_id = %ctx.activity_id,
                        which = "primary",
                        target_region = ?primary_region.as_ref().map(crate::options::Region::as_str),
                        reason = "secondary_won_race",
                        "cosmos.hedge.canceled",
                    );
                    tracing::debug!(
                        activity_id = %ctx.activity_id,
                        winner_region = ?secondary_region.as_ref().map(crate::options::Region::as_str),
                        was_hedge = true,
                        "cosmos.hedge.winner_selected",
                    );
                    record_hedge_outcome(
                        ctx.location_state_store,
                        HedgeOutcome::AlternateWin,
                        captured_pk_range_id
                            .as_ref()
                            .or(ctx.partition_key_range_id.as_ref()),
                        primary_region.as_ref(),
                    );
                    capture_session_token_for_winner(ctx, &tr);
                    HedgedRaceResult::Terminal(finalize_hedge_attempt(tr, parent_diagnostics))
                }
                HedgeClass::Transient => {
                    // Secondary transient — wait for primary (observing deadline).
                    let Some((primary_result, primary_diag)) = await_attempt_or_deadline_harvest(
                        primary_remaining,
                        ctx.deadline,
                        &mut parent_diagnostics,
                        effective_harvest_window(ctx.configured_request_timeout),
                    )
                    .await
                    else {
                        tracing::debug!(
                            activity_id = %ctx.activity_id,
                            "execute_hedged: deadline fired awaiting primary after secondary transient",
                        );
                        // No leg produced a final response — attach
                        // CancelledAwaitingPartner terminal state
                        // (was_hedge=false) so hedge win-rate metrics
                        // do not count this as an alternate win.
                        parent_diagnostics.set_hedge_diagnostics(
                            HedgeDiagnostics::cancelled_awaiting_partner(
                                strategy_config,
                                primary_region_for_diag.clone(),
                                secondary_region_for_diag.clone(),
                            ),
                        );
                        return HedgedRaceResult::Terminal(Err(application_cancelled_error(
                            parent_diagnostics,
                        )));
                    };
                    parent_diagnostics.merge_hedge_attempt(primary_diag);
                    captured_pk_range_id =
                        captured_pk_range_id.or_else(|| pk_range_id_from_result(&primary_result));
                    apply_hedge_leg_effects(
                        ctx,
                        retry_state_snapshot,
                        &primary_routing.endpoint,
                        &primary_result,
                        shared_hub_region_latch.as_ref(),
                        &mut race_observed_session_unavailable,
                    )
                    .await;
                    match classify_hedge_result(primary_result) {
                        HedgeClass::Final(tr) => {
                            parent_diagnostics.set_hedge_diagnostics(
                                HedgeDiagnostics::primary_won_after_hedge(
                                    strategy_config,
                                    primary_region_for_diag.clone(),
                                    secondary_region_for_diag.clone(),
                                ),
                            );
                            tracing::debug!(
                                activity_id = %ctx.activity_id,
                                "execute_hedged: primary won after secondary transient",
                            );
                            tracing::debug!(
                                activity_id = %ctx.activity_id,
                                winner_region = ?primary_region.as_ref().map(crate::options::Region::as_str),
                                was_hedge = true,
                                "cosmos.hedge.winner_selected",
                            );
                            record_hedge_outcome(
                                ctx.location_state_store,
                                HedgeOutcome::PrimaryWin,
                                captured_pk_range_id
                                    .as_ref()
                                    .or(ctx.partition_key_range_id.as_ref()),
                                primary_region.as_ref(),
                            );
                            capture_session_token_for_winner(ctx, &tr);
                            HedgedRaceResult::Terminal(finalize_hedge_attempt(
                                tr,
                                parent_diagnostics,
                            ))
                        }
                        HedgeClass::Transient => {
                            // Both legs transient. Same loop-fallback
                            // semantics as the symmetric Either::Left arm
                            // — see [`finalize_both_transient`].
                            finalize_both_transient(
                                ctx.activity_id,
                                ctx.deadline,
                                strategy_config,
                                primary_region,
                                secondary_region,
                                primary_region_for_diag.clone(),
                                secondary_region_for_diag.clone(),
                                parent_diagnostics,
                                captured_pk_range_id,
                                race_observed_session_unavailable,
                            )
                        }
                    }
                }
            }
        }
    }
}

/// Generic "both sides transient" error carried inside
/// [`HedgedRaceResult::BothTransient`] when neither leg produced a
/// final response and the deadline has not elapsed. The surrounding
/// operation pipeline will only surface this error to the caller if
/// the failover-retry budget has also been exhausted by the race —
/// otherwise the loop re-enters against the remaining regions.
///
/// The two raced regions are included in the message so operators
/// investigating "why didn't hedging save me?" can see at a glance
/// which two regions burnt RU on the failed race. `None` is rendered
/// as the [`HedgeDiagnostics::UNKNOWN_REGION_SENTINEL`] string for
/// consistency with the diagnostics-attachment surface.
///
/// Status is set to [`CosmosStatus::TRANSPORT_GENERATED_503`] so
/// retry-evaluation and telemetry can discriminate a client-side
/// "both legs transient" classification from any other 5xx surface.
/// Diagnostics are not threaded here: the surrounding
/// `BothTransient` flow returns a builder that the failover loop
/// keeps mutating; only the terminal error-surfacing path (when the
/// failover budget is exhausted) attaches diagnostics, and it does
/// so from the loop's own builder via the standard error-promotion
/// path.
fn transient_outcome_error(
    primary_region: Option<&Region>,
    secondary_region: Option<&Region>,
) -> crate::error::CosmosError {
    let p = primary_region
        .map(Region::as_str)
        .unwrap_or(HedgeDiagnostics::UNKNOWN_REGION_SENTINEL);
    let s = secondary_region
        .map(Region::as_str)
        .unwrap_or(HedgeDiagnostics::UNKNOWN_REGION_SENTINEL);
    crate::error::CosmosError::builder()
        .with_status(crate::models::CosmosStatus::TRANSPORT_GENERATED_503)
        .with_message(format!(
            "hedging completed without producing a final response \
             (primary={p}, secondary={s})"
        ))
        .build()
}

/// Centralizes the diagnostics attachment, structured tracing, and
/// outcome classification for the **both-legs-transient** terminal
/// state of [`execute_hedged`]'s Stage 4 race.
///
/// Returns:
///
/// - [`HedgedRaceResult::Terminal`] with [`application_cancelled_error`]
///   when the application deadline has elapsed (no remaining time
///   budget to spend on the failover-loop fallback).
/// - [`HedgedRaceResult::BothTransient`] otherwise, threading
///   `parent_diagnostics` back so the surrounding failover loop can
///   keep accumulating per-attempt request traces into the same
///   operation-scoped diagnostics chain.
///
/// `primary_region` / `secondary_region` are the original (potentially
/// `None`-for-global-endpoint) regions surfaced inside
/// `BothTransient` for telemetry; `primary_region_for_diag` /
/// `secondary_region_for_diag` are the
/// [`HedgeDiagnostics::UNKNOWN_REGION_SENTINEL`] sentinels used at the
/// `HedgeDiagnostics` attachment site so the attachment contract
/// holds even on global-endpoint accounts.
///
/// `partition_key_range_id` and `observed_session_unavailable` are
/// per-leg signals accumulated during the race; both are surfaced
/// verbatim on `HedgedRaceResult::BothTransient` for the failover
/// loop's write-back contract (see the variant docs).
#[allow(
    clippy::too_many_arguments,
    reason = "All ten values come from `execute_hedged`'s state and \
              are passed through to a single helper call site. Bundling \
              them into a struct would add an indirection without \
              improving readability — the two-region pairing (raw / \
              for-diag) is intentional and explicit at the call site."
)]
fn finalize_both_transient(
    activity_id: &ActivityId,
    deadline: Option<Instant>,
    strategy_config: HedgingStrategyConfig,
    primary_region: Option<Region>,
    secondary_region: Option<Region>,
    primary_region_for_diag: Region,
    secondary_region_for_diag: Region,
    mut parent_diagnostics: DiagnosticsContextBuilder,
    partition_key_range_id: Option<PartitionKeyRangeId>,
    observed_session_unavailable: bool,
) -> HedgedRaceResult {
    let deadline_was_elapsed = deadline_elapsed(deadline);
    tracing::warn!(
        activity_id = %activity_id,
        deadline_elapsed = deadline_was_elapsed,
        primary_region = ?primary_region.as_ref().map(Region::as_str),
        secondary_region = ?secondary_region.as_ref().map(Region::as_str),
        "cosmos.hedge.both_transient",
    );
    if deadline_was_elapsed {
        // Terminal both-transient under elapsed deadline — stamp
        // BothTransient here because the application_cancelled_error
        // path is the operation's final answer.
        parent_diagnostics.set_hedge_diagnostics(HedgeDiagnostics::both_transient(
            strategy_config,
            primary_region_for_diag,
            secondary_region_for_diag,
            deadline_was_elapsed,
        ));
        tracing::debug!(
            activity_id = %activity_id,
            "execute_hedged: both transient under elapsed deadline; surfacing app-cancel",
        );
        HedgedRaceResult::Terminal(Err(application_cancelled_error(parent_diagnostics)))
    } else {
        // Non-terminal: the failover loop will run more attempts. Do not
        // stamp HedgeDiagnostics here — a later successful retry would
        // carry a misleading `terminal_state = BothTransient`. Instead,
        // carry `strategy_config` and the `*_for_diag` regions on the
        // variant so the fallback can stamp it only if the failover budget
        // turns out to be exhausted.
        tracing::debug!(
            activity_id = %activity_id,
            primary_region = ?primary_region.as_ref().map(Region::as_str),
            secondary_region = ?secondary_region.as_ref().map(Region::as_str),
            observed_session_unavailable,
            "execute_hedged: both legs transient; bubbling up for failover-loop fallback",
        );
        HedgedRaceResult::BothTransient {
            last_error: transient_outcome_error(primary_region.as_ref(), secondary_region.as_ref()),
            primary_region,
            secondary_region,
            strategy_config,
            primary_region_for_diag,
            secondary_region_for_diag,
            diagnostics: parent_diagnostics,
            partition_key_range_id,
            observed_session_unavailable,
        }
    }
}

/// Handles the [`HedgedRaceResult::BothTransient`] outcome of
/// [`execute_hedged`] by advancing `retry_state` so the surrounding
/// failover loop can re-enter against the remaining regions.
///
/// Returns:
///
/// - `Ok(())` when the budget allowed advancing (caller `continue`s
///   the loop).
/// - `Err(last_error)` when `failover_retry_count + 2 >
///   max_failover_retries` (no remaining budget; caller surfaces
///   `last_error` as the operation's terminal error).
///
/// # Region accounting
///
/// The race consumed exactly two regions (the primary at the
/// snapshot's current `LocationIndex` and the secondary picked by
/// `evaluate_hedge_eligibility`). We charge two slots against
/// `failover_retry_count` and walk the `LocationIndex` forward until
/// it lands on an endpoint whose region matches neither the raced
/// primary nor the raced secondary, so the next iteration's
/// `resolve_endpoint` selects a region not yet tried in this race.
///
/// Walking forward (rather than blindly advancing by a fixed offset)
/// matters because the secondary picker no longer guarantees the
/// secondary sits at `primary_index + 1` — it scans the preferred
/// endpoints from the front and returns the first endpoint whose
/// region and endpoint key differ from the primary. With a fixed
/// `+2` advance the post-race `LocationIndex` could land back on the
/// just-failed primary or secondary (or skip an untried region) when
/// the primary was promoted to a non-zero index by prior retry state.
///
/// # Why two slots, not one?
///
/// A non-hedged operation that hit transients on the same two regions
/// would have consumed two failover-retry slots — one per region.
/// Charging the same amount here keeps the hedge-eligible path's
/// worst-case region coverage identical to the non-hedged path's.
/// Charging only one would let pathologically slow regions occupy
/// both slots of every race indefinitely; charging two converges on
/// the third region in bounded time exactly as the non-hedged loop
/// does.
fn try_advance_after_both_transient(
    retry_state: &mut OperationRetryState,
    location: &LocationSnapshot,
    is_read_only: bool,
    primary_region: Option<&Region>,
    secondary_region: Option<&Region>,
    last_error: crate::error::CosmosError,
) -> Result<(), crate::error::CosmosError> {
    let consumed: u32 = 2;
    let next_count = retry_state.failover_retry_count.saturating_add(consumed);
    if next_count > retry_state.max_failover_retries {
        tracing::debug!(
            failover_retry_count = retry_state.failover_retry_count,
            max_failover_retries = retry_state.max_failover_retries,
            "hedge both-transient: failover budget exhausted; surfacing terminal error",
        );
        return Err(last_error);
    }

    retry_state.failover_retry_count = next_count;
    let endpoints =
        preferred_endpoints_for_attempt(location.account.as_ref(), retry_state, is_read_only);
    let endpoints_len = endpoints.len();
    if endpoints_len > 0 {
        // Walk the LocationIndex forward starting from its current
        // position. `next_for_generation` rebases stale indices on the
        // first call when the snapshot generation changed, so the
        // first step lands on a position in the refreshed ordering.
        // We then keep advancing while the endpoint at the resolved
        // index belongs to a region that was just raced (primary or
        // secondary), bounded by `endpoints_len` iterations so we
        // always make forward progress even when only the raced
        // regions remain.
        let raced_region = |candidate: Option<&Region>| -> bool {
            match candidate {
                Some(c) => {
                    primary_region.is_some_and(|p| p == c)
                        || secondary_region.is_some_and(|s| s == c)
                }
                None => false,
            }
        };

        let mut advanced = retry_state
            .location
            .next_for_generation(endpoints_len, location.account.generation);
        // `endpoints_len - 1` extra steps is enough: combined with the
        // initial advance above we cover every distinct index in the
        // list, and the loop bails out the moment we find one that
        // is not in the raced set.
        for _ in 0..endpoints_len.saturating_sub(1) {
            if !raced_region(endpoints[advanced.index()].region()) {
                break;
            }
            advanced = advanced.next_for_generation(endpoints_len, location.account.generation);
        }
        retry_state.location = advanced;
    }
    tracing::debug!(
        failover_retry_count = retry_state.failover_retry_count,
        max_failover_retries = retry_state.max_failover_retries,
        "hedge both-transient: failover loop will continue against remaining regions",
    );
    Ok(())
}

/// Flips the per-state and shared `hub_region_processing_only` latches
/// when a hedge leg observed a 1002 the non-hedged
/// `build_session_retry_state` would have latched on, and advances
/// `session_token_retry_count` symmetrically so `max_session_retries`
/// is honored across both non-hedged and hedge-fallback flows.
fn propagate_hedge_session_unavailable(
    retry_state: &mut OperationRetryState,
    observed_session_unavailable: bool,
) {
    if !observed_session_unavailable {
        return;
    }
    // Mirror `.advance_session_retry()` in the non-hedged path so the
    // hedge fallback can't exceed `max_session_retries`. Gate on
    // `can_retry_session` to avoid overflowing past the cap.
    if retry_state.can_retry_session() {
        retry_state.session_token_retry_count =
            retry_state.session_token_retry_count.saturating_add(1);
    }
    if retry_state.hub_region_processing_only {
        return;
    }
    retry_state.hub_region_processing_only = true;
    if let Some(shared) = retry_state.shared_hub_region_latch.as_ref() {
        shared.store(true, Ordering::Release);
    }
    tracing::debug!(
        session_token_retry_count = retry_state.session_token_retry_count,
        max_session_retries = retry_state.max_session_retries,
        "hedge both-transient: 1002 observed by at least one leg; \
         flipped hub_region_processing_only latch and advanced \
         session-retry counter for next attempt",
    );
}

#[cfg(test)]
mod tests {
    use std::{sync::Arc, time::Duration};

    use azure_core::http::headers::HeaderName;
    use url::Url;

    use super::build_transport_request;
    use super::OperationOverrides;
    use super::TransportRequestContext;
    use crate::{
        diagnostics::ExecutionContext,
        driver::{
            pipeline::components::{RoutingDecision, TransportMode},
            routing::{
                AccountEndpointState, CosmosEndpoint, LocationEffect, LocationIndex,
                LocationSnapshot,
            },
        },
        models::{
            request_header_names, AccountReference, ActivityId, ContainerProperties,
            ContainerReference, CosmosOperation, DatabaseReference, EffectivePartitionKey,
            FeedRange, ItemReference, PartitionKey, PartitionKeyDefinition, SystemProperties,
        },
        options::{PriorityLevel, ResolvedThroughputControl},
    };

    fn test_account() -> AccountReference {
        AccountReference::with_master_key(
            Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "test-key",
        )
    }

    fn test_partition_key_definition(path: &str) -> PartitionKeyDefinition {
        serde_json::from_str(&format!(r#"{{"paths":["{path}"]}}"#)).unwrap()
    }

    fn test_container_props() -> ContainerProperties {
        ContainerProperties {
            id: "testcontainer".into(),
            partition_key: test_partition_key_definition("/pk"),
            system_properties: SystemProperties::default(),
        }
    }

    fn test_container() -> ContainerReference {
        ContainerReference::new(
            test_account(),
            "testdb",
            "testdb_rid",
            "testcontainer",
            "testcontainer_rid",
            &test_container_props(),
        )
    }

    fn test_routing() -> RoutingDecision {
        let endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        RoutingDecision {
            selected_url: endpoint.url().clone(),
            endpoint,
            transport_mode: TransportMode::Gateway,
        }
    }

    #[test]
    fn apply_headers_pk_range_only_omits_read_key_type() {
        let overrides = OperationOverrides {
            partition_key_range_id: Some("0".to_string()),
            ..Default::default()
        };
        let mut headers = azure_core::http::headers::Headers::new();
        overrides
            .apply_headers(&mut headers)
            .expect("apply_headers should succeed");

        assert_eq!(
            headers
                .get_optional_str(&HeaderName::from_static(
                    request_header_names::PARTITION_KEY_RANGE_ID
                ))
                .map(|s| s.to_string()),
            Some("0".to_string())
        );
        assert!(
            headers
                .get_optional_str(&HeaderName::from_static(
                    request_header_names::READ_FEED_KEY_TYPE
                ))
                .is_none(),
            "whole-PK-range targets must not emit x-ms-read-key-type"
        );
        assert!(headers
            .get_optional_str(&HeaderName::from_static(request_header_names::START_EPK))
            .is_none());
        assert!(headers
            .get_optional_str(&HeaderName::from_static(request_header_names::END_EPK))
            .is_none());
    }

    #[test]
    fn apply_headers_feed_range_emits_read_key_type_and_epk_bounds() {
        let feed_range = FeedRange::new(
            EffectivePartitionKey::from("10"),
            EffectivePartitionKey::from("20"),
        )
        .unwrap();
        let overrides = OperationOverrides {
            partition_key_range_id: Some("pkrange".to_string()),
            feed_range: Some(feed_range),
            ..Default::default()
        };
        let mut headers = azure_core::http::headers::Headers::new();
        overrides
            .apply_headers(&mut headers)
            .expect("apply_headers should succeed");

        assert_eq!(
            headers
                .get_optional_str(&HeaderName::from_static(
                    request_header_names::READ_FEED_KEY_TYPE
                ))
                .map(|s| s.to_string()),
            Some("EffectivePartitionKey".to_string())
        );
        assert_eq!(
            headers
                .get_optional_str(&HeaderName::from_static(request_header_names::START_EPK))
                .map(|s| s.to_string()),
            Some("10".to_string())
        );
        assert_eq!(
            headers
                .get_optional_str(&HeaderName::from_static(request_header_names::END_EPK))
                .map(|s| s.to_string()),
            Some("20".to_string())
        );
    }

    #[test]
    fn build_transport_request_feed_path_is_resolved() {
        let operation = CosmosOperation::read_all_databases(test_account());

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        assert_eq!(request.url.path(), "/dbs");
    }

    #[test]
    fn build_transport_request_single_resource_path_is_resolved() {
        let db = DatabaseReference::from_name(test_account(), "mydb");
        let operation = CosmosOperation::read_database(db);

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        assert_eq!(request.url.path(), "/dbs/mydb");
    }

    #[test]
    fn build_transport_request_uses_operation_activity_id_when_present() {
        let operation = CosmosOperation::read_all_databases(test_account())
            .with_activity_id(ActivityId::from_string("operation-activity".to_string()));

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        let activity_header = request
            .headers
            .get_optional_str(&HeaderName::from_static("x-ms-activity-id"))
            .expect("activity id should be set");
        assert_eq!(activity_header, "operation-activity");
    }

    #[test]
    fn build_transport_request_adds_partition_key_header_for_item_operation() {
        let item_ref =
            ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::read_item(item_ref);

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Retry,
            deadline: Some(std::time::Instant::now() + Duration::from_secs(5)),
            resolved_session_token: None,
            throughput_control: None,
        };
        let overrides = OperationOverrides {
            partition_key: Some(PartitionKey::from("pk1")),
            ..Default::default()
        };
        let request = build_transport_request(&operation, &overrides, None, &ctx)
            .expect("request should build");

        let partition_key_header = request
            .headers
            .get_optional_str(&HeaderName::from_static("x-ms-documentdb-partitionkey"))
            .expect("partition key header should be set");
        assert_eq!(partition_key_header, "[\"pk1\"]");
    }

    #[test]
    fn build_transport_request_uses_routed_endpoint_url_directly() {
        let operation =
            CosmosOperation::read_database(DatabaseReference::from_name(test_account(), "mydb"));
        let routing = RoutingDecision {
            endpoint: CosmosEndpoint::regional_with_gateway20(
                "westus2".into(),
                Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
                Url::parse("https://test-westus2-thin.documents.azure.com:444/").unwrap(),
            ),
            selected_url: Url::parse("https://test-westus2-thin.documents.azure.com:444/").unwrap(),
            transport_mode: TransportMode::Gateway20,
        };

        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        assert_eq!(
            request.url.as_str(),
            "https://test-westus2-thin.documents.azure.com:444/dbs/mydb"
        );
    }

    #[test]
    fn build_transport_request_uses_default_url_for_global_endpoint() {
        let operation =
            CosmosOperation::read_database(DatabaseReference::from_name(test_account(), "mydb"));
        let routing = RoutingDecision {
            endpoint: CosmosEndpoint::global(
                Url::parse("https://test.documents.azure.com:443/").unwrap(),
            ),
            selected_url: Url::parse("https://test.documents.azure.com:443/").unwrap(),
            transport_mode: TransportMode::Gateway,
        };

        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        assert_eq!(
            request.url.as_str(),
            "https://test.documents.azure.com/dbs/mydb"
        );
    }

    #[test]
    fn resolve_endpoint_uses_write_region_for_single_write_session_retry() {
        let operation = CosmosOperation::read_all_databases(test_account());
        let write_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let read_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![read_endpoint].into(),
            preferred_write_endpoints: vec![write_endpoint.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: write_endpoint.clone(),
        }));

        let retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 1,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: Vec::new(),
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredWriteEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(routing.endpoint, write_endpoint);
    }

    #[test]
    fn resolve_endpoint_deprioritizes_unavailable_over_global_fallback() {
        let operation = CosmosOperation::read_all_databases(test_account());
        let default_endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        let read_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            read_endpoint.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::TransportError,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![read_endpoint.clone()].into(),
            preferred_write_endpoints: vec![default_endpoint.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: default_endpoint.clone(),
        }));

        let retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: Vec::new(),
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        // Unavailable regional endpoint is de-prioritized but still preferred
        // over the global fallback.
        assert_eq!(routing.endpoint, read_endpoint);
    }

    #[test]
    fn resolve_endpoint_ignores_write_forbidden_for_reads() {
        let operation = CosmosOperation::read_all_databases(test_account());
        let read_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            read_endpoint.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::WriteForbidden,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![read_endpoint.clone()].into(),
            preferred_write_endpoints: vec![read_endpoint.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: read_endpoint.clone(),
        }));

        let retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: Vec::new(),
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(routing.endpoint, read_endpoint);
    }

    #[test]
    fn stale_generation_advances_across_refreshed_endpoint_list() {
        let operation = CosmosOperation::read_all_databases(test_account());
        let endpoint_a = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let endpoint_b = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );
        let endpoint_c = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 1,
            preferred_read_endpoints: vec![
                endpoint_a.clone(),
                endpoint_b.clone(),
                endpoint_c.clone(),
            ]
            .into(),
            preferred_write_endpoints: vec![
                endpoint_a.clone(),
                endpoint_b.clone(),
                endpoint_c.clone(),
            ]
            .into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: endpoint_a.clone(),
        }));

        let stale_retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0).next(3),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 3,
            can_use_multiple_write_locations: true,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: Vec::new(),
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };

        let first_routing = super::resolve_endpoint(
            &operation,
            &stale_retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(first_routing.endpoint, endpoint_a);

        let advanced_state = stale_retry_state
            .advance_failover()
            .advance_location(3, location.account.generation);

        let second_routing = super::resolve_endpoint(
            &operation,
            &advanced_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(second_routing.endpoint, endpoint_b);
    }

    mod should_capture_session_token_from_status_tests {
        use azure_core::http::StatusCode;

        use crate::{
            driver::pipeline::components::TransportOutcome,
            models::{CosmosResponseHeaders, CosmosStatus, SubStatusCode},
        };

        use super::super::should_capture_session_token_from_status;

        fn success_outcome() -> TransportOutcome {
            TransportOutcome::Success {
                status: CosmosStatus::new(StatusCode::Ok),
                cosmos_headers: CosmosResponseHeaders::default(),
                body: Vec::new(),
            }
        }

        fn http_error_outcome(status: StatusCode) -> TransportOutcome {
            TransportOutcome::HttpError {
                status: CosmosStatus::new(status),
                cosmos_headers: CosmosResponseHeaders::default(),
                body: Vec::new(),
                request_sent: crate::diagnostics::RequestSentStatus::Sent,
            }
        }

        #[test]
        fn captures_on_success() {
            let outcome = success_outcome();
            assert!(should_capture_session_token_from_status(None, &outcome));
        }

        #[test]
        fn captures_on_409_conflict() {
            let outcome = http_error_outcome(StatusCode::Conflict);
            assert!(should_capture_session_token_from_status(None, &outcome));
        }

        #[test]
        fn captures_on_412_precondition_failed() {
            let outcome = http_error_outcome(StatusCode::PreconditionFailed);
            assert!(should_capture_session_token_from_status(None, &outcome));
        }

        #[test]
        fn skips_on_404_with_substatus_1002() {
            let outcome = http_error_outcome(StatusCode::NotFound);
            let substatus = SubStatusCode::READ_SESSION_NOT_AVAILABLE;
            assert!(!should_capture_session_token_from_status(
                Some(&substatus),
                &outcome
            ));
        }

        #[test]
        fn captures_on_404_without_substatus_1002() {
            let outcome = http_error_outcome(StatusCode::NotFound);
            assert!(should_capture_session_token_from_status(None, &outcome));
        }

        #[test]
        fn skips_on_500_internal_server_error() {
            let outcome = http_error_outcome(StatusCode::InternalServerError);
            assert!(!should_capture_session_token_from_status(None, &outcome));
        }
    }

    mod effective_consistency_tests {
        use crate::{models::DefaultConsistencyLevel, options::ReadConsistencyStrategy};

        #[test]
        fn default_strategy_with_session_account() {
            assert!(ReadConsistencyStrategy::Default
                .is_session_effective(DefaultConsistencyLevel::Session));
        }

        #[test]
        fn default_strategy_with_strong_account() {
            assert!(!ReadConsistencyStrategy::Default
                .is_session_effective(DefaultConsistencyLevel::Strong));
        }

        #[test]
        fn session_strategy_overrides_account() {
            assert!(ReadConsistencyStrategy::Session
                .is_session_effective(DefaultConsistencyLevel::Strong));
        }

        #[test]
        fn eventual_strategy_never_session() {
            assert!(!ReadConsistencyStrategy::Eventual
                .is_session_effective(DefaultConsistencyLevel::Session));
        }

        #[test]
        fn consistent_prefix_not_session() {
            assert!(!ReadConsistencyStrategy::Default
                .is_session_effective(DefaultConsistencyLevel::ConsistentPrefix));
        }
    }

    #[test]
    fn resolve_endpoint_prefers_gateway20_for_dataplane_reads() {
        let operation = CosmosOperation::read_item(ItemReference::from_name(
            &test_container(),
            PartitionKey::from("pk1"),
            "doc1",
        ));
        let endpoint = CosmosEndpoint::regional_with_gateway20(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
            Url::parse("https://test-westus2-thin.documents.azure.com:444/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![endpoint.clone()].into(),
            preferred_write_endpoints: vec![endpoint.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: endpoint.clone(),
        }));

        let retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            true,
            Duration::from_secs(60),
        );
        assert_eq!(routing.endpoint, endpoint);
        assert_eq!(routing.transport_mode, TransportMode::Gateway20);
        assert_eq!(
            routing.selected_url.as_str(),
            "https://test-westus2-thin.documents.azure.com:444/"
        );
    }

    #[test]
    fn resolve_endpoint_skips_unavailable_region_when_gateway20_is_present() {
        let operation = CosmosOperation::read_item(ItemReference::from_name(
            &test_container(),
            PartitionKey::from("pk1"),
            "doc1",
        ));
        let endpoint = CosmosEndpoint::regional_with_gateway20(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
            Url::parse("https://test-westus2-thin.documents.azure.com:444/").unwrap(),
        );
        let fallback_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            endpoint.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::TransportError,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![endpoint.clone(), fallback_endpoint.clone()].into(),
            preferred_write_endpoints: vec![endpoint].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: true,
            default_endpoint: fallback_endpoint.clone(),
        }));

        let retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            3,
        );

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            true,
            Duration::from_secs(60),
        );
        assert_eq!(routing.endpoint, fallback_endpoint);
    }

    #[test]
    fn resolve_endpoint_metadata_falls_back_to_hub_when_all_excluded() {
        // Pipeline-routed metadata operations (e.g. read_all_databases,
        // CreateDatabase, CreateContainer, Offer reads) must fall back to
        // the hub regional endpoint when every preferred region is excluded
        // — never the global endpoint. The global endpoint is only used by
        // account-topology fetches, which bypass this routing path.
        let operation = CosmosOperation::read_all_databases(test_account());
        let default_endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        let hub_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let read_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![read_endpoint.clone()].into(),
            preferred_write_endpoints: vec![hub_endpoint.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: default_endpoint.clone(),
        }));

        let retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: vec!["westus2".into(), "eastus".into()],
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(routing.endpoint, hub_endpoint);
        assert!(!routing.endpoint.is_global());
    }

    #[test]
    fn resolve_endpoint_dataplane_excluded_read_region_routes_to_hub() {
        // Only the read region is excluded — the hub write region is still
        // available, so resolve_endpoint should pick it directly from the
        // write endpoint list (not via the last-resort fallback path).
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::read_item(item);
        let default_endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        let hub_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let read_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![read_endpoint.clone()].into(),
            preferred_write_endpoints: vec![hub_endpoint.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: default_endpoint.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: vec!["westus2".into()],
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };
        retry_state.is_dataplane = true;

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(routing.endpoint, hub_endpoint);
        assert!(!routing.endpoint.is_global());
    }

    #[test]
    fn resolve_endpoint_dataplane_all_regions_excluded_falls_back_to_hub() {
        // Both the read region AND the hub write region are excluded.
        // resolve_endpoint must still use the hub write region via the
        // last-resort fallback (preferred_write_endpoints[0]), never the
        // global endpoint.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::read_item(item);
        let default_endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        let hub_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let read_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![read_endpoint.clone()].into(),
            preferred_write_endpoints: vec![hub_endpoint.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: default_endpoint.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: vec!["westus2".into(), "eastus".into()],
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };
        retry_state.is_dataplane = true;

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        // Even with all regions excluded, the hub write region is used as
        // the last-resort fallback for data-plane operations.
        assert_eq!(routing.endpoint, hub_endpoint);
        assert!(!routing.endpoint.is_global());
    }

    #[test]
    fn resolve_endpoint_dataplane_excluded_and_unavailable_still_uses_hub() {
        // When a read endpoint is both user-excluded AND marked unavailable,
        // the data-plane fallback must still use the hub write region.
        // Note: if an endpoint is only unavailable (not excluded),
        // try_select_endpoint already returns it as a deprioritized fallback
        // — this test validates the combined exclusion + unavailability case.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::read_item(item);
        let default_endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        let hub_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let read_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        // Mark the only read endpoint as unavailable.
        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            read_endpoint.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::ServiceUnavailable,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![read_endpoint.clone()].into(),
            preferred_write_endpoints: vec![hub_endpoint.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: default_endpoint.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: vec!["westus2".into()],
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };
        retry_state.is_dataplane = true;

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        // Excluded + unavailable: data-plane op must get the hub write
        // region, not the global endpoint.
        assert_eq!(routing.endpoint, hub_endpoint);
        assert!(!routing.endpoint.is_global());
    }

    #[test]
    fn resolve_endpoint_dataplane_isolated_region_unavailable_retries_same_region() {
        // Region-isolation guarantee: when the caller excludes every region
        // EXCEPT one (intending to confine the workload to that single
        // region), the SDK must NOT silently fall back to the hub region
        // when the chosen region becomes unavailable. Instead the chosen
        // region is returned as a deprioritized-but-not-replaced endpoint
        // (`first_unavailable`), preserving isolation. The caller's retry
        // budget eventually surfaces the error, which is the correct
        // signal — a workload pinned to one region should fail, not silently
        // cross a region boundary.
        //
        // This is the scenario where the customer wants the hub region
        // excluded (e.g. compliance / cost / blast-radius reasons) and the
        // only retained region (WestUS2 here) is unavailable. We must NOT
        // route to EastUS.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::read_item(item);
        let default_endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        let hub_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let isolated_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        // Mark the caller's chosen region as unavailable.
        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            isolated_endpoint.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::ServiceUnavailable,
            ),
        );

        // Account topology: both regions are readable; hub is the write
        // region. The caller's preference puts the isolated region first.
        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![isolated_endpoint.clone(), hub_endpoint.clone()].into(),
            preferred_write_endpoints: vec![hub_endpoint.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: default_endpoint.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState {
            location: LocationIndex::initial(0),
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 3,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: false,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            // Caller excludes the hub region — they want isolation to
            // WestUS2 only.
            excluded_regions: vec!["eastus".into()],
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        };
        retry_state.is_dataplane = true;

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );

        // The isolated region is returned even though it's unavailable —
        // crucially NOT the hub region. This is what preserves
        // region-isolation intent: the caller's retry policy will eventually
        // exhaust and surface the error, but no request ever crosses into
        // the excluded hub region.
        assert_eq!(
            routing.endpoint, isolated_endpoint,
            "region-isolation broken: resolve_endpoint silently fell back \
             to a region the caller excluded"
        );
        assert_ne!(
            routing.endpoint, hub_endpoint,
            "region-isolation broken: resolve_endpoint chose the excluded hub region"
        );
        assert!(!routing.endpoint.is_global());
    }

    #[test]
    fn resolve_endpoint_multi_write_isolated_region_unavailable_read_returns_isolated_not_excluded()
    {
        // Multi-write (multi-master) account, read op.
        // Topology: preferred_read = [r1, r2], preferred_write = [r1, r2]
        //           (both regions readable AND writable).
        // Caller config: excluded_regions = [r1] (pin workload to r2).
        // Service state: r2 marked unavailable in account.unavailable_endpoints.
        //
        // Expected: r2 is returned as `first_unavailable`. We must NOT leak to
        // r1 — even though r1 is in the preferred list and is the "first
        // preferred region", it was hard-excluded by the caller and must
        // never be selected.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::read_item(item);

        let r1 = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let r2 = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            r2.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::ServiceUnavailable,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![r1.clone(), r2.clone()].into(),
            preferred_write_endpoints: vec![r1.clone(), r2.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: true,
            default_endpoint: r1.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            vec!["eastus".into()],
            3,
            2,
        );
        retry_state.is_dataplane = true;

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, r2,
            "isolation broken on read: resolve_endpoint did not return the \
             caller's isolated region (r2)"
        );
        assert_ne!(
            routing.endpoint, r1,
            "isolation broken on read: resolve_endpoint silently routed to \
             the excluded region (r1)"
        );
    }

    #[test]
    fn resolve_endpoint_multi_write_isolated_region_unavailable_write_retry_returns_isolated_not_excluded(
    ) {
        // Multi-write (multi-master) account, write op, simulating attempt 2
        // after the first attempt against r2 failed.
        // Topology: preferred_read = [r1, r2], preferred_write = [r1, r2].
        // Caller config: excluded_regions = [r1] (pin workload to r2).
        // Service state: r2 marked unavailable in account.unavailable_endpoints.
        // In-flight state: pending_write_effects contains a partition mark
        //                  for r2, so the in-flight skip set on this attempt
        //                  is [r2].
        //
        // Trace through resolve_endpoint:
        //   pass 1 (skip=[r2]): r1 excluded → continue; r2 in skip →
        //                       continue; returns None.
        //   pass 2 (skip=[]):   r1 excluded → continue; r2 not excluded,
        //                       not in skip, unavailable → recorded as
        //                       first_unavailable; returns Some(r2).
        //   selected = Some(r2). The last-resort
        //   `preferred_write_endpoints[0]` fallback never fires because
        //   pass 2 returned Some.
        //
        // Expected: r2 returned. We must NOT leak to r1.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let r1 = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let r2 = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            r2.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::ServiceUnavailable,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![r1.clone(), r2.clone()].into(),
            preferred_write_endpoints: vec![r1.clone(), r2.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: true,
            default_endpoint: r1.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            vec!["eastus".into()],
            3,
            2,
        );
        retry_state.is_dataplane = true;
        // Simulate one prior failed write attempt against r2 (westus2).
        retry_state
            .pending_write_effects
            .push(make_pending_partition_mark_for_region("westus2"));

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, r2,
            "isolation broken on write retry: resolve_endpoint did not \
             return the caller's isolated region (r2)"
        );
        assert_ne!(
            routing.endpoint, r1,
            "isolation broken on write retry: resolve_endpoint silently \
             routed to the excluded region (r1) via the last-resort fallback"
        );
    }

    #[test]
    fn resolve_endpoint_single_write_excluded_hub_satellite_unavailable_read_returns_satellite() {
        // Single-write (single-master) account, read op.
        // Topology: preferred_read = [hub, satellite], preferred_write = [hub]
        //           (only hub is writable; both readable).
        // Caller config: excluded_regions = [hub] (pin reads to satellite).
        // Service state: satellite marked unavailable.
        //
        // For READS on a single-write account, the routing primary list is
        // preferred_read_endpoints (which contains BOTH hub and satellite).
        // Excluding hub leaves satellite as the only eligible region, and
        // even though satellite is unavailable, `first_unavailable` returns
        // it. We must NOT leak to hub on reads — the caller asked for
        // isolation, and the satellite-unavailable case is exactly when the
        // caller wants to see the error, not a silent cross-region hop.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::read_item(item);

        let hub = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let satellite = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            satellite.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::ServiceUnavailable,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![hub.clone(), satellite.clone()].into(),
            preferred_write_endpoints: vec![hub.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: hub.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            vec!["eastus".into()],
            3,
            2,
        );
        retry_state.is_dataplane = true;

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, satellite,
            "isolation broken on single-write read: resolve_endpoint did \
             not return the caller's isolated region (satellite)"
        );
        assert_ne!(
            routing.endpoint, hub,
            "isolation broken on single-write read: resolve_endpoint \
             silently routed to the excluded hub region"
        );
    }

    #[test]
    fn resolve_endpoint_picks_first_available_over_unavailable() {
        let operation = CosmosOperation::read_all_databases(test_account());
        let default_endpoint =
            CosmosEndpoint::global(Url::parse("https://test.documents.azure.com:443/").unwrap());
        let unavailable_endpoint = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );
        let available_endpoint = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            unavailable_endpoint.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::ServiceUnavailable,
            ),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![
                unavailable_endpoint.clone(),
                available_endpoint.clone(),
            ]
            .into(),
            preferred_write_endpoints: vec![default_endpoint.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: default_endpoint.clone(),
        }));

        let retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        // Available endpoint is preferred over the unavailable one.
        assert_eq!(routing.endpoint, available_endpoint);
    }

    // ── PPAF write-retry cross-region fallback ─────────────────────────

    fn make_pending_partition_mark_for_region(
        region: &'static str,
    ) -> crate::driver::routing::LocationEffect {
        crate::driver::routing::LocationEffect::MarkPartitionUnavailable(
            crate::driver::routing::UnavailablePartition {
                partition_key_range_id: None,
                region: Some(region.into()),
                is_read: false,
                is_partitioned_resource: true,
            },
        )
    }

    #[test]
    fn resolve_endpoint_skips_in_flight_failed_write_region() {
        // Multi-write account: writes can rotate across both write regions.
        // After the first attempt to eastus fails, the in-flight skip set
        // should route the next attempt to westus2 instead of repeating eastus.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let west = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![east.clone(), west.clone()].into(),
            preferred_write_endpoints: vec![east.clone(), west.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: east.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        // Simulate one prior failed attempt against eastus that deferred
        // a partition mark for that region.
        retry_state
            .pending_write_effects
            .push(make_pending_partition_mark_for_region("eastus"));

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, west,
            "in-flight skip set must route the retry to westus2"
        );
    }

    #[test]
    fn resolve_endpoint_honors_excluded_regions() {
        // Pins `excluded_regions` as a hard dataplane write filter.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let west = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![east.clone(), west.clone()].into(),
            preferred_write_endpoints: vec![east.clone(), west.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: east.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            vec!["westus2".into()],
            3,
            2,
        );
        retry_state.is_dataplane = true;
        // West is excluded; only East should be eligible.
        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, east,
            "excluded_regions must gate selection — got {:?}",
            routing.endpoint
        );
    }

    #[test]
    fn resolve_endpoint_ppaf_write_uses_read_endpoints_as_primary_list() {
        // Single-master account with PPAF: preferred_write_endpoints = [eastus]
        // only, but preferred_read_endpoints = [westus2, eastus] (different
        // ordering — westus2 is the user's preferred region). With PPAF
        // enabled, a write must iterate over the READ list so the first
        // attempt targets westus2 (the user's preferred region) and probes for
        // the actual write region, rather than blindly hitting the only entry
        // in the write list.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let west = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![west.clone(), east.clone()].into(),
            preferred_write_endpoints: vec![east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: east.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );
        retry_state.ppaf_write_retry_allowed = true;

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, west,
            "PPAF write must use the read endpoint list (preferred order) as the primary candidate set"
        );
    }

    #[test]
    fn resolve_endpoint_ppaf_falls_back_to_read_region_when_write_exhausted() {
        // Single-master account with PPAF: write_endpoints = [eastus] only.
        // After eastus has failed, PPAF write retry should fall back to a
        // read region (westus2) for cross-regional write region discovery.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let west = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![east.clone(), west.clone()].into(),
            preferred_write_endpoints: vec![east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: east.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );
        retry_state.ppaf_write_retry_allowed = true;
        retry_state
            .pending_write_effects
            .push(make_pending_partition_mark_for_region("eastus"));

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, west,
            "PPAF write retry must fall back to a read region when all write regions are in the in-flight skip set"
        );
    }

    #[test]
    fn resolve_endpoint_ppaf_override_skipped_when_current_endpoint_failed_in_flight() {
        // Regression test for PPAF write failback infinite-retry bug.
        //
        // Scenario: an earlier successful PPAF discovery recorded an
        // override pointing at `centralus`. A new write begins:
        //   1. resolve_endpoint sees the PPAF override → routes to centralus.
        //   2. centralus is failing back (returns 403/3) → the failure-path
        //      effects are deferred into `pending_write_effects` because
        //      PPAF SM defers writes until success/region-confirming abort.
        //   3. The persistent `failover_overrides[pk_range_id].current_endpoint`
        //      still says centralus (deferred effects haven't been flushed).
        //   4. On retry, the PPAF override branch in resolve_endpoint MUST
        //      consult the in-flight skip set and fall through to the primary
        //      selection (which has already rotated past centralus) — otherwise
        //      every retry hammers the same failed override region.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![north.clone(), central.clone()].into(),
            preferred_write_endpoints: vec![north.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: north.clone(),
        });

        // Build a partition state with PPAF enabled and a stale override
        // entry that points at the now-failing centralus region.
        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let mut partitions = PartitionEndpointState::new(PartitionFailoverOptions::default());
        partitions.per_partition_automatic_failover_enabled = true;
        partitions.failover_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: central.clone(),
                first_failed_endpoint: central.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: 0,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );
        retry_state.ppaf_write_retry_allowed = true;
        retry_state.partition_key_range_id = Some(pk_range_id);
        // Simulate that the current operation already failed against centralus
        // (override target) and the deferred mark is sitting in the buffer.
        retry_state
            .pending_write_effects
            .push(make_pending_partition_mark_for_region("centralus"));

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, north,
            "PPAF override pointing at a region already in the in-flight skip set must be skipped, \
             so cross-region retry can rotate to a different region instead of looping on the failed override"
        );
    }

    #[test]
    fn resolve_endpoint_ppaf_override_honored_when_current_endpoint_not_failed() {
        // Counterpart to the regression test above: when the override's
        // current_endpoint is NOT in the in-flight skip set, the PPAF
        // override MUST be honored (otherwise prior failover decisions
        // would be silently ignored on every retry).
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![north.clone(), central.clone()].into(),
            preferred_write_endpoints: vec![north.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: north.clone(),
        });

        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let mut partitions = PartitionEndpointState::new(PartitionFailoverOptions::default());
        partitions.per_partition_automatic_failover_enabled = true;
        partitions.failover_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: central.clone(),
                first_failed_endpoint: north.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: 0,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );
        retry_state.ppaf_write_retry_allowed = true;
        retry_state.partition_key_range_id = Some(pk_range_id);
        // pending_write_effects is empty — first attempt of the operation,
        // so the override should be applied as-is.

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, central,
            "PPAF override with a healthy current_endpoint must be honored"
        );
    }

    // ── PPCB override skip-closure ────────────────────────────────────

    /// Builds a PPCB override that is already over the write-failover threshold.
    fn make_partition_state_with_ppcb_override(
        pk_range_id: &super::PartitionKeyRangeId,
        override_target: CosmosEndpoint,
    ) -> crate::driver::routing::partition_endpoint_state::PartitionEndpointState {
        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let config = PartitionFailoverOptions::default();
        let mut partitions = PartitionEndpointState::new(config);
        partitions.per_partition_circuit_breaker_enabled = true;
        partitions.circuit_breaker_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: override_target.clone(),
                first_failed_endpoint: override_target,
                failed_endpoints: Default::default(),
                read_failure_count: 100,
                write_failure_count: 100,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );
        partitions
    }

    #[test]
    fn resolve_endpoint_ppcb_override_skipped_when_in_excluded_regions() {
        // PPCB overrides must not route to caller-excluded regions.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![north.clone(), central.clone()].into(),
            preferred_write_endpoints: vec![north.clone(), central.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: north.clone(),
        });

        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let partitions = make_partition_state_with_ppcb_override(&pk_range_id, central.clone());
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        retry_state.partition_key_range_id = Some(pk_range_id);
        retry_state.excluded_regions = vec![crate::options::Region::from("centralus")];

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, north,
            "PPCB override pointing at a caller-excluded region must be skipped; \
             fall-through to primary selection should pick the non-excluded region"
        );
    }

    #[test]
    fn resolve_endpoint_ppcb_override_skipped_when_current_endpoint_not_in_topology() {
        // Topology refresh does not prune PPCB overrides; this pins the stale-region skip.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        // Post-refresh topology dropped `central`; the PPCB override still points there.
        let account = Arc::new(AccountEndpointState {
            generation: 1,
            preferred_read_endpoints: vec![north.clone()].into(),
            preferred_write_endpoints: vec![north.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: north.clone(),
        });

        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let partitions = make_partition_state_with_ppcb_override(&pk_range_id, central.clone());
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        retry_state.partition_key_range_id = Some(pk_range_id);
        // No excluded_regions, no in-flight failures, no endpoint mark —
        // `region_not_in_topology` is the only gate that can fire.

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, north,
            "PPCB override pointing at a region dropped from the post-refresh \
             topology must be skipped; fall-through to primary selection should \
             pick the only surviving region (`north`). The override map is not \
             pruned by topology refresh, so `region_not_in_topology` in \
             `ppcb_should_skip` is the only thing preventing a 1008 loop."
        );
    }

    #[test]
    fn resolve_endpoint_ppcb_override_skipped_when_endpoint_marked_unavailable() {
        // PPCB overrides must not resurrect transport-dead endpoints.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            central.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::TransportError,
            ),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![north.clone(), central.clone()].into(),
            preferred_write_endpoints: vec![north.clone(), central.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: true,
            default_endpoint: north.clone(),
        });

        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let partitions = make_partition_state_with_ppcb_override(&pk_range_id, central.clone());
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        retry_state.partition_key_range_id = Some(pk_range_id);

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, north,
            "PPCB override pointing at an endpoint marked unavailable (e.g. transport-dead) \
             must be skipped so the next attempt does not repeat the same connect failure"
        );
    }

    #[test]
    fn resolve_endpoint_ppcb_override_skipped_when_current_endpoint_failed_in_flight() {
        // PPCB skips override targets already failed by this operation.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![north.clone(), central.clone()].into(),
            preferred_write_endpoints: vec![north.clone(), central.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: north.clone(),
        });

        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let partitions = make_partition_state_with_ppcb_override(&pk_range_id, central.clone());
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        retry_state.partition_key_range_id = Some(pk_range_id);
        retry_state
            .pending_write_effects
            .push(make_pending_partition_mark_for_region("centralus"));

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, north,
            "PPCB override pointing at a region in the in-flight skip set must be skipped"
        );
    }

    // ── PPAF override does NOT honor excluded / unavailable ────────────

    #[test]
    fn resolve_endpoint_ppaf_override_honored_even_when_in_excluded_regions() {
        // PPAF targets the single current write region, even if the caller excluded it.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![north.clone(), central.clone()].into(),
            preferred_write_endpoints: vec![north.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: north.clone(),
        });

        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let mut partitions = PartitionEndpointState::new(PartitionFailoverOptions::default());
        partitions.per_partition_automatic_failover_enabled = true;
        partitions.failover_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: central.clone(),
                first_failed_endpoint: north.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: 0,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );
        retry_state.ppaf_write_retry_allowed = true;
        retry_state.partition_key_range_id = Some(pk_range_id);
        retry_state.excluded_regions = vec![crate::options::Region::from("centralus")];

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, central,
            "PPAF override target must be honored even when in excluded_regions: \
             for a single-master account there is no other write region, so the SDK \
             routes to the PPAF target and surfaces the failure to the caller"
        );
    }

    #[test]
    fn resolve_endpoint_ppaf_override_honored_even_when_endpoint_marked_unavailable() {
        // PPAF must still try the only write region even when it is marked unavailable.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let north = CosmosEndpoint::regional(
            "northcentralus".into(),
            Url::parse("https://test-northcentralus.documents.azure.com:443/").unwrap(),
        );
        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );

        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            central.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::TransportError,
            ),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![north.clone(), central.clone()].into(),
            preferred_write_endpoints: vec![north.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: north.clone(),
        });

        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let mut partitions = PartitionEndpointState::new(PartitionFailoverOptions::default());
        partitions.per_partition_automatic_failover_enabled = true;
        partitions.failover_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: central.clone(),
                first_failed_endpoint: north.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: 0,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );
        retry_state.ppaf_write_retry_allowed = true;
        retry_state.partition_key_range_id = Some(pk_range_id);

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, central,
            "PPAF override target must be honored even when marked unavailable: \
             single-master account has no other write region to fail over to"
        );
    }

    #[test]
    fn resolve_endpoint_ppcb_override_probe_skipped_when_first_failed_endpoint_failed_in_flight() {
        // ProbeCandidate retries must skip the probe target after it fails in-flight.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );
        let east = CosmosEndpoint::regional(
            "eastus2".into(),
            Url::parse("https://test-eastus2.documents.azure.com:443/").unwrap(),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![central.clone(), east.clone()].into(),
            preferred_write_endpoints: vec![central.clone(), east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: central.clone(),
        });

        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let mut partitions = PartitionEndpointState::new(PartitionFailoverOptions::default());
        partitions.per_partition_circuit_breaker_enabled = true;
        partitions.circuit_breaker_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                // Probe routes to `first_failed_endpoint` regardless of
                // `current_endpoint`; both point at centralus here.
                current_endpoint: east.clone(),
                first_failed_endpoint: central.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: 0,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::ProbeCandidate,
                failback_jitter: Duration::ZERO,
            },
        );
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true, // multi-write
            Vec::new(),
            3,
            2,
        );
        retry_state.partition_key_range_id = Some(pk_range_id);
        retry_state
            .pending_write_effects
            .push(make_pending_partition_mark_for_region("centralus"));

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_ne!(
            routing.endpoint, central,
            "PPCB ProbeCandidate must skip the probe target when its region is already in \
             the in-flight skip set; otherwise retry pins to the failing probe region"
        );
    }

    #[test]
    fn resolve_endpoint_ppcb_override_honored_when_current_endpoint_not_failed() {
        // Fresh attempts must honor PPCB overrides until the target fails in-flight.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );
        let east = CosmosEndpoint::regional(
            "eastus2".into(),
            Url::parse("https://test-eastus2.documents.azure.com:443/").unwrap(),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![central.clone(), east.clone()].into(),
            preferred_write_endpoints: vec![central.clone(), east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: central.clone(),
        });

        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let mut partitions = PartitionEndpointState::new(PartitionFailoverOptions::default());
        partitions.per_partition_circuit_breaker_enabled = true;
        let write_threshold = partitions.config.write_failure_threshold();
        partitions.circuit_breaker_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: east.clone(),
                first_failed_endpoint: central.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: write_threshold as i32 + 10,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        retry_state.partition_key_range_id = Some(pk_range_id);
        // pending_write_effects empty — first attempt of the operation.

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, east,
            "PPCB override with a healthy current_endpoint must be honored on a fresh attempt"
        );
    }

    #[test]
    fn resolve_endpoint_ppcb_override_pinned_to_unavailable_endpoint_reproduces_prod_403_3_loop() {
        // Production-shape repro: PPCB override threshold met while central is unavailable.
        // Multi-write leaves `pending_write_effects` empty, so availability is the only guard.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );
        let east = CosmosEndpoint::regional(
            "eastus2".into(),
            Url::parse("https://test-eastus2.documents.azure.com:443/").unwrap(),
        );

        // Multi-write 403/3 applied the endpoint mark before this retry.
        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            central.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::WriteForbidden,
            ),
        );

        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![central.clone(), east.clone()].into(),
            preferred_write_endpoints: vec![central.clone(), east.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: true,
            default_endpoint: central.clone(),
        });

        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::options::PartitionFailoverOptions;
        let pk_range_id: super::PartitionKeyRangeId = "0".parse().unwrap();
        let mut partitions = PartitionEndpointState::new(PartitionFailoverOptions::default());
        partitions.per_partition_circuit_breaker_enabled = true;
        // PPCB override still points at the now-unavailable endpoint.
        partitions.circuit_breaker_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: central.clone(),
                first_failed_endpoint: central.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                // Above the default threshold so PPCB failover triggers.
                write_failure_count: 10,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );
        let location = LocationSnapshot::for_tests_with_partitions(account, Arc::new(partitions));

        // Multi-write applies attempt effects immediately, leaving no in-flight skip set.
        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        retry_state.partition_key_range_id = Some(pk_range_id);

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_ne!(
            routing.endpoint, central,
            "BUG: PPCB override pinned the partition to centralus even though \
             centralus is in account.unavailable_endpoints. This is the \
             production 4-attempt-all-to-central failure mode. The PPCB \
             override-skip path in resolve_endpoint must honor \
             account.unavailable_endpoints (and excluded_regions) the same \
             way try_select_endpoint does."
        );
        assert_eq!(
            routing.endpoint, east,
            "with central in unavailable_endpoints and east the only other write \
             region, resolve_endpoint must route the next attempt to east"
        );
    }

    #[test]
    fn resolve_endpoint_rotates_to_next_region_via_location_index_on_multi_write() {
        // Pins LocationIndex rotation when multi-write PPCB-managed statuses
        // suppress endpoint marks and leave the deferred bucket empty.
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let central = CosmosEndpoint::regional(
            "centralus".into(),
            Url::parse("https://test-centralus.documents.azure.com:443/").unwrap(),
        );
        let east = CosmosEndpoint::regional(
            "eastus2".into(),
            Url::parse("https://test-eastus2.documents.azure.com:443/").unwrap(),
        );

        // The bumped LocationIndex is the only signal that central failed.
        let account = Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![central.clone(), east.clone()].into(),
            preferred_write_endpoints: vec![central.clone(), east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: true,
            default_endpoint: central.clone(),
        });
        let location = LocationSnapshot::for_tests(account);

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            true,
            Vec::new(),
            3,
            2,
        );
        // Mirror production advancement while preserving the empty multi-write bucket.
        retry_state.location = retry_state.location.next_for_generation(2, 0);
        assert_eq!(
            retry_state.location.index(),
            1,
            "precondition: LocationIndex must have advanced from 0 to 1"
        );
        assert!(
            retry_state.pending_write_effects.is_empty(),
            "precondition: multi-write deferred bucket must be empty"
        );

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(
            routing.endpoint, east,
            "BUG: with LocationIndex=1 and empty in_flight_failed, \
             resolve_endpoint must route to east. The multi-write \
             PPCB-managed path has no other skip signal — if LocationIndex \
             rotation regresses, the next attempt will pin to the just-failed \
             centralus and reproduce the same-region-retry loop."
        );
    }

    #[test]
    fn resolve_endpoint_does_not_skip_for_reads() {
        // The in-flight skip set is only consulted for writes — reads should
        // continue to use the standard preferred-endpoint selection even when
        // pending_write_effects is non-empty (which can never occur
        // for a read in practice, but the invariant should hold defensively).
        let operation = CosmosOperation::read_all_databases(test_account());

        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );

        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![east.clone()].into(),
            preferred_write_endpoints: vec![east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: east.clone(),
        }));

        let mut retry_state = crate::driver::pipeline::components::OperationRetryState::initial(
            0,
            false,
            Vec::new(),
            3,
            2,
        );
        retry_state
            .pending_write_effects
            .push(make_pending_partition_mark_for_region("eastus"));

        let routing = super::resolve_endpoint(
            &operation,
            &retry_state,
            &location,
            false,
            Duration::from_secs(60),
        );
        assert_eq!(routing.endpoint, east);
    }

    // ── flush_pending_write_effects: skip already-applied ──────────────

    #[test]
    fn already_applied_skips_endpoint_mark_when_endpoint_in_unavailable_set() {
        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let mut unavailable = std::collections::HashMap::new();
        unavailable.insert(
            east.url().clone(),
            (
                std::time::Instant::now(),
                crate::driver::routing::UnavailableReason::TransportError,
            ),
        );
        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![east.clone()].into(),
            preferred_write_endpoints: vec![east.clone()].into(),
            unavailable_endpoints: unavailable,
            multiple_write_locations_enabled: false,
            default_endpoint: east.clone(),
        }));

        let effect = LocationEffect::MarkEndpointUnavailable {
            endpoint: east,
            reason: crate::driver::routing::UnavailableReason::TransportError,
        };
        assert!(
            super::is_effect_already_applied(&effect, &location),
            "endpoint already in unavailable set must be considered already applied"
        );
    }

    #[test]
    fn already_applied_returns_false_when_endpoint_not_in_unavailable_set() {
        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![east.clone()].into(),
            preferred_write_endpoints: vec![east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: east.clone(),
        }));

        let effect = LocationEffect::MarkEndpointUnavailable {
            endpoint: east,
            reason: crate::driver::routing::UnavailableReason::TransportError,
        };
        assert!(!super::is_effect_already_applied(&effect, &location));
    }

    #[test]
    fn already_applied_skips_partition_mark_when_override_already_moved_past_failed_region() {
        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::driver::routing::partition_key_range_id::PartitionKeyRangeId;

        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let west = CosmosEndpoint::regional(
            "westus2".into(),
            Url::parse("https://test-westus2.documents.azure.com:443/").unwrap(),
        );
        let pk_range_id = PartitionKeyRangeId::from(String::from("0"));

        let mut partitions = PartitionEndpointState {
            per_partition_automatic_failover_enabled: true,
            ..Default::default()
        };
        partitions.failover_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: west.clone(), // already moved off eastus
                first_failed_endpoint: east.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: 0,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );

        let location = LocationSnapshot::for_tests_with_partitions(
            Arc::new(AccountEndpointState {
                generation: 0,
                preferred_read_endpoints: vec![east.clone(), west.clone()].into(),
                preferred_write_endpoints: vec![east.clone()].into(),
                unavailable_endpoints: Default::default(),
                multiple_write_locations_enabled: false,
                default_endpoint: east.clone(),
            }),
            Arc::new(partitions),
        );

        let effect = LocationEffect::MarkPartitionUnavailable(
            crate::driver::routing::UnavailablePartition {
                partition_key_range_id: Some(pk_range_id),
                region: Some("eastus".into()),
                is_read: false,
                is_partitioned_resource: true,
            },
        );
        assert!(
            super::is_effect_already_applied(&effect, &location),
            "PPAF override that has already moved past the failed region must be considered already applied"
        );
    }

    #[test]
    fn already_applied_returns_false_when_partition_override_still_on_failed_region() {
        use crate::driver::routing::partition_endpoint_state::{
            HealthStatus, PartitionEndpointState, PartitionFailoverEntry,
        };
        use crate::driver::routing::partition_key_range_id::PartitionKeyRangeId;

        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let pk_range_id = PartitionKeyRangeId::from(String::from("0"));

        let mut partitions = PartitionEndpointState {
            per_partition_automatic_failover_enabled: true,
            ..Default::default()
        };
        partitions.failover_overrides.insert(
            pk_range_id.clone(),
            PartitionFailoverEntry {
                current_endpoint: east.clone(), // still on the failed region
                first_failed_endpoint: east.clone(),
                failed_endpoints: Default::default(),
                read_failure_count: 0,
                write_failure_count: 0,
                first_failure_time: std::time::Instant::now(),
                last_failure_time: std::time::Instant::now(),
                health_status: HealthStatus::Unhealthy,
                failback_jitter: Duration::ZERO,
            },
        );

        let location = LocationSnapshot::for_tests_with_partitions(
            Arc::new(AccountEndpointState {
                generation: 0,
                preferred_read_endpoints: vec![east.clone()].into(),
                preferred_write_endpoints: vec![east.clone()].into(),
                unavailable_endpoints: Default::default(),
                multiple_write_locations_enabled: false,
                default_endpoint: east.clone(),
            }),
            Arc::new(partitions),
        );

        let effect = LocationEffect::MarkPartitionUnavailable(
            crate::driver::routing::UnavailablePartition {
                partition_key_range_id: Some(pk_range_id),
                region: Some("eastus".into()),
                is_read: false,
                is_partitioned_resource: true,
            },
        );
        assert!(
            !super::is_effect_already_applied(&effect, &location),
            "override still pointing at the failed region must NOT be skipped"
        );
    }

    #[test]
    fn already_applied_returns_false_when_no_partition_override_exists() {
        let east = CosmosEndpoint::regional(
            "eastus".into(),
            Url::parse("https://test-eastus.documents.azure.com:443/").unwrap(),
        );
        let location = LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: vec![east.clone()].into(),
            preferred_write_endpoints: vec![east.clone()].into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: east.clone(),
        }));

        let effect = LocationEffect::MarkPartitionUnavailable(
            crate::driver::routing::UnavailablePartition {
                partition_key_range_id: Some(
                    crate::driver::routing::partition_key_range_id::PartitionKeyRangeId::from(
                        String::from("0"),
                    ),
                ),
                region: Some("eastus".into()),
                is_read: false,
                is_partitioned_resource: true,
            },
        );
        assert!(!super::is_effect_already_applied(&effect, &location));
    }

    #[test]
    fn build_transport_request_sets_is_upsert_header() {
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::upsert_item(item).with_body(b"{}".to_vec());

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        let is_upsert = request
            .headers
            .get_optional_str(&HeaderName::from_static("x-ms-documentdb-is-upsert"))
            .expect("is-upsert header should be set");
        assert_eq!(is_upsert, "true");

        // Upsert targets the collection feed URL, not the individual document.
        assert_eq!(
            request.url.path(),
            "/dbs/testdb/colls/testcontainer/docs",
            "upsert should POST to the collection feed, not /docs/doc1"
        );
    }

    #[test]
    fn build_transport_request_omits_is_upsert_header_for_create() {
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        assert!(
            request
                .headers
                .get_optional_str(&HeaderName::from_static("x-ms-documentdb-is-upsert"))
                .is_none(),
            "is-upsert header should not be set for create"
        );

        // Create targets the collection feed URL, not the individual document.
        assert_eq!(
            request.url.path(),
            "/dbs/testdb/colls/testcontainer/docs",
            "create should POST to the collection feed, not /docs/doc1"
        );
    }

    #[test]
    fn build_transport_request_sets_batch_headers() {
        let operation = CosmosOperation::batch(test_container(), PartitionKey::from("pk1"))
            .with_body(b"[]".to_vec());

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        assert_eq!(
            request
                .headers
                .get_optional_str(&HeaderName::from_static("x-ms-cosmos-is-batch-request")),
            Some("True"),
            "is-batch-request header should be set"
        );
        assert_eq!(
            request
                .headers
                .get_optional_str(&HeaderName::from_static("x-ms-cosmos-batch-atomic")),
            Some("True"),
            "batch-atomic header should be set"
        );
        assert_eq!(
            request.headers.get_optional_str(&HeaderName::from_static(
                "x-ms-cosmos-batch-continue-on-error"
            )),
            Some("False"),
            "batch-continue-on-error header should be set"
        );
    }

    #[test]
    fn build_transport_request_omits_batch_headers_for_create() {
        let container = test_container();
        let operation = CosmosOperation::create_item(ItemReference::from_name(
            &container,
            PartitionKey::from("pk1"),
            "doc1",
        ))
        .with_body(b"{}".to_vec());

        let routing = test_routing();
        let activity_id = ActivityId::from_string("default-activity".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .expect("request should build");

        assert!(
            request
                .headers
                .get_optional_str(&HeaderName::from_static("x-ms-cosmos-is-batch-request"))
                .is_none(),
            "batch headers should not be set for create"
        );
    }

    #[test]
    fn build_transport_request_sets_priority_level_header() {
        let container = test_container();
        let operation = CosmosOperation::read_item(ItemReference::from_name(
            &container,
            PartitionKey::from("pk1"),
            "doc1",
        ));
        let routing = test_routing();
        let activity_id = ActivityId::new_uuid();

        let throughput_control = Some(ResolvedThroughputControl {
            throughput_bucket: None,
            priority_level: Some(PriorityLevel::Low),
        });

        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .unwrap();

        let priority = request
            .headers
            .get_optional_str(&HeaderName::from_static(
                request_header_names::PRIORITY_LEVEL,
            ))
            .expect("priority level header should be set");
        assert_eq!(priority, "Low");
        assert!(request
            .headers
            .get_optional_str(&HeaderName::from_static(
                request_header_names::THROUGHPUT_BUCKET
            ))
            .is_none());
    }

    #[test]
    fn build_transport_request_sets_throughput_bucket_header() {
        let container = test_container();
        let operation = CosmosOperation::read_item(ItemReference::from_name(
            &container,
            PartitionKey::from("pk1"),
            "doc1",
        ));
        let routing = test_routing();
        let activity_id = ActivityId::new_uuid();

        let throughput_control = Some(ResolvedThroughputControl {
            throughput_bucket: Some(42),
            priority_level: None,
        });

        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .unwrap();

        let bucket = request
            .headers
            .get_optional_str(&HeaderName::from_static(
                request_header_names::THROUGHPUT_BUCKET,
            ))
            .expect("throughput bucket header should be set");
        assert_eq!(bucket, "42");
        assert!(request
            .headers
            .get_optional_str(&HeaderName::from_static(
                request_header_names::PRIORITY_LEVEL
            ))
            .is_none());
    }

    #[test]
    fn build_transport_request_sets_both_throughput_headers() {
        let container = test_container();
        let operation = CosmosOperation::read_item(ItemReference::from_name(
            &container,
            PartitionKey::from("pk1"),
            "doc1",
        ));
        let routing = test_routing();
        let activity_id = ActivityId::new_uuid();

        let throughput_control = Some(ResolvedThroughputControl {
            throughput_bucket: Some(100),
            priority_level: Some(PriorityLevel::High),
        });

        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control,
        };
        let request =
            build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
                .unwrap();

        assert_eq!(
            request.headers.get_optional_str(&HeaderName::from_static(
                request_header_names::PRIORITY_LEVEL
            )),
            Some("High")
        );
        assert_eq!(
            request.headers.get_optional_str(&HeaderName::from_static(
                request_header_names::THROUGHPUT_BUCKET
            )),
            Some("100")
        );
    }

    #[test]
    fn build_transport_request_auto_emits_query_headers_for_query_operations() {
        let container = test_container();
        let pk_def = container.partition_key_definition().clone();

        // Single-partition item query (scoped to a logical partition via FeedRange)
        let feed_range = FeedRange::for_partition(PartitionKey::from("pk1"), &pk_def);
        let op = CosmosOperation::query_items(container.clone(), Some(feed_range))
            .with_body(br#"{"query":"SELECT * FROM c"}"#.to_vec());
        assert_query_headers_present(&op, "query_items (single partition)");

        // Cross-partition item query (full container via FeedRange::full)
        let op = CosmosOperation::query_items(container, Some(FeedRange::full()))
            .with_body(br#"{"query":"SELECT * FROM c"}"#.to_vec());
        assert_query_headers_present(&op, "query_items (cross partition)");

        // Offer query (used by find_offer / throughput poller path)
        let op = CosmosOperation::query_offers(test_account())
            .with_body(br#"{"query":"SELECT * FROM root"}"#.to_vec());
        assert_query_headers_present(&op, "query_offers");
    }

    /// Helper: builds a transport request from `op` and asserts the two
    /// well-known query headers (`x-ms-documentdb-isquery` and the
    /// `application/query+json` content type) are auto-emitted by the pipeline.
    fn assert_query_headers_present(op: &CosmosOperation, label: &str) {
        let routing = test_routing();
        let activity_id = ActivityId::new_uuid();
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        let req = build_transport_request(op, &OperationOverrides::default(), None, &ctx)
            .expect("request should build");
        assert_eq!(
            req.headers
                .get_optional_str(&HeaderName::from_static(request_header_names::IS_QUERY)),
            Some("True"),
            "{label}: x-ms-documentdb-isquery should be 'True'"
        );
        assert_eq!(
            req.headers
                .get_optional_str(&azure_core::http::headers::CONTENT_TYPE),
            Some(crate::models::cosmos_headers::QUERY_CONTENT_TYPE),
            "{label}: Content-Type should be application/query+json"
        );
    }
    // ── compute_execution_context ─────────────────────────────────────

    fn retry_state_with_counts(
        failover_retry_count: u32,
        session_token_retry_count: u32,
    ) -> super::OperationRetryState {
        let mut state = super::OperationRetryState::initial(0, false, Vec::new(), 3, 1);
        state.failover_retry_count = failover_retry_count;
        state.session_token_retry_count = session_token_retry_count;
        state
    }

    #[test]
    fn execution_context_initial_when_no_retries() {
        let state = retry_state_with_counts(0, 0);
        assert!(matches!(
            super::compute_execution_context(&state),
            ExecutionContext::Initial
        ));
    }

    #[test]
    fn execution_context_retry_when_session_retry_active() {
        // Session-retry takes precedence over failover-retry: when both
        // counters are non-zero, the most recent advance was the session
        // retry, so the attempt is annotated as a `Retry`.
        let state = retry_state_with_counts(1, 1);
        assert!(matches!(
            super::compute_execution_context(&state),
            ExecutionContext::Retry
        ));

        let state = retry_state_with_counts(0, 1);
        assert!(matches!(
            super::compute_execution_context(&state),
            ExecutionContext::Retry
        ));
    }

    #[test]
    fn execution_context_region_failover_when_only_failover_active() {
        let state = retry_state_with_counts(1, 0);
        assert!(matches!(
            super::compute_execution_context(&state),
            ExecutionContext::RegionFailover
        ));
    }

    // ── apply_hub_region_header ──────────────────────────────────────
    //
    // See HUB_REGION_PROCESSING_HEADER_SPEC.md §3.4 / public-spec §4.2.
    // The emission logic itself is a 4-line conditional; these tests
    // exercise both branches so AC-1/AC-5 don't drift on a refactor.

    fn build_minimal_transport_request() -> super::TransportRequest {
        let operation = CosmosOperation::read_all_databases(test_account());
        let routing = test_routing();
        let activity_id = ActivityId::from_string("hub-region-test".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
            .expect("request should build")
    }

    /// T-6 — When the latch is set on `retry_state`, the helper emits
    /// `x-ms-cosmos-hub-region-processing-only: True` on the transport
    /// request (AC-1).
    #[test]
    fn transport_request_emits_hub_region_header_when_latched() {
        let mut request = build_minimal_transport_request();
        let mut state = super::OperationRetryState::initial(0, false, Vec::new(), 3, 1);
        state.is_dataplane = true;
        state.hub_region_processing_only = true;

        super::apply_hub_region_header(&mut request, &state);

        let value = request.headers.get_optional_str(&HeaderName::from_static(
            request_header_names::HUB_REGION_PROCESSING_ONLY,
        ));
        assert_eq!(value, Some("True"));
    }

    /// T-7 — When the latch is NOT set, the helper does not emit the
    /// header. Covers AC-5 / cross-operation isolation guarantee at the
    /// emission layer.
    #[test]
    fn transport_request_omits_hub_region_header_when_not_latched() {
        let mut request = build_minimal_transport_request();
        let state = super::OperationRetryState::initial(0, false, Vec::new(), 3, 1);
        assert!(!state.hub_region_processing_only);

        super::apply_hub_region_header(&mut request, &state);

        let value = request.headers.get_optional_str(&HeaderName::from_static(
            request_header_names::HUB_REGION_PROCESSING_ONLY,
        ));
        assert!(
            value.is_none(),
            "hub-region header must not be present when latch is unset, got {value:?}",
        );
    }

    // ── apply_tentative_writes_header ────────────────────────────────
    //
    // Required on multi-write accounts. Without
    // `x-ms-cosmos-allow-tentative-writes: true`, satellite write
    // regions reject writes with `403 / 3 (WriteForbidden)`.

    fn build_write_transport_request() -> super::TransportRequest {
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());
        let routing = test_routing();
        let activity_id = ActivityId::from_string("tentative-writes-test".to_string());
        let ctx = TransportRequestContext {
            routing: &routing,
            activity_id: &activity_id,
            execution_context: ExecutionContext::Initial,
            deadline: None,
            resolved_session_token: None,
            throughput_control: None,
        };
        build_transport_request(&operation, &OperationOverrides::default(), None, &ctx)
            .expect("request should build")
    }

    fn tentative_writes_header(request: &super::TransportRequest) -> Option<&str> {
        request.headers.get_optional_str(&HeaderName::from_static(
            request_header_names::ALLOW_TENTATIVE_WRITES,
        ))
    }

    /// Multi-write account + write op → header MUST be emitted as "true".
    /// Without it, satellite write regions return
    /// `403 / 3 (WriteForbidden)`.
    #[test]
    fn tentative_writes_header_set_for_write_on_multi_write_account() {
        let mut request = build_write_transport_request();
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        super::apply_tentative_writes_header(&mut request, &operation, true);

        assert_eq!(tentative_writes_header(&request), Some("true"));
    }

    /// Reads on a multi-write account never need the tentative-writes
    /// header — they're idempotent and route per the read policy.
    #[test]
    fn tentative_writes_header_omitted_for_read_on_multi_write_account() {
        let mut request = build_minimal_transport_request();
        let operation = CosmosOperation::read_all_databases(test_account());

        super::apply_tentative_writes_header(&mut request, &operation, true);

        assert!(tentative_writes_header(&request).is_none());
    }

    /// Single-master accounts must not see the header even on writes; the
    /// hub region rejects unknown headers in some build configurations
    /// and this header is only meaningful for multi-write topologies.
    #[test]
    fn tentative_writes_header_omitted_for_write_on_single_master_account() {
        let mut request = build_write_transport_request();
        let item = ItemReference::from_name(&test_container(), PartitionKey::from("pk1"), "doc1");
        let operation = CosmosOperation::create_item(item).with_body(b"{}".to_vec());

        super::apply_tentative_writes_header(&mut request, &operation, false);

        assert!(tentative_writes_header(&request).is_none());
    }

    // ── apply_failover_delay ──────────────────────────────────────────

    #[tokio::test]
    async fn failover_delay_none_returns_immediately() {
        let start = std::time::Instant::now();
        super::apply_failover_delay(None).await;
        // Allow generous slack for CI scheduling jitter; the goal is to
        // confirm that `None` does not invoke the sleep path at all.
        assert!(start.elapsed() < Duration::from_millis(50));
    }

    #[tokio::test]
    async fn failover_delay_zero_returns_immediately() {
        let start = std::time::Instant::now();
        super::apply_failover_delay(Some(Duration::ZERO)).await;
        assert!(start.elapsed() < Duration::from_millis(50));
    }

    #[tokio::test(start_paused = true)]
    async fn failover_delay_real_value_actually_sleeps() {
        // Use tokio's pause-time to verify the sleep path is taken
        // without making the test wall-clock-slow.
        let start = tokio::time::Instant::now();
        super::apply_failover_delay(Some(Duration::from_secs(5))).await;
        assert!(start.elapsed() >= Duration::from_secs(5));
    }

    // ── enforce_deadline_or_timeout ───────────────────────────────────

    fn empty_options_view() -> crate::options::OperationOptionsView<'static> {
        crate::options::OperationOptionsView::new(None, None, None, None)
    }

    fn test_diagnostics() -> crate::diagnostics::DiagnosticsContextBuilder {
        crate::diagnostics::DiagnosticsContextBuilder::new(
            crate::models::ActivityId::from_string("test-deadline".to_owned()),
            std::sync::Arc::new(crate::options::DiagnosticsOptions::default()),
        )
    }

    #[test]
    fn enforce_deadline_none_is_ok() {
        let options = empty_options_view();
        let diagnostics = test_diagnostics();
        let result = super::enforce_deadline_or_timeout(None, &options, diagnostics);
        assert!(result.is_ok());
    }

    #[test]
    fn enforce_deadline_in_future_is_ok() {
        let options = empty_options_view();
        let diagnostics = test_diagnostics();
        let deadline = std::time::Instant::now() + Duration::from_secs(60);
        let result = super::enforce_deadline_or_timeout(Some(deadline), &options, diagnostics);
        assert!(result.is_ok());
    }

    #[test]
    fn enforce_deadline_in_past_returns_timeout_error_with_diagnostics() {
        let options = empty_options_view();
        let diagnostics = test_diagnostics();
        let deadline = std::time::Instant::now() - Duration::from_millis(1);
        let result = super::enforce_deadline_or_timeout(Some(deadline), &options, diagnostics);
        let err = result.expect_err("past deadline should produce an error");
        let msg = err.to_string();
        assert!(
            msg.contains("end-to-end operation timeout exceeded"),
            "unexpected error message: {msg}"
        );
        // Diagnostics must be attached so callers reading
        // `error.diagnostics()` on a timeout outcome get the
        // pipeline's tracked retry history rather than `None`.
        assert!(
            err.diagnostics().is_some(),
            "timeout error must carry finalized diagnostics"
        );
    }

    // ── classify_hedge_result (Part 4b) ────────────────────────────────

    fn http_result(status_code: u16, sub_status: Option<u32>) -> super::TransportResult {
        use azure_core::http::StatusCode;
        let mut status = crate::models::CosmosStatus::new(StatusCode::from(status_code));
        if let Some(v) = sub_status {
            status = status.with_sub_status(v as u16);
        }
        super::TransportResult::from_http_response(
            status,
            crate::models::CosmosResponseHeaders::default(),
            Vec::new(),
        )
    }

    #[test]
    fn classify_hedge_result_success_is_final() {
        let tr = http_result(200, None);
        assert!(matches!(
            super::classify_hedge_result(Ok(tr)),
            super::HedgeClass::Final(_)
        ));
    }

    #[test]
    fn classify_hedge_result_409_conflict_is_final() {
        // 409 is a final HTTP error — terminates hedging.
        let tr = http_result(409, None);
        assert!(matches!(
            super::classify_hedge_result(Ok(tr)),
            super::HedgeClass::Final(_)
        ));
    }

    #[test]
    fn classify_hedge_result_503_is_transient() {
        // 503 ServiceUnavailable is transient — keeps the other side racing.
        let tr = http_result(503, None);
        assert!(matches!(
            super::classify_hedge_result(Ok(tr)),
            super::HedgeClass::Transient
        ));
    }

    #[test]
    fn classify_hedge_result_404_1002_is_transient() {
        // 404/1002 ReadSessionNotAvailable is retriable.
        let tr = http_result(404, Some(1002));
        assert!(matches!(
            super::classify_hedge_result(Ok(tr)),
            super::HedgeClass::Transient
        ));
    }

    #[test]
    fn classify_hedge_result_deadline_exceeded_is_transient() {
        let tr =
            super::TransportResult::deadline_exceeded(crate::diagnostics::RequestSentStatus::Sent);
        assert!(matches!(
            super::classify_hedge_result(Ok(tr)),
            super::HedgeClass::Transient
        ));
    }

    #[test]
    fn classify_hedge_result_request_build_error_is_transient() {
        let err = crate::error::CosmosError::builder()
            .with_message("synthetic build error")
            .build();
        assert!(matches!(
            super::classify_hedge_result(Err(err)),
            super::HedgeClass::Transient
        ));
    }

    // ── result_is_final (Part 4b — pre-threshold PrimaryWin gating) ────
    //
    // Regression tests for the pre-threshold primary-completion branch
    // in `execute_hedged`. Before the fix the branch recorded
    // `PrimaryWin` unconditionally — including for `Transient` primary
    // outcomes — which would perpetually reset the
    // consecutive-hedge-win counter under sticky-fast-transient
    // traffic, neutralizing the very PPCB signal the counter was
    // designed to detect. `result_is_final` is the non-consuming
    // classifier used to gate the recording; it must agree with
    // `classify_hedge_result` for every input shape.

    #[test]
    fn result_is_final_success_is_true() {
        let tr = http_result(200, None);
        assert!(super::result_is_final(&tr));
    }

    #[test]
    fn result_is_final_409_conflict_is_true() {
        let tr = http_result(409, None);
        assert!(super::result_is_final(&tr));
    }

    #[test]
    fn result_is_final_503_is_false() {
        let tr = http_result(503, None);
        assert!(!super::result_is_final(&tr));
    }

    #[test]
    fn result_is_final_404_1002_is_false() {
        // 404/1002 ReadSessionNotAvailable is transient — the
        // pre-threshold branch must NOT record PrimaryWin (per the
        // c328cf50 over-correction).
        let tr = http_result(404, Some(1002));
        assert!(!super::result_is_final(&tr));
    }

    #[test]
    fn result_is_final_deadline_exceeded_is_false() {
        let tr =
            super::TransportResult::deadline_exceeded(crate::diagnostics::RequestSentStatus::Sent);
        assert!(!super::result_is_final(&tr));
    }

    #[test]
    fn result_is_final_429_ru_budget_and_hot_partition_are_final() {
        // RU-budget / hot-partition throttles cannot be relieved by racing a
        // second region, so they short-circuit the race.
        assert!(super::result_is_final(&http_result(429, Some(3200)))); // RU_BUDGET_EXCEEDED
        assert!(super::result_is_final(&http_result(429, Some(3210)))); // RU_BUDGET_EXCEEDED_FOR_MASTER
        assert!(super::result_is_final(&http_result(429, Some(3214)))); // HOT_PARTITION_KEY_THROTTLED
    }

    #[test]
    fn result_is_final_429_generic_and_3092_are_transient() {
        // A generic 429 and the transient-capacity 3092 sub-status keep the
        // other leg racing — another region may have spare capacity.
        assert!(!super::result_is_final(&http_result(429, None)));
        assert!(!super::result_is_final(&http_result(429, Some(3092))));
    }

    /// Cross-check: every `Ok(tr)` shape that `classify_hedge_result`
    /// maps to `HedgeClass::Final` must also be `true` under
    /// `result_is_final`, and vice versa. Keeping the two in lockstep
    /// is the load-bearing invariant for the pre-threshold PrimaryWin
    /// gating fix — drift between them re-opens the c328cf50 bug.
    #[test]
    fn result_is_final_agrees_with_classify_hedge_result() {
        let cases = [
            http_result(200, None),
            http_result(201, None),
            http_result(204, None),
            http_result(400, None),
            http_result(404, None),
            http_result(404, Some(1002)),
            http_result(409, None),
            http_result(412, None),
            http_result(429, None),
            http_result(429, Some(3092)),
            http_result(429, Some(3200)),
            http_result(429, Some(3210)),
            http_result(429, Some(3214)),
            http_result(500, None),
            http_result(503, None),
            super::TransportResult::deadline_exceeded(crate::diagnostics::RequestSentStatus::Sent),
        ];
        for tr in cases {
            let by_peek = super::result_is_final(&tr);
            let by_classify = matches!(
                super::classify_hedge_result(Ok(tr)),
                super::HedgeClass::Final(_)
            );
            assert_eq!(
                by_peek, by_classify,
                "result_is_final must agree with classify_hedge_result",
            );
        }
    }

    // ── finalize_hedge_attempt (Part 4b) ──────────────────────────────

    #[test]
    fn finalize_hedge_attempt_http_error_returns_error_with_status() {
        let tr = Box::new(http_result(409, None));
        let diagnostics = test_diagnostics();
        let err = super::finalize_hedge_attempt(tr, diagnostics)
            .expect_err("409 should be surfaced as an error");
        assert_eq!(u16::from(err.status().status_code()), 409);
    }

    #[test]
    fn finalize_hedge_attempt_deadline_returns_other_error() {
        let tr = Box::new(super::TransportResult::deadline_exceeded(
            crate::diagnostics::RequestSentStatus::Sent,
        ));
        let diagnostics = test_diagnostics();
        let err = super::finalize_hedge_attempt(tr, diagnostics)
            .expect_err("deadline should produce an error");
        assert!(err.to_string().contains("deadline exceeded"));
    }

    // ── DiagnosticsContextBuilder hedge helpers (Part 4b) ─────────────

    #[test]
    fn diagnostics_clone_for_hedge_attempt_starts_empty() {
        let parent = test_diagnostics();
        let child = parent.clone_for_hedge_attempt();
        // A fresh sub-builder must not carry the parent's request list,
        // status, or accumulated hedge diagnostics.
        assert_eq!(child.request_count(), 0);
    }

    #[test]
    fn diagnostics_merge_hedge_attempt_absorbs_requests() {
        use crate::diagnostics::{TransportHttpVersion, TransportKind};

        let mut parent = test_diagnostics();
        let mut child = parent.clone_for_hedge_attempt();

        let endpoint = crate::driver::routing::CosmosEndpoint::global(
            url::Url::parse("https://acct.example/").unwrap(),
        );
        let _ = child.start_request(
            super::ExecutionContext::Hedging,
            super::PipelineType::DataPlane,
            super::TransportSecurity::Secure,
            TransportKind::Gateway,
            TransportHttpVersion::Http11,
            &endpoint,
        );

        assert_eq!(child.request_count(), 1);
        assert_eq!(parent.request_count(), 0);

        parent.merge_hedge_attempt(child);
        // After merge the parent reflects the absorbed request and the
        // child is consumed.
        assert_eq!(parent.request_count(), 1);
    }

    // ── application-cancel harvest (Part 4c) ───────────────────────────

    #[test]
    fn deadline_elapsed_none_is_false() {
        assert!(!super::deadline_elapsed(None));
    }

    #[test]
    fn deadline_elapsed_future_is_false() {
        let d = std::time::Instant::now() + Duration::from_secs(60);
        assert!(!super::deadline_elapsed(Some(d)));
    }

    #[test]
    fn deadline_elapsed_past_is_true() {
        let d = std::time::Instant::now() - Duration::from_millis(1);
        assert!(super::deadline_elapsed(Some(d)));
    }

    #[test]
    fn application_cancelled_error_carries_app_cancel_message() {
        let err = super::application_cancelled_error(test_diagnostics());
        let msg = err.to_string();
        assert!(
            msg.contains("cancelled by application deadline"),
            "unexpected error message: {msg}"
        );
        // Typed-status invariant: telemetry/retry-evaluation can
        // discriminate a client-side hedge cancel from a service 408.
        let status = err.status();
        assert_eq!(
            status.status_code(),
            azure_core::http::StatusCode::RequestTimeout
        );
        assert_eq!(
            status.sub_status(),
            Some(crate::models::SubStatusCode::CLIENT_OPERATION_TIMEOUT)
        );
        // Diagnostics-on-error invariant: the synthesized error must
        // carry the operation's diagnostics chain (cf. P0 #1).
        assert!(
            err.diagnostics().is_some(),
            "application_cancelled_error must graft diagnostics"
        );
    }

    #[test]
    fn harvest_window_is_50ms() {
        // Load-bearing spec constant — surfaced as a test so the
        // HARVEST_WINDOW contract is enforced.
        assert_eq!(super::HARVEST_WINDOW, Duration::from_millis(50));
    }

    #[tokio::test]
    async fn deadline_signal_none_does_not_complete() {
        // A `None` deadline must produce a never-resolving future so
        // `select` against deadline collapses to whatever the other arm
        // is awaiting (zero deadline observation overhead when unset).
        let fut = super::deadline_signal(None);
        let timer = Box::pin(azure_core::sleep(
            azure_core::time::Duration::try_from(Duration::from_millis(20)).unwrap(),
        ));
        match futures::future::select(fut, timer).await {
            futures::future::Either::Right(((), _)) => { /* expected */ }
            futures::future::Either::Left(((), _)) => {
                panic!("deadline_signal(None) must never resolve");
            }
        }
    }

    #[tokio::test]
    async fn deadline_signal_past_resolves_immediately() {
        let past = std::time::Instant::now() - Duration::from_millis(10);
        let fut = super::deadline_signal(Some(past));
        // A short timer that should NOT win this race.
        let timer = Box::pin(azure_core::sleep(
            azure_core::time::Duration::try_from(Duration::from_millis(50)).unwrap(),
        ));
        match futures::future::select(fut, timer).await {
            futures::future::Either::Left(((), _)) => { /* expected */ }
            futures::future::Either::Right(((), _)) => {
                panic!("deadline_signal(past) must resolve before a 50ms sleep");
            }
        }
    }

    #[tokio::test]
    async fn harvest_remaining_attempt_merges_diagnostics_when_attempt_completes_in_window() {
        // Simulates a hedge attempt that produces a result quickly after
        // the app-cancel deadline fires — the harvest window MUST capture
        // its diagnostics into the parent.
        use crate::diagnostics::{TransportHttpVersion, TransportKind};

        let mut parent = test_diagnostics();
        let mut child = parent.clone_for_hedge_attempt();
        let endpoint = crate::driver::routing::CosmosEndpoint::global(
            url::Url::parse("https://acct.example/").unwrap(),
        );
        let _ = child.start_request(
            super::ExecutionContext::Hedging,
            super::PipelineType::DataPlane,
            super::TransportSecurity::Secure,
            TransportKind::Gateway,
            TransportHttpVersion::Http11,
            &endpoint,
        );

        // The "attempt" completes immediately (well within HARVEST_WINDOW).
        let attempt = Box::pin(async move {
            (
                Err::<super::TransportResult, _>(
                    crate::error::CosmosError::builder()
                        .with_message("synthetic transport error")
                        .build(),
                ),
                child,
            )
        });

        super::harvest_remaining_attempt(attempt, &mut parent, super::HARVEST_WINDOW).await;
        assert_eq!(parent.request_count(), 1);
    }

    #[tokio::test(start_paused = true)]
    async fn harvest_remaining_attempt_drops_attempt_when_window_exceeded() {
        // A hedge attempt that never completes within HARVEST_WINDOW
        // must be dropped — the parent diagnostics MUST NOT be mutated.
        use crate::diagnostics::{TransportHttpVersion, TransportKind};

        let mut parent = test_diagnostics();
        let mut child = parent.clone_for_hedge_attempt();
        let endpoint = crate::driver::routing::CosmosEndpoint::global(
            url::Url::parse("https://acct.example/").unwrap(),
        );
        let _ = child.start_request(
            super::ExecutionContext::Hedging,
            super::PipelineType::DataPlane,
            super::TransportSecurity::Secure,
            TransportKind::Gateway,
            TransportHttpVersion::Http11,
            &endpoint,
        );

        // The "attempt" sleeps far beyond HARVEST_WINDOW.
        let attempt = Box::pin(async move {
            azure_core::sleep(
                azure_core::time::Duration::try_from(Duration::from_secs(60)).unwrap(),
            )
            .await;
            (
                Err::<super::TransportResult, _>(
                    crate::error::CosmosError::builder()
                        .with_message("should not reach here")
                        .build(),
                ),
                child,
            )
        });

        // Drive the test clock past HARVEST_WINDOW.
        let parent_before = parent.request_count();
        super::harvest_remaining_attempt(attempt, &mut parent, super::HARVEST_WINDOW).await;
        assert_eq!(parent.request_count(), parent_before);
    }

    // ── Shared hub-region latch (Part 5) ──────────────────────────

    /// T-S5 — Eligibility predicate: data-plane + single-master → build.
    #[test]
    fn shared_hub_region_latch_eligibility_dataplane_single_master() {
        assert!(super::should_build_shared_hub_region_latch(
            super::PipelineType::DataPlane,
            false, // single-master
        ));
    }

    /// T-S6 — Eligibility predicate: multi-master → skip. Mirrors AC-4.
    #[test]
    fn shared_hub_region_latch_eligibility_skip_multi_master() {
        assert!(!super::should_build_shared_hub_region_latch(
            super::PipelineType::DataPlane,
            true, // multi-master
        ));
    }

    /// T-S7 — Eligibility predicate: metadata pipeline → skip. Mirrors
    /// AC-8 and the data-plane scope gate of
    /// `HUB_REGION_PROCESSING_HEADER_SPEC.md`.
    #[test]
    fn shared_hub_region_latch_eligibility_skip_metadata() {
        assert!(!super::should_build_shared_hub_region_latch(
            super::PipelineType::Metadata,
            false,
        ));
        assert!(!super::should_build_shared_hub_region_latch(
            super::PipelineType::Metadata,
            true,
        ));
    }

    /// T-S8 — Emission helper: per-state latch alone emits.
    #[test]
    fn should_emit_hub_region_header_per_state_only() {
        assert!(super::should_emit_hub_region_header(true, None));
    }

    /// T-S9 — Emission helper: shared latch alone (Acquire-load `true`)
    /// emits, even when per-state latch is `false`. This is the new
    /// cross-hedge propagation rule from PR #5815.
    #[test]
    fn should_emit_hub_region_header_shared_only() {
        use std::sync::{
            atomic::{AtomicBool, Ordering},
            Arc,
        };
        let shared = Arc::new(AtomicBool::new(true));
        assert!(super::should_emit_hub_region_header(false, Some(&shared)));
        // Sanity-check the atomic ordering pairing.
        assert!(shared.load(Ordering::Acquire));
    }

    /// T-S10 — Emission helper: neither latch set → no header. Mirrors
    /// AC-5 / `shared_hub_region_latch_no_1002_emits_no_header` from
    /// integration tests.
    #[test]
    fn should_emit_hub_region_header_neither_latched() {
        use std::sync::{atomic::AtomicBool, Arc};
        let shared = Arc::new(AtomicBool::new(false));
        assert!(!super::should_emit_hub_region_header(false, None));
        assert!(!super::should_emit_hub_region_header(false, Some(&shared)));
    }

    /// T-S11 — `apply_hub_region_header` emits the header when only the
    /// shared latch is `true` on the retry state. Mirrors the PR #5815
    /// `CrossRegionAvailabilityContext_PropagatesHubHeaderFlagToHedgedRequests`
    /// test at the emission layer.
    #[test]
    fn apply_hub_region_header_emits_when_only_shared_latch_set() {
        use std::sync::{atomic::AtomicBool, Arc};

        let mut request = build_minimal_transport_request();
        let shared = Arc::new(AtomicBool::new(true));
        let mut state = super::OperationRetryState::initial(0, false, Vec::new(), 3, 1);
        state.is_dataplane = true;
        state = state.with_shared_hub_region_latch(shared);
        assert!(!state.hub_region_processing_only);

        super::apply_hub_region_header(&mut request, &state);

        let value = request.headers.get_optional_str(&HeaderName::from_static(
            request_header_names::HUB_REGION_PROCESSING_ONLY,
        ));
        assert_eq!(value, Some("True"));
    }

    /// T-S12 — `apply_hub_region_header` omits the header when the
    /// shared latch is attached but its bool is `false`. Defends
    /// against an over-eager "present means set" emission rule.
    #[test]
    fn apply_hub_region_header_omits_when_shared_latch_present_but_false() {
        use std::sync::{atomic::AtomicBool, Arc};

        let mut request = build_minimal_transport_request();
        let shared = Arc::new(AtomicBool::new(false));
        let mut state = super::OperationRetryState::initial(0, false, Vec::new(), 3, 1);
        state.is_dataplane = true;
        state = state.with_shared_hub_region_latch(shared);

        super::apply_hub_region_header(&mut request, &state);

        let value = request.headers.get_optional_str(&HeaderName::from_static(
            request_header_names::HUB_REGION_PROCESSING_ONLY,
        ));
        assert!(value.is_none());
    }

    // ── try_advance_after_both_transient (region-aware advancement) ───
    //
    // After the `evaluate_hedge_eligibility` secondary picker change
    // (commit 5dea1c9) the raced secondary is no longer guaranteed
    // to sit at `primary_index + 1`. These tests pin the
    // `try_advance_after_both_transient` contract: the post-race
    // `LocationIndex` must NOT land on either of the two regions the
    // race already consumed, regardless of where the picker placed
    // the secondary relative to the primary.
    fn make_endpoint(region: &'static str) -> CosmosEndpoint {
        CosmosEndpoint::regional(
            region.into(),
            Url::parse(&format!("https://acc-{region}.documents.azure.com:443/"))
                .expect("test endpoint url should parse"),
        )
    }

    fn make_advance_test_state(
        location_index: usize,
        endpoint_count: usize,
    ) -> crate::driver::pipeline::components::OperationRetryState {
        let mut location = LocationIndex::initial(0);
        for _ in 0..location_index {
            location = location.next(endpoint_count);
        }
        crate::driver::pipeline::components::OperationRetryState {
            location,
            failover_retry_count: 0,
            session_token_retry_count: 0,
            backend_failover_retry_count: 0,
            max_failover_retries: 10,
            max_backend_failover_retries: 120,
            max_session_retries: 2,
            can_use_multiple_write_locations: false,
            is_dataplane: true,
            hub_region_processing_only: false,
            shared_hub_region_latch: None,
            excluded_regions: Vec::new(),
            session_retry_routing:
                crate::driver::pipeline::components::SessionRetryRouting::PreferredEndpoints,
            partition_key_range_id: None,
            ppaf_write_retry_allowed: false,
            ppcb_active: false,
            pending_write_effects: Vec::new(),
            hedge_already_fired: false,
        }
    }

    fn make_advance_test_location(regions: &[&'static str]) -> super::LocationSnapshot {
        let endpoints: Vec<CosmosEndpoint> = regions.iter().copied().map(make_endpoint).collect();
        let default = endpoints[0].clone();
        super::LocationSnapshot::for_tests(Arc::new(AccountEndpointState {
            generation: 0,
            preferred_read_endpoints: endpoints.clone().into(),
            preferred_write_endpoints: endpoints.into(),
            unavailable_endpoints: Default::default(),
            multiple_write_locations_enabled: false,
            default_endpoint: default,
        }))
    }

    fn dummy_last_error() -> crate::error::CosmosError {
        crate::error::CosmosError::builder()
            .with_message("test-both-transient")
            .build()
    }

    /// Regression: STAGE 7 picker now selects the secondary as the
    /// first endpoint with a region/key different from the primary,
    /// which can sit at an index earlier than the primary. The
    /// post-race advance must skip BOTH raced regions instead of
    /// blindly stepping `LocationIndex` by `+2`.
    ///
    /// Endpoints: [A, B, C, D]. Primary promoted to index 2 (C);
    /// picker walks from the front and lands on A (index 0) as the
    /// secondary. After `BothTransient` the next attempt must target
    /// D (the only untried region), not A again.
    #[test]
    fn try_advance_after_both_transient_skips_raced_regions_when_secondary_is_before_primary() {
        let regions = ["region-a", "region-b", "region-c", "region-d"];
        let location = make_advance_test_location(&regions);
        let mut state = make_advance_test_state(2, regions.len()); // primary = region-c

        let primary = crate::options::Region::new("region-c");
        let secondary = crate::options::Region::new("region-a");

        super::try_advance_after_both_transient(
            &mut state,
            &location,
            true,
            Some(&primary),
            Some(&secondary),
            dummy_last_error(),
        )
        .expect("budget should allow advance");

        let landed = location.account.preferred_read_endpoints[state.location.index()].region();
        assert_eq!(
            landed.map(crate::options::Region::as_str),
            Some("region-d"),
            "post-BothTransient LocationIndex must skip the raced primary and \
             the raced secondary (no matter where it sat) and land on the \
             only untried region",
        );
        assert_eq!(state.failover_retry_count, 2);
    }

    /// Sanity: when the secondary sits immediately after the primary
    /// (the historical layout the original `+2` advance assumed), the
    /// new implementation still skips both raced regions and lands on
    /// the next untried region.
    #[test]
    fn try_advance_after_both_transient_skips_raced_regions_when_secondary_is_after_primary() {
        let regions = ["region-a", "region-b", "region-c", "region-d"];
        let location = make_advance_test_location(&regions);
        let mut state = make_advance_test_state(0, regions.len()); // primary = region-a

        let primary = crate::options::Region::new("region-a");
        let secondary = crate::options::Region::new("region-b");

        super::try_advance_after_both_transient(
            &mut state,
            &location,
            true,
            Some(&primary),
            Some(&secondary),
            dummy_last_error(),
        )
        .expect("budget should allow advance");

        let landed = location.account.preferred_read_endpoints[state.location.index()].region();
        assert_eq!(
            landed.map(crate::options::Region::as_str),
            Some("region-c"),
            "secondary-after-primary case must still skip both raced regions",
        );
    }

    /// Edge case: only two regions exist and both were raced. The
    /// function must terminate (no infinite loop) and charge the two
    /// slots against the failover budget. With nowhere untried left
    /// to go, the `LocationIndex` is allowed to wrap; the next
    /// iteration's `resolve_endpoint` relies on the unavailable-
    /// endpoint de-prioritization to make a sensible choice.
    #[test]
    fn try_advance_after_both_transient_terminates_when_all_regions_are_raced() {
        let regions = ["region-a", "region-b"];
        let location = make_advance_test_location(&regions);
        let mut state = make_advance_test_state(0, regions.len());

        let primary = crate::options::Region::new("region-a");
        let secondary = crate::options::Region::new("region-b");

        let result = super::try_advance_after_both_transient(
            &mut state,
            &location,
            true,
            Some(&primary),
            Some(&secondary),
            dummy_last_error(),
        );

        assert!(
            result.is_ok(),
            "should not surface a terminal error when budget remains"
        );
        assert_eq!(
            state.failover_retry_count, 2,
            "two slots are always charged regardless of layout",
        );
    }

    /// Budget-exhaustion path remains untouched: when
    /// `failover_retry_count + 2 > max_failover_retries`, the
    /// function returns the supplied error without mutating
    /// `LocationIndex`.
    #[test]
    fn try_advance_after_both_transient_surfaces_terminal_error_when_budget_exhausted() {
        let regions = ["region-a", "region-b", "region-c"];
        let location = make_advance_test_location(&regions);
        let mut state = make_advance_test_state(0, regions.len());
        state.max_failover_retries = 1;
        let starting_index = state.location.index();

        let primary = crate::options::Region::new("region-a");
        let secondary = crate::options::Region::new("region-b");

        let result = super::try_advance_after_both_transient(
            &mut state,
            &location,
            true,
            Some(&primary),
            Some(&secondary),
            dummy_last_error(),
        );

        assert!(result.is_err(), "exhausted budget must surface terminal");
        assert_eq!(
            state.location.index(),
            starting_index,
            "exhausted budget must not mutate LocationIndex",
        );
        assert_eq!(state.failover_retry_count, 0);
    }

    /// When a hedge race ends in `BothTransient` and the failover budget
    /// is exhausted, the race is the terminal outcome, so the non-terminal
    /// path must still carry `strategy_config` + the diagnostic regions on
    /// the variant for the budget-exhausted handler to stamp them.
    #[test]
    fn both_transient_budget_exhausted_carries_hedge_diagnostics() {
        let threshold =
            crate::options::HedgeThreshold::new(std::time::Duration::from_millis(200)).unwrap();
        let strategy_config = super::HedgingStrategyConfig::new(threshold);
        let primary_for_diag = crate::options::Region::new("region-a");
        let secondary_for_diag = crate::options::Region::new("region-b");

        // Non-terminal both-transient (deadline = None) must return the
        // `BothTransient` variant carrying the data the budget-exhausted
        // handler needs to stamp diagnostics.
        let race = super::finalize_both_transient(
            &crate::models::ActivityId::from_string("both-transient-budget".to_owned()),
            None, // deadline not elapsed
            strategy_config,
            Some(crate::options::Region::new("region-a")),
            Some(crate::options::Region::new("region-b")),
            primary_for_diag.clone(),
            secondary_for_diag.clone(),
            test_diagnostics(),
            None,
            false,
        );

        let super::HedgedRaceResult::BothTransient {
            strategy_config: carried_strategy,
            primary_region_for_diag,
            secondary_region_for_diag,
            mut diagnostics,
            ..
        } = race
        else {
            panic!("deadline-not-elapsed both-transient must return BothTransient");
        };

        // The variant must carry exactly what the handler stamps —
        // otherwise the hedge diagnostics would be silently dropped on
        // the budget-exhausted terminal error.
        assert_eq!(carried_strategy, strategy_config);
        assert_eq!(primary_region_for_diag, primary_for_diag);
        assert_eq!(secondary_region_for_diag, secondary_for_diag);

        // Reproduce the budget-exhausted handler step: stamp the
        // both-transient hedge result with `deadline_elapsed = false`
        // (the budget, not the deadline, ended the race).
        diagnostics.set_hedge_diagnostics(super::HedgeDiagnostics::both_transient(
            carried_strategy,
            primary_region_for_diag,
            secondary_region_for_diag,
            false,
        ));
        let ctx = diagnostics.complete();

        let hedge = ctx
            .hedge_diagnostics()
            .expect("budget-exhausted both-transient must carry hedge diagnostics");
        assert_eq!(
            hedge.terminal_state(),
            crate::diagnostics::HedgeTerminalState::BothTransient {
                deadline_elapsed: false,
            },
        );
        assert_eq!(hedge.primary_region(), &primary_for_diag);
        assert_eq!(hedge.alternate_region(), Some(&secondary_for_diag));
        // No leg produced a final response in a both-transient terminal.
        assert_eq!(hedge.response_region(), None);
    }
}