zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! Request routing logic for optimal worker selection.

use std::sync::atomic::{AtomicUsize, Ordering};

use serde::{Deserialize, Serialize};

use super::balance::BalanceManager;
use super::worker::{Worker, WorkerRegistry};

/// Routing strategy for worker selection
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RoutingStrategy {
    /// Select worker with lowest price (default)
    #[default]
    BestPrice,
    /// Select worker with lowest latency
    BestLatency,
    /// Select worker with most available resources
    BestAvailability,
    /// Round-robin across all healthy workers
    RoundRobin,
    /// Random worker selection
    Random,
    /// Weighted random based on capacity
    WeightedCapacity,
}

impl RoutingStrategy {
    pub fn as_str(&self) -> &'static str {
        match self {
            RoutingStrategy::BestPrice => "best_price",
            RoutingStrategy::BestLatency => "best_latency",
            RoutingStrategy::BestAvailability => "best_availability",
            RoutingStrategy::RoundRobin => "round_robin",
            RoutingStrategy::Random => "random",
            RoutingStrategy::WeightedCapacity => "weighted_capacity",
        }
    }

    pub fn description(&self) -> &'static str {
        match self {
            RoutingStrategy::BestPrice => "Lowest cost per compute",
            RoutingStrategy::BestLatency => "Fastest response time",
            RoutingStrategy::BestAvailability => "Most available resources",
            RoutingStrategy::RoundRobin => "Even distribution",
            RoutingStrategy::Random => "Random selection",
            RoutingStrategy::WeightedCapacity => "Weighted by capacity",
        }
    }
}

impl std::str::FromStr for RoutingStrategy {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "best_price" | "price" | "cheap" | "cheapest" => Ok(RoutingStrategy::BestPrice),
            "best_latency" | "latency" | "fast" | "fastest" => Ok(RoutingStrategy::BestLatency),
            "best_availability" | "availability" | "available" => {
                Ok(RoutingStrategy::BestAvailability)
            }
            "round_robin" | "robin" | "rr" => Ok(RoutingStrategy::RoundRobin),
            "random" | "rand" => Ok(RoutingStrategy::Random),
            "weighted_capacity" | "weighted" | "capacity" => Ok(RoutingStrategy::WeightedCapacity),
            _ => Err(format!("Unknown routing strategy: {}", s)),
        }
    }
}

/// Resource requirements for a compute request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceRequirements {
    /// Required CPU cores
    #[serde(default = "default_cpus")]
    pub cpus: f64,
    /// Required memory in bytes
    #[serde(default = "default_memory")]
    pub memory_bytes: u64,
    /// Required GPUs
    #[serde(default)]
    pub gpus: u32,
    /// Preferred worker type (optional)
    #[serde(default)]
    pub worker_type: Option<String>,
    /// Required tags (optional)
    #[serde(default)]
    pub tags: Vec<String>,
    /// Estimated duration in seconds (for cost estimation)
    #[serde(default = "default_duration")]
    pub estimated_duration_secs: f64,
    /// Routing strategy (optional, defaults to BestPrice)
    #[serde(default)]
    pub strategy: RoutingStrategy,
    /// Requested timeout in seconds. The request will be aborted after this duration.
    /// Workers whose max_timeout_secs is > 0 and < this value will be excluded.
    #[serde(default)]
    pub timeout_secs: f64,
    /// If true, require remote execution only (no local fallback)
    #[serde(default)]
    pub remote_only: bool,
    /// Maximum yen to spend on this job. Auto-derives an effective timeout
    /// so the job stops when its budget is exhausted.
    #[serde(default)]
    pub budget: Option<f64>,
    /// Deprecated / no-op for routing: worker selection is the managing
    /// broker's private authority, never a client-routable target (see the
    /// 2026-07-11 key-derived-identity amendment's Routing addendum). Kept in
    /// the request schema for backward-compat deserialization only — a value
    /// here never selects, restricts, or rejects a worker.
    #[serde(default)]
    pub target_worker: Option<String>,
    /// Restrict dispatch to a specific node (accepts `zc://node-…` or bare name).
    #[serde(default)]
    pub target_node: Option<String>,
    /// Minimum advertised GPU VRAM (GiB) a candidate must have. `None` (the
    /// default, including every spec written before this field existed)
    /// applies no VRAM floor at all. A worker that advertises no VRAM is
    /// excluded once a minimum is set -- "we don't know" is not "yes"
    /// (zakuro-ai/zc#345, L'Atelier phase-1 placement).
    #[serde(default)]
    pub min_vram_gb: Option<u32>,
    /// The CPython version that built the payload (`"3.12"` or `"3.12.3"`).
    /// A cloudpickled function runs only on the same major.minor (zc#327):
    /// a candidate whose worker reports another, or none at all, is ruled
    /// out. `None` (every client that does not send it) applies no filter.
    #[serde(default)]
    pub python: Option<String>,
    /// Mesh placement policy (zc#474): `own_first`, `best_price_mesh` or
    /// `mesh_only`. `None` = not stated, which resolves to the hub's
    /// account-level default and then `own_first`; an unknown value is a
    /// parse error (a 400 at `/execute`).
    #[serde(default)]
    pub placement: Option<super::placement::Placement>,
}

fn default_cpus() -> f64 {
    1.0
}
fn default_memory() -> u64 {
    1024 * 1024 * 1024
} // 1 GiB
fn default_duration() -> f64 {
    1.0
}

impl Default for ResourceRequirements {
    fn default() -> Self {
        Self {
            cpus: 1.0,
            memory_bytes: 1024 * 1024 * 1024,
            gpus: 0,
            worker_type: None,
            tags: Vec::new(),
            estimated_duration_secs: 1.0,
            strategy: RoutingStrategy::default(),
            timeout_secs: 0.0, // 0 = no explicit timeout
            remote_only: false,
            budget: None,
            target_worker: None,
            target_node: None,
            min_vram_gb: None,
            python: None,
            placement: None,
        }
    }
}

/// Routing decision result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingDecision {
    /// Selected worker
    pub worker: Worker,
    /// Estimated cost in yen
    pub estimated_cost: f64,
    /// Reason for selection
    pub reason: String,
    /// Alternative workers considered
    pub alternatives_count: usize,
}

/// Routing error
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingError {
    /// Error code
    pub code: String,
    /// Error message
    pub message: String,
}

impl RoutingError {
    pub fn no_workers() -> Self {
        Self {
            code: "NO_WORKERS".to_string(),
            message: "No workers available".to_string(),
        }
    }

    pub fn no_capacity(requirements: &ResourceRequirements) -> Self {
        Self {
            code: "NO_CAPACITY".to_string(),
            message: format!(
                "No worker has capacity for {} CPUs, {} bytes memory, {} GPUs",
                requirements.cpus, requirements.memory_bytes, requirements.gpus
            ),
        }
    }

    pub fn insufficient_funds(required: f64, available: f64) -> Self {
        Self {
            code: "INSUFFICIENT_FUNDS".to_string(),
            message: format!(
                "Insufficient balance: need {:.4}, have {:.4}",
                required, available
            ),
        }
    }

    pub fn rate_limited() -> Self {
        Self {
            code: "RATE_LIMITED".to_string(),
            message: "Rate limit exceeded".to_string(),
        }
    }

    pub fn worker_type_unavailable(worker_type: &str) -> Self {
        Self {
            code: "WORKER_TYPE_UNAVAILABLE".to_string(),
            message: format!("No workers of type '{}' available", worker_type),
        }
    }

    pub fn timeout_incompatible(timeout: f64) -> Self {
        Self {
            code: "TIMEOUT_INCOMPATIBLE".to_string(),
            message: format!(
                "No worker accepts timeout of {:.1}s. Reduce timeout or wait for a compatible worker.",
                timeout
            ),
        }
    }

    /// Tags were required and no healthy worker carries them all.
    /// `missing` lists the required tags no healthy worker has at all.
    pub fn tags_unavailable(required: &[String], missing: &[&str]) -> Self {
        let detail = if missing.is_empty() {
            "no single worker carries them all".to_string()
        } else {
            format!("no worker advertises: {}", missing.join(", "))
        };
        Self {
            code: "NO_WORKERS_WITH_TAGS".to_string(),
            message: format!(
                "No healthy worker carries the required tag(s) [{}] ({})",
                required.join(", "),
                detail
            ),
        }
    }

    pub fn quota_exceeded() -> Self {
        Self {
            code: "QUOTA_EXCEEDED".to_string(),
            message: "All workers have exceeded their request quota for this time window"
                .to_string(),
        }
    }
}

/// Router for selecting optimal workers
pub struct Router {
    /// Round-robin counter for even distribution
    round_robin_counter: AtomicUsize,
    /// This broker's own key-derived node fingerprint, bare (no `zc://node-`).
    ///
    /// The only thing a `target_node` pin can be matched against. `None` when
    /// no identity was supplied — a pin is then unmatchable and rejected,
    /// because a broker that cannot prove it is the named node must not
    /// answer for it.
    node_fp: Option<String>,
}

/// What a task handed to `w` right now should take: the work already in
/// front of it plus its own. Service time alone makes a saturated fast worker
/// look idle.
fn expected_completion_ms(w: &Worker) -> f64 {
    w.avg_latency_ms * (1.0 + w.active_requests as f64)
}

/// Which of this broker's workers a selection may consider.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope<'a> {
    /// Every healthy worker the registry holds, peer-synced ones included.
    Any,
    /// Only workers this broker owns and executes itself.
    ///
    /// Ownership, not the spelling of a URI, decides: a broker sharing a
    /// WireGuard sidecar's network namespace reaches its own worker through
    /// the container gateway and registers it under a `zc://` handle carrying
    /// no IP at all (staging 2026-08-14). `own_ip` is this node's mesh address
    /// when one is known.
    Local { own_ip: Option<&'a str> },
    /// Only workers that are NOT this broker's own (peer-synced). What
    /// `mesh_only` placement (zc#481) may use on the paths that do not publish.
    Mesh { own_ip: Option<&'a str> },
}

/// Choose with the measured policy rather than `requirements.strategy`.
///
/// Passed alongside every [`Selection`] as a required argument rather than
/// carried inside it: a path cannot be wired up without saying whether the
/// policy routes it, which is how "the policy only applies to some traffic"
/// stops being possible to write by accident.
pub struct Adaptive<'a> {
    pub rng: &'a mut crate::broker::sampler::Rng,
    pub weights: &'a crate::broker::policy::Weights,
}

/// One worker selection: everything about it except who does the choosing.
///
/// Every path that picks a worker builds one of these and hands it to
/// [`Router::select`]. What used to be four hand-written selectors that drifted
/// apart is now these fields; the choosing — the strategy, its queue term, the
/// tie spread and the adaptive policy — happens once, for all of them.
///
/// There is deliberately no `Default` and no constructor. A new concern
/// becomes a new field, and every caller then has to say what it wants about
/// it. That is the failure #252 was: a path that had quietly stopped honouring
/// `strategy`, with nothing to fail.
#[derive(Debug, Clone, Copy)]
pub struct Selection<'a> {
    pub requirements: &'a ResourceRequirements,
    /// Which workers are eligible at all.
    pub scope: Scope<'a>,
    /// Rule out workers that cannot fit the request, or that refuse its
    /// timeout.
    ///
    /// Off where a broker executes rather than brokers: local mode and the
    /// publish-lock path have always handed work to a healthy worker whatever
    /// it reported free, and turning that on here would start failing jobs
    /// that run today. It is a field with a reason rather than a rule one path
    /// silently forgot.
    pub check_capacity: bool,
    /// Rule out workers whose type or tags do not match the request.
    pub check_labels: bool,
    /// Rule out workers dearer than this per hour. `f64::INFINITY` = uncapped.
    pub max_price_per_hour: f64,
    /// `Some(balance)` when this user pays for the work: the chosen worker's
    /// estimate is checked against it, and the decision carries that estimate.
    /// `None` on the unbilled paths — local mode, self-execution, and an
    /// accepted peer offer, where the requester's broker holds the money.
    pub billed_to: Option<f64>,
}

/// Whether this broker owns `w` and may execute it itself.
///
/// `source_node` is the registry's authoritative ownership marker: `None`
/// means this broker registered it, `Some(node)` that it arrived by a peer
/// sync. It is checked first and vetoes the rest, so a peer's worker can never
/// be executed as local — and billed at 0.0 — however its URI is spelt.
/// `explicit_local` is the operator naming the address in `ZAKURO_WORKERS`,
/// which only ever meant anything for a worker this broker owns.
pub(crate) fn is_own_worker(w: &Worker, own_ip: Option<&str>) -> bool {
    // Ownership first, and it is a veto. A worker that arrived by peer sync is
    // never ours whatever its URI says: a peer reached over a loopback tunnel,
    // through a rewritten discovery URI, or on an address that merely CONTAINS
    // ours would otherwise pass the address arms below and be executed as
    // local — which means billed at 0.0, so the machine that ran the work is
    // never paid (#297/#329). Only `explicit_local` used to carry this gate;
    // the address arms are the ones a mesh actually trips.
    if w.source_node.is_some() {
        return false;
    }
    w.uri.contains("127.0.0.1")
        || w.uri.contains("localhost")
        || own_ip.is_some_and(|ip| w.uri.contains(ip))
        || w.explicit_local
}

/// What `best_price` must rank on: what the requester will actually be
/// CHARGED, not what the worker advertises.
///
/// Three things were wrong, and together they made the strategy named "lowest
/// cost per compute" the second *most* expensive on a live fleet (#335):
///
/// 1. It ranked on `estimate_cost(estimated_duration_secs)` alone, and the
///    default duration is 1s while `min_charge` defaults to ¥0.15. Any worker
///    at or below ¥540/h floors to exactly ¥0.15 — 9 of 13 workers on the
///    measured fleet — so the rate it was supposed to compare was erased.
///
///    No single reference duration fixes that: the floor stops binding only
///    above `3600 * min_charge / price`, which is 1s at ¥540/h and 360s
///    at ¥1.5. A 10s reference would still tie every worker under ¥54. So
///    the estimate and the rate are compared lexicographically — the charged
///    estimate first, because that is what the job actually costs, and the
///    hourly rate only where the floor has made the estimates equal.
///
/// 2. Free placement is decided elsewhere, so a zero-charge local worker
///    ranked by its advertised `price_per_hour` like any other. Ranking free
///    work first is the whole point of a cheapest-first strategy, and it is
///    what made `best_latency` beat `best_price` on price by an infinite
///    ratio — 0.0000 against ¥0.2239.
///
/// 3. `min_by` returns the first of equals and "first" came from a `DashMap`
///    iteration, which is shard order: unordered, and unstable across calls.
///    So among tied workers the winner was arbitrary, which is precisely why
///    `best_price` measured the same as `random`. Ties break on worker id.
fn price_key(w: &Worker, duration_secs: f64) -> (u8, i64, i64, String) {
    (
        // A worker this broker registered itself runs on this node; one that
        // arrived from a peer roster carries that peer as `source_node`. Same
        // signal the adaptive policy already uses for locality.
        u8::from(w.source_node.is_some()),
        (w.pricing.estimate_cost(duration_secs) * 1e9) as i64,
        (w.pricing.price_per_hour * 1e9) as i64,
        w.id.clone(),
    )
}

/// What `best_availability` must rank on: how much of itself a worker has
/// left, not how big it is.
///
/// The old score added `cpus_available` to gibibytes of memory. Those units
/// are incommensurable and the sum is dominated by whichever number happens
/// to be larger — memory, on a 62 GiB box — so the strategy just picked the
/// biggest machine. On the measured fleet the winner answered in 2410ms and
/// was billed, while the workers it passed over answered in ~5ms and were
/// free: 0% free work, worst latency and worst cost of any strategy.
///
/// The unit is **free cores**, and memory enters as a fraction rather than a
/// second addend. A worker with 32 idle cores really does have more available
/// resource than one with 1, so the score still prefers the bigger idle box —
/// that part of the old behaviour was right and stays. What changes is that a
/// big box which is nearly full no longer outranks a small one that is empty,
/// because its memory fraction pulls its free cores down.
///
/// The load penalty is now one core per in-flight request, which is the same
/// unit as the rest of the score and therefore able to move it. At a flat 0.5
/// against scores spanning 12.9..94.1 it took ~160 concurrent requests to
/// change the ranking, so `active_requests` — the one dynamic input the
/// strategy has — could never actually balance anything.
///
/// Note this deliberately does not consider price or latency. "Most available
/// resources" is not a claim about either, and a strategy that quietly
/// optimised cost would be the same category of lie this is fixing.
fn availability_score(w: &Worker) -> f64 {
    let mem_frac = match w.resources.memory_total > 0 {
        true => w.resources.memory_available as f64 / w.resources.memory_total as f64,
        false => 0.0,
    };
    w.resources.cpus_available * mem_frac - w.active_requests as f64
}

/// What `weighted_capacity` must weight by.
///
/// Same correction as `availability_score`, and it mattered more here: the
/// old weight multiplied cores BY gibibytes, so the bias was squared rather
/// than merely present. The local node ended up with 1.7% of the fleet's
/// total weight and the bench duly reported 1% of the work landing free.
///
/// Weighting by free cores makes the share proportional to capacity, which is
/// what "weighted by capacity" says: an 8-core node among two 32-core nodes
/// gets 8/72, about 11%, not 1.7%.
fn capacity_weight(w: &Worker) -> f64 {
    // The floor keeps a fully-loaded worker reachable rather than starved out
    // of the draw entirely.
    availability_score(w).max(0.0) + 0.01
}

/// Whether `w` satisfies a requested `min_vram_gb`. `None` always passes --
/// old clients and every non-GPU job are unaffected. A worker that advertises
/// no VRAM at all fails once a minimum is set: absence of data is not proof
/// of capacity.
/// `major.minor` of a version string: `"3.12.3"` -> `"3.12"`.
fn python_minor(v: &str) -> &str {
    match v.match_indices('.').nth(1) {
        Some((i, _)) => &v[..i],
        None => v,
    }
}

/// Whether `w`'s interpreter can run a payload built on `python`. Unknown is
/// not compatible: a worker too old to report its version is exactly the one
/// most likely to be on another interpreter.
pub(crate) fn runs_payload(w: &Worker, python: Option<&str>) -> bool {
    match python {
        None => true,
        Some(want) => w
            .hardware
            .python_version
            .as_deref()
            .is_some_and(|have| python_minor(have) == python_minor(want)),
    }
}

/// The error for a request whose required `tags` no worker in `workers` can
/// satisfy, or `None` when `tags` is empty or some worker carries them all.
/// Names the required tags that no worker has, so "no apple-silicon worker"
/// is stated, not inferred from a generic "no workers".
pub fn tags_unsatisfied(workers: &[Worker], tags: &[String]) -> Option<RoutingError> {
    if tags.is_empty()
        || workers
            .iter()
            .any(|w| tags.iter().all(|t| w.tags.contains(t)))
    {
        return None;
    }
    let missing: Vec<&str> = tags
        .iter()
        .filter(|t| !workers.iter().any(|w| w.tags.contains(t)))
        .map(String::as_str)
        .collect();
    Some(RoutingError::tags_unavailable(tags, &missing))
}

pub(crate) fn meets_vram(w: &Worker, min_vram_gb: Option<u32>) -> bool {
    match min_vram_gb {
        None => true,
        Some(min) => w.hardware.gpu_vram_gb.is_some_and(|v| v >= min),
    }
}

/// Why `w` does not satisfy `req`'s hard constraints under the policy
/// `select_worker` applies (`Scope::Any`, capacity + label checks on, no
/// price cap) -- `None` when it is fully eligible.
///
/// This is NOT the same code `select()` runs: `select()` has its own
/// `retain()` chain (worker_type, tags, price cap, `can_handle`,
/// `meets_vram`, timeout) that fails fast with one specific `RoutingError`
/// per stage, because that is what gives `/execute` its distinct error codes
/// (`WORKER_TYPE_UNAVAILABLE`, `NO_CAPACITY`, `TIMEOUT_INCOMPATIBLE`, ...).
/// This function re-implements the same predicates in one pass so `/route`
/// can report a reason for EVERY excluded worker, not just the first stage
/// that emptied the candidate list. The two are kept honest with each other
/// by `route_dry_run_tests::route_dry_run_agrees_with_select_worker_everywhere`
/// (a parity test across worker/requirement/strategy combinations), not by
/// sharing a call path -- a filter added to one and not the other is a bug
/// that test exists to catch.
fn ineligibility_reason(w: &Worker, req: &ResourceRequirements) -> Option<String> {
    if let Some(wt) = req.worker_type.as_deref() {
        if w.worker_type != wt {
            return Some(format!(
                "worker_type '{}' != required '{}'",
                w.worker_type, wt
            ));
        }
    }
    if !req.tags.is_empty() {
        let missing: Vec<&str> = req
            .tags
            .iter()
            .filter(|t| !w.tags.contains(t))
            .map(String::as_str)
            .collect();
        if !missing.is_empty() {
            return Some(format!("missing required tags: {}", missing.join(", ")));
        }
    }
    if !w.can_handle(req.cpus, req.memory_bytes, req.gpus) {
        return Some(format!(
            "insufficient capacity: needs {:.2} cpus / {} bytes mem / {} gpus; has {:.2} cpus / {} bytes mem / {} gpus available (or unhealthy)",
            req.cpus,
            req.memory_bytes,
            req.gpus,
            w.resources.cpus_available,
            w.resources.memory_available,
            w.resources.gpus_available
        ));
    }
    if req.timeout_secs > 0.0 && w.max_timeout_secs > 0.0 && w.max_timeout_secs < req.timeout_secs {
        return Some(format!(
            "max_timeout_secs {:.1} < requested timeout_secs {:.1}",
            w.max_timeout_secs, req.timeout_secs
        ));
    }
    if !runs_payload(w, req.python.as_deref()) {
        return Some(match w.hardware.python_version.as_deref() {
            Some(have) => format!(
                "python {have} cannot run a payload built on {}",
                req.python.as_deref().unwrap_or("")
            ),
            None => "worker reports no python version".to_string(),
        });
    }
    if !meets_vram(w, req.min_vram_gb) {
        return Some(match (req.min_vram_gb, w.hardware.gpu_vram_gb) {
            (Some(min), Some(have)) => format!("gpu_vram_gb {have} < min_vram_gb {min}"),
            (Some(min), None) => format!("no advertised gpu_vram_gb < min_vram_gb {min}"),
            (None, _) => unreachable!("meets_vram only fails when min_vram_gb is Some"),
        });
    }
    None
}

/// One worker as `/route` (contract zc#345 §4) reports it: everything a
/// caller needs to understand or re-derive the ranking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteCandidate {
    pub worker: Worker,
    pub estimated_cost: f64,
}

/// A healthy worker `/route` ruled out before ranking, and why.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExcludedWorker {
    pub worker_id: String,
    pub reason: String,
}

/// The full answer to "what would `/execute` do right now" -- a preview that
/// executes, reserves, bills and mutates nothing (contract zc#345 §4).
/// `chosen` is `None` only when every healthy worker was excluded; the caller
/// (`/route`'s HTTP handler) turns that into a 404 carrying `excluded`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteDryRun {
    pub strategy: RoutingStrategy,
    pub chosen: Option<RouteCandidate>,
    /// Ranked best first; `chosen` is `candidates[0]` when non-empty.
    pub candidates: Vec<RouteCandidate>,
    pub excluded: Vec<ExcludedWorker>,
}

impl Router {
    /// Create a new router with no node identity. A `target_node` pin is
    /// rejected until [`with_node`](Self::with_node) supplies one.
    pub fn new() -> Self {
        Self {
            round_robin_counter: AtomicUsize::new(0),
            node_fp: None,
        }
    }

    /// Tell the router which node it is, so a pin naming that node resolves
    /// here instead of being pushed out to the mesh.
    ///
    /// `fp` may be given bare or in either prefixed spelling; it is stored
    /// bare so the comparison has one shape.
    pub fn with_node(mut self, fp: impl AsRef<str>) -> Self {
        self.node_fp = Some(super::node_identity::strip_node_arg(fp.as_ref()).to_string());
        self
    }

    /// Get all available routing strategies
    pub fn available_strategies() -> Vec<RoutingStrategy> {
        vec![
            RoutingStrategy::BestPrice,
            RoutingStrategy::BestLatency,
            RoutingStrategy::BestAvailability,
            RoutingStrategy::RoundRobin,
            RoutingStrategy::Random,
            RoutingStrategy::WeightedCapacity,
        ]
    }

    /// Honour a mesh pin (`target_node` only — a broker pin) against LOCAL
    /// workers.
    ///
    /// `target_worker` is intentionally NOT honoured: worker selection is this
    /// broker's private authority, never a client-routable target (see
    /// docs/superpowers/specs/2026-07-11-zc-key-derived-identity-amendment.md
    /// "Routing addendum"). A client-supplied `target_worker` is a no-op for
    /// routing.
    ///
    /// Returns `None` when no pin applies (selection proceeds normally), or
    /// `Some(Err(..))` when `target_node` names a broker this one is not — so
    /// a misdirected pin is rejected, never silently rerouted.
    ///
    /// A node is its key-derived fingerprint and nothing else. This compared
    /// the pin against `node_name_or_default()` — a hostname label such as
    /// `zc-worker-x399-2` — which a `zc://node-<fp>` pin can never equal, so
    /// EVERY pin, including a broker's pin to itself, returned `NO_WORKERS`.
    /// On the P2P path that is not a rejection: `/execute` reads it as "no
    /// local worker" and offers the job to the whole mesh, so the pin ran the
    /// work anywhere BUT the named node. Measured 2026-09-19 against a
    /// 0.0.32 broker: pinned to its own node id, the job ran on `zc-broker-2`.
    fn pin_local(
        &self,
        _registry: &WorkerRegistry,
        requirements: &ResourceRequirements,
    ) -> Option<Result<RoutingDecision, RoutingError>> {
        let tn = requirements.target_node.as_deref()?;
        match &self.node_fp {
            // Pinned to this broker: fall through to normal worker selection.
            Some(ours) if super::node_identity::fp_matches_node_arg(ours, tn) => None,
            // Named someone else, or we cannot prove who we are.
            _ => Some(Err(RoutingError::no_workers())),
        }
    }

    /// Pick a worker for `sel`, with `adaptive` doing the choosing when it is
    /// supplied.
    ///
    /// The one place this broker decides which of its workers runs a job.
    /// Everything that used to differ between the four hand-written selectors
    /// is a field of [`Selection`]; the order of business is the same for all
    /// of them:
    ///
    /// 1. honour a broker pin,
    /// 2. narrow to eligible workers,
    /// 3. choose — the adaptive policy, or the requested strategy with its
    ///    queue term, spreading what the strategy cannot separate,
    /// 4. check the caller can pay for the one chosen, when they are paying,
    /// 5. take its quota slot, falling through the rest if it has just filled.
    ///
    /// The caller must `cancel_quota_reservation` if the request then fails.
    ///
    /// A client-supplied `target_worker` is deliberately honoured nowhere:
    /// worker selection is this broker's private authority, never a
    /// client-routable target (see
    /// docs/superpowers/specs/2026-07-11-zc-key-derived-identity-amendment.md
    /// "Routing addendum").
    pub fn select(
        &self,
        registry: &WorkerRegistry,
        sel: Selection<'_>,
        mut adaptive: Option<Adaptive<'_>>,
    ) -> Result<RoutingDecision, RoutingError> {
        let req = sel.requirements;
        if let Some(pinned) = self.pin_local(registry, req) {
            return pinned;
        }

        let mut candidates = registry.healthy();
        if let Scope::Local { own_ip } = sel.scope {
            candidates.retain(|w| is_own_worker(w, own_ip));
        }
        if let Scope::Mesh { own_ip } = sel.scope {
            candidates.retain(|w| !is_own_worker(w, own_ip));
        }
        if candidates.is_empty() {
            return Err(RoutingError::no_workers());
        }

        if sel.check_labels {
            if let Some(wt) = req.worker_type.as_deref() {
                candidates.retain(|w| w.worker_type == wt);
                if candidates.is_empty() {
                    return Err(RoutingError::worker_type_unavailable(wt));
                }
            }
        }

        // Required tags are a hard capability (zc#403), like the interpreter
        // below: applied under every policy, including the local-only
        // selection that skips label checks, so a tagged job never runs on
        // an untagged worker here and instead falls through to peers.
        if !req.tags.is_empty() {
            let before = candidates.clone();
            candidates.retain(|w| req.tags.iter().all(|t| w.tags.contains(t)));
            if candidates.is_empty() {
                return Err(
                    tags_unsatisfied(&before, &req.tags).unwrap_or_else(RoutingError::no_workers)
                );
            }
        }

        // An interpreter mismatch is not capacity: it can never run, so it is
        // filtered whatever the selection policy checks.
        if req.python.is_some() {
            candidates.retain(|w| runs_payload(w, req.python.as_deref()));
            if candidates.is_empty() {
                return Err(RoutingError::no_workers());
            }
        }

        if sel.max_price_per_hour.is_finite() {
            candidates.retain(|w| w.pricing.price_per_hour <= sel.max_price_per_hour);
            if candidates.is_empty() {
                return Err(RoutingError::no_workers());
            }
        }

        if sel.check_capacity {
            candidates.retain(|w| w.can_handle(req.cpus, req.memory_bytes, req.gpus));
            if candidates.is_empty() {
                return Err(RoutingError::no_capacity(req));
            }
            // zc#345: a GPU-heavy job (e.g. an atelier LoRA finetune) can fit
            // a worker's free cpu/mem/gpu COUNT while still not fitting on
            // its card. VRAM is therefore its own filter, not folded into
            // `can_handle`, which knows nothing about VRAM at all.
            if req.min_vram_gb.is_some() {
                candidates.retain(|w| meets_vram(w, req.min_vram_gb));
                if candidates.is_empty() {
                    return Err(RoutingError::no_capacity(req));
                }
            }
            // A worker advertising a ceiling below the requested timeout would
            // abort the job part-way through it.
            if req.timeout_secs > 0.0 {
                candidates.retain(|w| {
                    w.max_timeout_secs <= 0.0 || w.max_timeout_secs >= req.timeout_secs
                });
                if candidates.is_empty() {
                    return Err(RoutingError::timeout_incompatible(req.timeout_secs));
                }
            }
        }

        let alternatives_count = candidates.len() - 1;
        let mut first_choice_was_full = false;
        loop {
            if candidates.is_empty() {
                return Err(RoutingError::quota_exceeded());
            }
            let (idx, mut reason) = match adaptive.as_mut() {
                Some(a) => self.choose_adaptive(&candidates, a)?,
                None => self.choose_by_strategy(&candidates, req),
            };
            if first_choice_was_full {
                reason.push_str(" (first choice was full)");
            }

            // Charge for the worker actually chosen, not for the fleet.
            let estimated_cost = candidates[idx]
                .pricing
                .estimate_cost(req.estimated_duration_secs);
            if let Some(balance) = sel.billed_to {
                if balance < estimated_cost {
                    return Err(RoutingError::insufficient_funds(estimated_cost, balance));
                }
            }

            if registry.try_reserve_quota(&candidates[idx].id) {
                return Ok(RoutingDecision {
                    // Nothing is charged on the unbilled paths, however the
                    // workers were priced or ordered.
                    estimated_cost: match sel.billed_to {
                        Some(_) => estimated_cost,
                        None => 0.0,
                    },
                    worker: candidates.swap_remove(idx),
                    reason,
                    alternatives_count,
                });
            }
            // Lost the race — that worker just hit its quota. Try the rest.
            candidates.swap_remove(idx);
            first_choice_was_full = true;
        }
    }

    /// Dry-run `select_worker`'s filtering and strategy ranking without
    /// reserving quota, advancing the round-robin cursor, or touching any
    /// worker's in-flight count -- `POST /route` (contract zc#345 §4)
    /// promises this executes, reserves, bills and mutates NOTHING.
    ///
    /// Mirrors `select_worker`'s policy: `Scope::Any`, capacity and label
    /// checks on, no price cap -- the same requirements body `/execute`
    /// uses. What differs from `select()` is that every healthy candidate is
    /// kept and annotated with why it would be excluded (via
    /// `ineligibility_reason`, a second implementation of the same
    /// predicates `select()`'s retain chain runs -- see that function's
    /// docs for how the two are kept honest with each other), rather than
    /// the chain of fast-fail retains `select()` uses to return one specific
    /// error code; and ranking reuses `strategy_key` -- the exact function
    /// `choose_by_strategy`'s own tie-detection calls -- rather than a
    /// second copy of what each strategy promises.
    ///
    /// `chosen` is the policy's first choice among ELIGIBLE candidates, not
    /// a guarantee of what `/execute` will actually dispatch to: the live
    /// `select()` loop retries past a first choice that has just hit its
    /// quota (`try_reserve_quota` failing -> `first_choice_was_full`) and
    /// tries the rest before giving up with `QUOTA_EXCEEDED`. A dry run has
    /// no request to reserve, so it cannot observe or reproduce that --
    /// `chosen` can therefore name a worker `/execute` ends up skipping over
    /// at the moment it actually runs.
    pub fn route_dry_run(
        &self,
        registry: &WorkerRegistry,
        requirements: &ResourceRequirements,
    ) -> Result<RouteDryRun, RoutingError> {
        // A node pin is honoured identically to a real selection: previewing
        // past a pin a live call would reject would preview a job that could
        // never actually be placed.
        if let Some(Err(e)) = self.pin_local(registry, requirements) {
            return Err(e);
        }

        let healthy = registry.healthy();
        if healthy.is_empty() {
            return Err(RoutingError::no_workers());
        }

        let mut eligible: Vec<Worker> = Vec::new();
        let mut excluded: Vec<ExcludedWorker> = Vec::new();
        for w in healthy {
            match ineligibility_reason(&w, requirements) {
                None => eligible.push(w),
                Some(reason) => excluded.push(ExcludedWorker {
                    worker_id: w.id.clone(),
                    reason,
                }),
            }
        }

        // Rank with the SAME key the real selection uses to settle ties
        // (`strategy_key`) wherever the strategy defines one. The three
        // "spread by construction" strategies have no quality order to show
        // without actually drawing from a cursor or the clock -- and doing
        // that here would either mutate the live round-robin counter or be
        // unrepeatable noise -- so they are ranked by a stable, strategy-
        // appropriate stand-in instead: `weighted_capacity` by the very
        // weight its draw samples from (descending), `round_robin`/`random`
        // by worker id (there is no "better" worker to put first for either).
        eligible.sort_by(|a, b| match requirements.strategy {
            RoutingStrategy::WeightedCapacity => capacity_weight(b)
                .partial_cmp(&capacity_weight(a))
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.id.cmp(&b.id)),
            RoutingStrategy::RoundRobin | RoutingStrategy::Random => a.id.cmp(&b.id),
            _ => {
                let ka = self.strategy_key(a, requirements).unwrap_or(i64::MAX);
                let kb = self.strategy_key(b, requirements).unwrap_or(i64::MAX);
                ka.cmp(&kb).then_with(|| a.id.cmp(&b.id))
            }
        });

        let candidates: Vec<RouteCandidate> = eligible
            .iter()
            .map(|w| RouteCandidate {
                estimated_cost: w
                    .pricing
                    .estimate_cost(requirements.estimated_duration_secs),
                worker: w.clone(),
            })
            .collect();
        let chosen = candidates.first().cloned();

        Ok(RouteDryRun {
            strategy: requirements.strategy,
            chosen,
            candidates,
            excluded,
        })
    }

    /// Choose by `requirements.strategy`, spreading what it cannot separate.
    /// Returns an index into `workers`, which is never empty here.
    ///
    /// The spread matters wherever a strategy runs out of things to compare:
    /// every worker is free in local mode, and a fleet often charges one
    /// price. Left alone, a cost-based strategy would then hand everything to
    /// whichever worker sorts first.
    fn choose_by_strategy(
        &self,
        workers: &[Worker],
        requirements: &ResourceRequirements,
    ) -> (usize, String) {
        let (idx, reason) = self.select_by_strategy(workers, requirements);
        let n = workers.len();
        let Some(winning_key) = self.strategy_key(&workers[idx], requirements) else {
            return (idx, reason); // already spread by construction
        };
        let tied = workers
            .iter()
            .all(|w| self.strategy_key(w, requirements) == Some(winning_key));
        if tied && n > 1 {
            let slot = self.round_robin_counter.fetch_add(1, Ordering::Relaxed) % n;
            return (slot, format!("{reason} (tied; spread to slot {slot})"));
        }
        (idx, reason)
    }

    /// Choose with the measured policy: draw `weights.candidates_per_choice`
    /// candidates weighted by what each has been observed doing, judge each
    /// on a sample from its own posterior, take the better. Returns an index
    /// into `workers`.
    ///
    /// Constant work per task whatever the size of the fleet, which is what a
    /// mesh of millions needs.
    fn choose_adaptive(
        &self,
        workers: &[Worker],
        adaptive: &mut Adaptive<'_>,
    ) -> Result<(usize, String), RoutingError> {
        use crate::broker::policy::{self, Candidate};
        use crate::broker::sampler::AliasTable;

        let candidates: Vec<Candidate> = workers
            .iter()
            .map(|w| Candidate {
                stats: w.stats,
                in_flight: w.active_requests,
                price_per_hour: w.pricing.price_per_hour,
                // A worker this broker registered itself is on this node;
                // one that arrived from a peer roster carries that peer as
                // its `source_node`. Only decides which prior an unmeasured
                // worker starts from.
                local: w.source_node.is_none(),
            })
            .collect();
        // A worker with less than one observation's worth of evidence starts
        // from what its siblings measure, not from a flat guess (#438).
        let candidates = policy::with_fleet_prior(&candidates, adaptive.weights);
        let table_weights: Vec<f64> = candidates
            .iter()
            .map(|c| policy::table_weight(c, adaptive.weights))
            .collect();
        let Some(table) = AliasTable::build(&table_weights) else {
            return Err(RoutingError::no_workers());
        };
        let Some(idx) = policy::choose(
            &candidates,
            &table,
            adaptive.rng,
            adaptive.weights.candidates_per_choice,
            adaptive.weights,
        ) else {
            return Err(RoutingError::no_workers());
        };
        let est = candidates[idx]
            .stats
            .expected_service_ms()
            .unwrap_or(adaptive.weights.unmeasured_ms);
        Ok((idx, format!("Adaptive: expected {est:.0}ms")))
    }

    /// Select a worker without balance or rate checks: local mode, or any
    /// broker with billing off.
    ///
    /// Skipping the *balance* checks is the only thing that should differ from
    /// the billed path; how a worker is chosen is not. This path used to
    /// round-robin and ignore `requirements.strategy` entirely, so every `-s`
    /// was silently discarded on such a broker and work spread evenly over
    /// workers answering in 254 ms and 1000 ms alike (#252).
    pub fn select_worker_no_checks(
        &self,
        registry: &WorkerRegistry,
        requirements: &ResourceRequirements,
        adaptive: Option<Adaptive<'_>>,
    ) -> Result<RoutingDecision, RoutingError> {
        self.select_worker_no_checks_in(registry, Scope::Any, requirements, adaptive)
    }

    /// [`Self::select_worker_no_checks`] narrowed to `scope`.
    pub fn select_worker_no_checks_in(
        &self,
        registry: &WorkerRegistry,
        scope: Scope<'_>,
        requirements: &ResourceRequirements,
        adaptive: Option<Adaptive<'_>>,
    ) -> Result<RoutingDecision, RoutingError> {
        self.select(
            registry,
            Selection {
                requirements,
                scope,
                check_capacity: false,
                check_labels: false,
                max_price_per_hour: f64::INFINITY,
                billed_to: None,
            },
            adaptive,
        )
    }

    /// The value a strategy orders workers by, used to tell "this one is
    /// better" from "there is nothing to choose between them".
    ///
    /// `None` for the strategies that already spread by construction. Asking
    /// whether round-robin's pick is tied is meaningless, and the old sentinel
    /// answered yes — every worker keyed 0, so the spread ran on top of the
    /// choice, took a second turn of the same counter, and handed consecutive
    /// requests to the same worker.
    fn strategy_key(&self, w: &Worker, requirements: &ResourceRequirements) -> Option<i64> {
        let v = match requirements.strategy {
            // Same function the selection uses. These were two copies of
            // each formula and they are one now: a tie-detector that disagrees
            // with the chooser spreads picks the chooser did not consider tied.
            RoutingStrategy::BestPrice => {
                // Mirrors the chooser's ordering without the id tiebreak:
                // workers with equal price ARE tied, and the spread is what
                // should settle them.
                let (remote, estimate, rate, _) =
                    price_key(w, requirements.estimated_duration_secs);
                return Some(
                    i64::from(remote)
                        .wrapping_mul(1 << 62)
                        .wrapping_add(estimate.wrapping_mul(1 << 20))
                        .wrapping_add(rate),
                );
            }
            RoutingStrategy::BestLatency => match w.total_requests > 0 {
                true => expected_completion_ms(w),
                false => f64::INFINITY,
            },
            RoutingStrategy::BestAvailability => -availability_score(w),
            // Spread-by-construction: there is nothing to be tied about.
            RoutingStrategy::RoundRobin
            | RoutingStrategy::Random
            | RoutingStrategy::WeightedCapacity => return None,
        };
        // Bucketed so floating-point noise doesn't read as a real difference.
        // Signed: `best_availability` negates its score before ranking, and an
        // unsigned cast saturated every negative to 0 — so a 32-core worker and
        // a 1-core one always compared equal and the spread took over, turning
        // the strategy into round-robin wherever it ran.
        Some((v * 1e6) as i64)
    }

    /// Select a worker this broker owns and executes itself.
    ///
    /// The publish-lock model: try local first, offer to peers if there is
    /// nothing here. It used to round-robin and never looked at
    /// `requirements` at all, so a broker running billing and peering ignored
    /// `-s` on exactly the traffic it executes itself.
    pub fn select_local_worker(
        &self,
        registry: &WorkerRegistry,
        own_ip: Option<&str>,
        requirements: &ResourceRequirements,
        adaptive: Option<Adaptive<'_>>,
    ) -> Result<RoutingDecision, RoutingError> {
        self.select(
            registry,
            Selection {
                requirements,
                scope: Scope::Local { own_ip },
                check_capacity: false,
                check_labels: false,
                max_price_per_hour: f64::INFINITY,
                billed_to: None,
            },
            adaptive,
        )
    }

    /// Select the best worker for a caller who will be charged for it.
    ///
    /// `balance` is the caller's pre-fetched balance for `user_id`.
    /// The `balances` parameter is only used for rate-limit enforcement.
    pub fn select_worker(
        &self,
        registry: &WorkerRegistry,
        balances: &BalanceManager,
        user_id: &str,
        balance: f64,
        requirements: &ResourceRequirements,
        adaptive: Option<Adaptive<'_>>,
    ) -> Result<RoutingDecision, RoutingError> {
        self.select_worker_in(
            registry,
            Scope::Any,
            balances,
            user_id,
            balance,
            requirements,
            adaptive,
        )
    }

    /// [`Self::select_worker`] narrowed to `scope`.
    #[allow(clippy::too_many_arguments)]
    pub fn select_worker_in(
        &self,
        registry: &WorkerRegistry,
        scope: Scope<'_>,
        balances: &BalanceManager,
        user_id: &str,
        balance: f64,
        requirements: &ResourceRequirements,
        adaptive: Option<Adaptive<'_>>,
    ) -> Result<RoutingDecision, RoutingError> {
        if !balances.check_rate_limit(user_id) {
            return Err(RoutingError::rate_limited());
        }
        self.select(
            registry,
            Selection {
                requirements,
                scope,
                check_capacity: true,
                check_labels: true,
                max_price_per_hour: f64::INFINITY,
                billed_to: Some(balance),
            },
            adaptive,
        )
    }

    /// Rank by `requirements.strategy` and return the winner's index into
    /// `workers`, which is never empty here.
    fn select_by_strategy(
        &self,
        workers: &[Worker],
        requirements: &ResourceRequirements,
    ) -> (usize, String) {
        match requirements.strategy {
            RoutingStrategy::BestPrice => {
                // Lowest estimated cost. min_by is O(n) and clones only the
                // winner (was: clone-all + O(n log n) sort). min_by returns the
                // first of equal-minimums, matching the prior stable-sort-first.
                let (idx, key) = workers
                    .iter()
                    .enumerate()
                    .map(|(i, w)| (i, price_key(w, requirements.estimated_duration_secs)))
                    .min_by(|a, b| a.1.cmp(&b.1))
                    .expect("select_by_strategy is only called with a non-empty worker list");
                let (remote, estimate, _, _) = key;
                (
                    idx,
                    match remote {
                        0 => "Best price: this node".to_string(),
                        _ => format!("Best price: ¥{:.6}", estimate as f64 / 1e9),
                    },
                )
            }

            RoutingStrategy::BestLatency => {
                // What the caller waits for is queue + service, not service.
                // Ranking on service time alone piles every task onto the same
                // "fastest" worker until it is deep in its own queue: measured
                // on a live mesh, that moved the median from 1.58 s to 1.12 s
                // and p90 from 2.07 s to 6.14 s.
                //
                // A worker that has never completed a request has
                // `avg_latency_ms` 0.0, the smallest number there is — taken
                // literally that sends everything to the one worker nobody has
                // heard back from, and starves one measured at 5 ms. Unmeasured
                // is unknown, so it sorts after everything measured; when
                // nothing is measured they are equal and the first wins.
                let (idx, latency) = workers
                    .iter()
                    .enumerate()
                    .map(|(i, w)| {
                        let measured = w.total_requests > 0;
                        (i, measured, expected_completion_ms(w))
                    })
                    .min_by(|a, b| {
                        b.1.cmp(&a.1).then_with(|| {
                            a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal)
                        })
                    })
                    .map(|(i, measured, latency)| (i, measured.then_some(latency)))
                    .expect("select_by_strategy is only called with a non-empty worker list");
                (
                    idx,
                    match latency {
                        Some(ms) => format!("Best latency: {:.1}ms", ms),
                        None => "Best latency: no measurement yet".to_string(),
                    },
                )
            }

            RoutingStrategy::BestAvailability => {
                // Highest availability score. Reversed comparator so min_by
                // returns the FIRST element of maximum score — matching the
                // prior descending-sort-then-first (max_by would return the LAST
                // of equals and change tie-breaking).
                let (idx, score) = workers
                    .iter()
                    .enumerate()
                    .map(|(i, w)| (i, availability_score(w)))
                    .min_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal))
                    .expect("select_by_strategy is only called with a non-empty worker list");
                (
                    idx,
                    format!("Best availability: {:.0}% idle", score * 100.0),
                )
            }

            RoutingStrategy::RoundRobin => {
                // Indexing the counter into `workers` directly is not a cycle.
                // That slice is the freshly collected `healthy()` Vec, whose
                // order comes from a DashMap — re-permuted on every call, and
                // re-filtered per request by capacity, timeout and tags so its
                // length moves too. A monotonic counter into a list that
                // permutes between calls is sampling with replacement, which
                // is why `round_robin` measured the same as `random` and the
                // "even distribution" it advertises never existed (#335).
                //
                // Ordering by id first gives the counter something stable to
                // walk, so consecutive requests actually visit different
                // workers.
                let mut order: Vec<usize> = (0..workers.len()).collect();
                order.sort_by(|&a, &b| workers[a].id.cmp(&workers[b].id));
                let slot = self.round_robin_counter.fetch_add(1, Ordering::Relaxed) % order.len();
                let idx = order[slot];
                (idx, format!("Round-robin: slot {slot} of {}", order.len()))
            }

            RoutingStrategy::Random => {
                // Random selection using simple PRNG
                use std::time::{SystemTime, UNIX_EPOCH};
                let seed = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .subsec_nanos() as usize;
                let idx = seed % workers.len();
                (idx, format!("Random: index {}", idx))
            }

            RoutingStrategy::WeightedCapacity => {
                // Weighted random based on available capacity
                use std::time::{SystemTime, UNIX_EPOCH};

                let weights: Vec<f64> = workers.iter().map(capacity_weight).collect();

                let total_weight: f64 = weights.iter().sum();

                // Simple random selection
                let seed = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .subsec_nanos() as f64;
                let target = (seed / 1_000_000_000.0) * total_weight;

                let mut cumulative = 0.0;
                for (i, weight) in weights.iter().enumerate() {
                    cumulative += weight;
                    if cumulative >= target {
                        return (i, format!("Weighted capacity: weight {:.2}", weight));
                    }
                }

                // Fallback to first worker
                (0, "Weighted capacity: fallback".to_string())
            }
        }
    }

    /// Get cost estimate without selecting a worker
    pub fn estimate_cost(
        &self,
        registry: &WorkerRegistry,
        requirements: &ResourceRequirements,
    ) -> Option<(f64, f64)> {
        let workers = registry.healthy();
        if workers.is_empty() {
            return None;
        }

        // Filter capable workers
        let capable: Vec<&Worker> = workers
            .iter()
            .filter(|w| {
                w.can_handle(
                    requirements.cpus,
                    requirements.memory_bytes,
                    requirements.gpus,
                ) && meets_vram(w, requirements.min_vram_gb)
                    && runs_payload(w, requirements.python.as_deref())
            })
            .collect();

        if capable.is_empty() {
            return None;
        }

        // Calculate min and max costs
        let costs: Vec<f64> = capable
            .iter()
            .map(|w| {
                w.pricing
                    .estimate_cost(requirements.estimated_duration_secs)
            })
            .collect();

        let min_cost = costs.iter().cloned().fold(f64::INFINITY, f64::min);
        let max_cost = costs.iter().cloned().fold(0.0, f64::max);

        Some((min_cost, max_cost))
    }

    /// List workers matching requirements (for preview)
    pub fn list_matching(
        &self,
        registry: &WorkerRegistry,
        requirements: &ResourceRequirements,
    ) -> Vec<(Worker, f64)> {
        let workers = registry.healthy();

        let mut matching: Vec<(Worker, f64)> = workers
            .iter()
            .filter(|w| {
                // Filter by type if specified
                if let Some(ref wt) = requirements.worker_type {
                    if &w.worker_type != wt {
                        return false;
                    }
                }
                // Filter by capacity
                w.can_handle(
                    requirements.cpus,
                    requirements.memory_bytes,
                    requirements.gpus,
                ) && meets_vram(w, requirements.min_vram_gb)
                    && runs_payload(w, requirements.python.as_deref())
            })
            .map(|w| {
                let cost = w
                    .pricing
                    .estimate_cost(requirements.estimated_duration_secs);
                (w.clone(), cost)
            })
            .collect();

        // Sort by cost (lowest first)
        matching.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
        matching
    }
}

impl Default for Router {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::broker::balance::BalanceManager;
    use crate::broker::worker::{
        HardwareInfo, WorkerPricing, WorkerRegistration, WorkerRegistry, WorkerResources,
    };

    // --- Helpers ---

    pub(super) fn make_reg(
        name: &str,
        port: usize,
        cpus: f64,
        memory_gib: u64,
        gpus: u32,
        price_per_hour: f64,
    ) -> WorkerRegistration {
        WorkerRegistration {
            name: name.to_string(),
            uri: format!("http://127.0.0.1:{}", 3960 + port),
            worker_type: "zakuro".to_string(),
            resources: WorkerResources {
                cpus_total: cpus,
                cpus_available: cpus,
                memory_total: memory_gib * 1024 * 1024 * 1024,
                memory_available: memory_gib * 1024 * 1024 * 1024,
                gpus_total: gpus,
                gpus_available: gpus,
            },
            pricing: WorkerPricing {
                price_per_hour,
                min_charge: 0.001,
            },
            tags: vec![],
            max_timeout_secs: 0.0,
            hardware: HardwareInfo::default(),
            wireguard_ip: None,
            is_docker: None,
            source_node: None,
            explicit_local: false,
            provider_type: Default::default(),
            served_models: vec![],
            price_per_mtok: 0.0,
        }
    }

    /// A worker that arrived by peer sync is never ours, however its URI is
    /// spelt. `is_own_worker`'s own docstring promises exactly this — "a peer's
    /// worker can never be executed as local — and billed at 0.0 — however its
    /// URI is spelt" — but only the `explicit_local` arm was gated on
    /// `source_node`. The three address arms were not, so a peer worker reached
    /// on loopback (a tunnel or a rewritten discovery URI) or on an address that
    /// merely CONTAINS ours passes as our own hardware. `Scope::Local` then
    /// offers it to `/execute/batch`, which hardcodes `self_executed = true` on
    /// the strength of this filter and bills the whole batch at 0.0 — so the
    /// node that ran the work is never paid (#297/#329).
    #[test]
    fn a_peer_synced_worker_is_not_ours_however_its_uri_is_spelt() {
        fn peer_worker(uri: &str) -> Worker {
            let mut w = Worker::new(
                "id".into(),
                "peer-worker".into(),
                uri.into(),
                "zakuro".into(),
            );
            // The registry's authoritative ownership marker: it came from a peer.
            w.source_node = Some("node-6188100f5daf463e".into());
            w
        }

        // Reached over a loopback tunnel.
        assert!(
            !is_own_worker(&peer_worker("http://127.0.0.1:3960"), Some("10.13.13.35")),
            "a peer worker on loopback is still a peer's"
        );
        assert!(
            !is_own_worker(&peer_worker("http://localhost:3960"), Some("10.13.13.35")),
            "a peer worker on localhost is still a peer's"
        );
        // An address that merely contains ours as a substring: own_ip
        // "10.13.13.3" is inside the peer's "10.13.13.35".
        assert!(
            !is_own_worker(&peer_worker("http://10.13.13.35:3960"), Some("10.13.13.3")),
            "a substring address match does not make a peer's worker ours"
        );
        // And the arm that was already correct stays correct.
        let mut explicit = peer_worker("http://10.13.13.20:3960");
        explicit.explicit_local = true;
        assert!(!is_own_worker(&explicit, None));

        // Our OWN workers must still be ours, or every local job starts billing.
        let mut mine = Worker::new(
            "id".into(),
            "w0".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        mine.source_node = None;
        assert!(is_own_worker(&mine, None), "our loopback worker is ours");
        let mut mine_ip = Worker::new(
            "id".into(),
            "w1".into(),
            "http://10.13.13.35:3960".into(),
            "zakuro".into(),
        );
        mine_ip.source_node = None;
        assert!(
            is_own_worker(&mine_ip, Some("10.13.13.35")),
            "our worker on our own address is ours"
        );
    }

    fn balances_for(user: &str, balance: f64) -> BalanceManager {
        let mgr = BalanceManager::new();
        mgr.get_or_create(user, balance);
        mgr
    }

    pub(super) fn req_default() -> ResourceRequirements {
        ResourceRequirements::default()
    }

    // --- Error cases ---

    /// Regression (staging 2026-08-14): a broker sharing a WireGuard sidecar's
    /// network namespace reaches its OWN worker through the container gateway
    /// (172.17.0.1:3960), and the worker registers under a `zc://` handle that
    /// contains no IP at all. Locality was decided by substring-matching the
    /// URI against 127.0.0.1/localhost/own_ip, so that worker was registered
    /// but never SELECTED -- /workers listed it while every job returned
    /// `No worker available (local or peer)` (HTTP 503).
    ///
    /// `source_node` is the registry's authoritative ownership marker: None
    /// means this broker registered it itself, Some(node) means it arrived via
    /// a peer sync. Locality follows ownership, not the spelling of a URI.
    #[test]
    fn local_selection_follows_ownership_not_uri_spelling() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut reg = make_reg("worker-sidecar", 0, 4.0, 4, 0, 0.001);
        reg.uri = "zc://worker-7fed13b4a701206f-3960".to_string();
        reg.source_node = None; // this broker's own worker
        reg.explicit_local = true; // named in ZAKURO_WORKERS
        registry.register(reg);

        let decision = router
            .select_local_worker(&registry, None, &req_default(), None)
            .expect("an owned worker must be selectable as local");
        assert_eq!(decision.worker.name, "worker-sidecar");
        assert_eq!(decision.estimated_cost, 0.0);
    }

    #[test]
    fn peer_synced_workers_are_never_selected_as_local() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut reg = make_reg("worker-remote", 1, 4.0, 4, 0, 0.001);
        // Even spelled as loopback, a peer-synced worker is not ours.
        reg.uri = "zc://worker-remote-3960".to_string();
        reg.explicit_local = true; // even declared, a peer's worker is not ours
        reg.source_node = Some("node-i9".to_string());
        registry.register(reg);

        assert!(router
            .select_local_worker(&registry, None, &req_default(), None)
            .is_err());
    }

    #[test]
    fn test_no_healthy_workers_returns_no_workers() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let balances = balances_for("alice", 1000.0);

        let err = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req_default(), None)
            .unwrap_err();
        assert_eq!(err.code, "NO_WORKERS");
    }

    // Was `test_pin_target_worker_selects_named_and_rejects_unknown`: client
    // worker-pinning is removed by design (brokers address workers, never
    // clients — see the 2026-07-11 key-derived-identity amendment's Routing
    // addendum). This now asserts the opposite: a client-supplied
    // `target_worker` is a no-op for routing — selection proceeds by the
    // broker's normal policy and even a nonexistent worker name never causes
    // a rejection (there is nothing to resolve against).
    #[test]
    fn test_client_target_worker_is_noop_for_routing() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("worker-a", 0, 4.0, 4, 0, 0.001));

        // A client naming a specific (even nonexistent) worker does not
        // steer or block routing — the sole healthy local worker is picked
        // by normal policy regardless of the pin.
        let req = ResourceRequirements {
            target_worker: Some("zc://worker-ghost".to_string()),
            ..req_default()
        };
        let decision = router
            .select_worker_no_checks(&registry, &req, None)
            .unwrap();
        assert_eq!(decision.worker.name, "worker-a");
    }

    #[test]
    fn test_pin_target_node_other_node_rejected() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("worker-a", 0, 4.0, 4, 0, 0.001));

        // A node pin for a different node has no local candidate here.
        let req = ResourceRequirements {
            target_node: Some("zc://node-somewhere-else".to_string()),
            ..req_default()
        };
        let err = router
            .select_worker_no_checks(&registry, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "NO_WORKERS");
    }

    /// The bug this file carried until 2026-09-19: a pin naming the broker's
    /// OWN node was compared against its hostname label, never matched, and
    /// came back `NO_WORKERS` — which `/execute` reads as "nothing local" and
    /// answers by offering the job to every peer. A pin that guarantees the
    /// work runs somewhere else is worse than no pin at all.
    #[test]
    fn test_pin_target_node_self_runs_here() {
        let router = Router::new().with_node("fd29ea8fe9ffa2e0");
        let registry = WorkerRegistry::new();
        registry.register(make_reg("worker-a", 0, 4.0, 4, 0, 0.001));

        for spelling in [
            "zc://node-fd29ea8fe9ffa2e0",
            "node-fd29ea8fe9ffa2e0",
            "fd29ea8fe9ffa2e0",
        ] {
            let req = ResourceRequirements {
                target_node: Some(spelling.to_string()),
                ..req_default()
            };
            let decision = router
                .select_worker_no_checks(&registry, &req, None)
                .unwrap_or_else(|e| panic!("pin {spelling} rejected: {}", e.code));
            assert_eq!(decision.worker.name, "worker-a", "pin {spelling}");
        }
    }

    /// Identity is the key-derived fingerprint. A hostname label is not a
    /// node handle and must not resolve to one, however suggestive it looks —
    /// two hosts can share a label, and a label is not proof of anything.
    #[test]
    fn test_pin_target_node_hostname_label_never_matches() {
        let router = Router::new().with_node("fd29ea8fe9ffa2e0");
        let registry = WorkerRegistry::new();
        registry.register(make_reg("worker-a", 0, 4.0, 4, 0, 0.001));

        let req = ResourceRequirements {
            target_node: Some("zc-worker-x399-2".to_string()),
            ..req_default()
        };
        let err = router
            .select_worker_no_checks(&registry, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "NO_WORKERS");
    }

    /// A router with no identity cannot prove it is the named node, so it
    /// must refuse rather than assume the pin meant it.
    #[test]
    fn test_pin_target_node_without_identity_is_rejected() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("worker-a", 0, 4.0, 4, 0, 0.001));

        let req = ResourceRequirements {
            target_node: Some("zc://node-fd29ea8fe9ffa2e0".to_string()),
            ..req_default()
        };
        let err = router
            .select_worker_no_checks(&registry, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "NO_WORKERS");
    }

    /// No pin at all is not a pin to nowhere: selection proceeds normally.
    #[test]
    fn test_no_pin_selects_normally_with_identity_set() {
        let router = Router::new().with_node("fd29ea8fe9ffa2e0");
        let registry = WorkerRegistry::new();
        registry.register(make_reg("worker-a", 0, 4.0, 4, 0, 0.001));
        let decision = router
            .select_worker_no_checks(&registry, &req_default(), None)
            .unwrap();
        assert_eq!(decision.worker.name, "worker-a");
    }

    #[test]
    fn test_no_capacity_returns_no_capacity() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("small", 0, 1.0, 1, 0, 0.001));
        let balances = balances_for("alice", 1000.0);

        let req = ResourceRequirements {
            cpus: 16.0,
            ..req_default()
        };
        let err = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "NO_CAPACITY");
    }

    #[test]
    fn test_insufficient_funds_returns_error() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        // Expensive worker: ¥1.0/CPU/s
        registry.register(make_reg("expensive", 0, 4.0, 4, 0, 1.0));
        let balances = balances_for("alice", 0.001); // near-zero balance

        let req = ResourceRequirements {
            cpus: 1.0,
            estimated_duration_secs: 3600.0, // 1 hour → very expensive
            ..req_default()
        };
        let err = router
            .select_worker(&registry, &balances, "alice", 0.001, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "INSUFFICIENT_FUNDS");
    }

    #[test]
    fn test_rate_limited_returns_error() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("w", 0, 4.0, 4, 0, 0.001));

        let mgr = BalanceManager::new();
        mgr.get_or_create("alice", 1000.0);
        mgr.set_rate_limits("alice", Some(0), None, None); // 0/sec → immediate block

        let err = router
            .select_worker(&registry, &mgr, "alice", 1000.0, &req_default(), None)
            .unwrap_err();
        assert_eq!(err.code, "RATE_LIMITED");
    }

    #[test]
    fn test_worker_type_mismatch_returns_error() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut reg = make_reg("ray-w", 0, 4.0, 4, 0, 0.001);
        reg.worker_type = "ray".to_string();
        registry.register(reg);
        let balances = balances_for("alice", 1000.0);

        let req = ResourceRequirements {
            worker_type: Some("spark".to_string()),
            ..req_default()
        };
        let err = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "WORKER_TYPE_UNAVAILABLE");
    }

    #[test]
    fn test_timeout_incompatible_returns_error() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut reg = make_reg("limited", 0, 4.0, 4, 0, 0.001);
        reg.max_timeout_secs = 30.0; // only accepts ≤ 30s requests
        registry.register(reg);
        let balances = balances_for("alice", 1000.0);

        let req = ResourceRequirements {
            timeout_secs: 60.0,
            ..req_default()
        };
        let err = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "TIMEOUT_INCOMPATIBLE");
    }

    #[test]
    fn test_timeout_unlimited_worker_accepts_any_timeout() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut reg = make_reg("unlimited", 0, 4.0, 4, 0, 0.001);
        reg.max_timeout_secs = 0.0; // 0 = unlimited
        registry.register(reg);
        let balances = balances_for("alice", 1000.0);

        let req = ResourceRequirements {
            timeout_secs: 3600.0,
            ..req_default()
        };
        assert!(router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .is_ok());
    }

    // --- Tag filtering ---

    #[test]
    fn test_tag_filter_requires_all_tags() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut reg = make_reg("gpu-w", 0, 8.0, 32, 2, 0.001);
        reg.tags = vec!["gpu".to_string(), "a100".to_string()];
        registry.register(reg);
        let balances = balances_for("alice", 1000.0);

        // Matching both tags
        let req_match = ResourceRequirements {
            tags: vec!["gpu".to_string(), "a100".to_string()],
            ..req_default()
        };
        assert!(router
            .select_worker(&registry, &balances, "alice", 1000.0, &req_match, None)
            .is_ok());

        // Requesting a tag that doesn't exist on any worker
        let req_no_match = ResourceRequirements {
            tags: vec!["gpu".to_string(), "h100".to_string()],
            ..req_default()
        };
        assert!(router
            .select_worker(&registry, &balances, "alice", 1000.0, &req_no_match, None)
            .is_err());
    }

    #[test]
    fn missing_required_tag_is_a_clear_error_naming_it() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("linux-gpu", 0, 8.0, 32, 2, 0.001));
        let balances = balances_for("alice", 1000.0);
        let req = ResourceRequirements {
            tags: vec!["apple-silicon".to_string()],
            ..req_default()
        };
        let err = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap_err();
        assert_eq!(err.code, "NO_WORKERS_WITH_TAGS");
        assert!(err.message.contains("apple-silicon"), "{}", err.message);
        // No tags required: unchanged.
        assert!(router
            .select_worker(&registry, &balances, "alice", 1000.0, &req_default(), None)
            .is_ok());
    }

    #[test]
    fn tags_unsatisfied_names_only_tags_no_worker_has() {
        let mut w = Worker::new("1".into(), "w".into(), "http://x:1".into(), "zakuro".into());
        w.tags = vec!["gpu".into()];
        let want = vec!["gpu".to_string(), "apple-silicon".to_string()];
        let e = tags_unsatisfied(&[w.clone()], &want).unwrap();
        assert!(e.message.contains("no worker advertises: apple-silicon"));
        assert!(tags_unsatisfied(&[w], &["gpu".to_string()]).is_none());
        assert!(tags_unsatisfied(&[], &[]).is_none());
    }

    // --- Strategy tests ---

    #[test]
    fn test_best_price_selects_cheapest_worker() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("cheap", 0, 4.0, 4, 0, 0.001));
        registry.register(make_reg("pricey", 1, 4.0, 4, 0, 1.0));
        let balances = balances_for("alice", 10000.0);

        // Use 1-hour duration so that price_per_hour values are directly comparable
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestPrice,
            estimated_duration_secs: 3600.0,
            ..req_default()
        };
        let decision = router
            .select_worker(&registry, &balances, "alice", 10000.0, &req, None)
            .unwrap();
        assert_eq!(decision.worker.name, "cheap");
    }

    #[test]
    fn best_price_selects_cheapest_with_many_candidates() {
        // Regression guard for the min_by refactor: cheapest must win with the
        // minimum in the middle of the candidate list.
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("w-a", 0, 4.0, 4, 0, 5.0));
        registry.register(make_reg("w-b", 1, 4.0, 4, 0, 2.0)); // cheapest
        registry.register(make_reg("w-c", 2, 4.0, 4, 0, 9.0));
        let balances = balances_for("alice", 10000.0);
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestPrice,
            estimated_duration_secs: 3600.0,
            ..req_default()
        };
        let decision = router
            .select_worker(&registry, &balances, "alice", 10000.0, &req, None)
            .unwrap();
        assert_eq!(decision.worker.name, "w-b", "must pick the cheapest worker");
    }

    #[test]
    fn test_best_latency_selects_fastest_worker() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let w_fast = registry.register(make_reg("fast", 0, 4.0, 4, 0, 0.001));
        let w_slow = registry.register(make_reg("slow", 1, 4.0, 4, 0, 0.001));

        // Simulate latency via record_request
        // fast: EMA = 0.1 * 5 = 0.5ms; slow: EMA = 0.1 * 500 = 50ms
        registry.record_request(&w_fast.id, 5.0, true);
        registry.record_request(&w_slow.id, 500.0, true);

        let balances = balances_for("alice", 1000.0);
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestLatency,
            ..req_default()
        };
        let decision = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap();
        assert_eq!(decision.worker.name, "fast");
    }

    /// A worker that has never completed a request has `avg_latency_ms` 0.0,
    /// which is the smallest value there is. `best_latency` therefore used to
    /// pick the one worker it knew nothing about over one measured at 5 ms —
    /// on a real mesh that meant every request went to a peer that had never
    /// answered, while the local worker sat idle at 5.5 ms.
    #[test]
    fn best_latency_does_not_mistake_never_measured_for_instant() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let measured = registry.register(make_reg("measured", 0, 4.0, 4, 0, 0.001));
        registry.register(make_reg("never-answered", 1, 4.0, 4, 0, 0.001));
        registry.record_request(&measured.id, 50.0, true);

        let balances = balances_for("alice", 1000.0);
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestLatency,
            ..req_default()
        };
        let decision = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap();
        assert_eq!(
            decision.worker.name, "measured",
            "a measured 5 ms beats an unknown"
        );
    }

    /// With nothing measured anywhere there is no fastest worker to pick, and
    /// refusing to route would strand a fresh broker. Any healthy worker will
    /// do, and it must be a real one.
    #[test]
    fn best_latency_still_routes_when_nothing_has_been_measured() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("a", 0, 4.0, 4, 0, 0.001));
        registry.register(make_reg("b", 1, 4.0, 4, 0, 0.001));

        let balances = balances_for("alice", 1000.0);
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestLatency,
            ..req_default()
        };
        let decision = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap();
        assert!(
            ["a", "b"].contains(&decision.worker.name.as_str()),
            "picked {}",
            decision.worker.name
        );
    }

    /// `/execute` uses this selector whenever the broker is in local mode or
    /// billing is off, and it round-robinned regardless of what the caller
    /// asked for — so every `zc bench -s …` on such a broker was ignored, and
    /// work spread evenly over workers answering in 254 ms and 1000 ms alike.
    #[test]
    fn the_unchecked_path_honours_the_strategy_it_was_given() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let fast = registry.register(make_reg("fast", 0, 4.0, 4, 0, 0.001));
        let slow = registry.register(make_reg("slow", 1, 4.0, 4, 0, 0.001));
        registry.record_request(&fast.id, 5.0, true);
        registry.record_request(&slow.id, 900.0, true);

        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestLatency,
            ..req_default()
        };
        for _ in 0..8 {
            let d = router
                .select_worker_no_checks(&registry, &req, None)
                .unwrap();
            assert_eq!(d.worker.name, "fast", "reason was: {}", d.reason);
        }
    }

    /// In local mode every worker is free, so a cost-based strategy cannot
    /// separate them. It must not therefore send everything to whichever one
    /// sorts first: with nothing to choose between them, the load still has to
    /// spread.
    #[test]
    fn workers_a_strategy_cannot_separate_still_share_the_load() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        for i in 0..4 {
            registry.register(make_reg(&format!("w{i}"), i, 4.0, 4, 0, 0.0));
        }
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestPrice,
            ..req_default()
        };
        let mut seen = std::collections::HashSet::new();
        for _ in 0..16 {
            seen.insert(
                router
                    .select_worker_no_checks(&registry, &req, None)
                    .unwrap()
                    .worker
                    .name,
            );
        }
        assert_eq!(seen.len(), 4, "every worker took some of it, got {seen:?}");
    }

    /// A caller has to be able to tell a considered choice from a fallback.
    /// Ranking on service time alone sends every task to the same "fastest"
    /// worker until it is deep in its own queue. Measured on a live mesh: the
    /// median improved from 1.58 s to 1.12 s while p90 went from 2.07 s to
    /// 6.14 s. What a caller waits for is queue + service, not service.
    #[test]
    fn best_latency_accounts_for_what_is_already_queued() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let busy = registry.register(make_reg("busy-fast", 0, 4.0, 4, 0, 0.001));
        let idle = registry.register(make_reg("idle-slower", 1, 4.0, 4, 0, 0.001));
        registry.record_request(&busy.id, 10.0, true);
        registry.record_request(&idle.id, 30.0, true);
        // Four already in flight on the fast one, none on the other.
        for _ in 0..4 {
            registry.increment_active(&busy.id);
        }

        let d = router
            .select_worker_no_checks(
                &registry,
                &ResourceRequirements {
                    strategy: RoutingStrategy::BestLatency,
                    ..req_default()
                },
                None,
            )
            .unwrap();
        assert_eq!(
            d.worker.name, "idle-slower",
            "an idle 30 ms worker beats a 10 ms one with four queued: {}",
            d.reason
        );
    }

    #[test]
    fn the_decision_says_how_it_was_made() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let fast = registry.register(make_reg("fast", 0, 4.0, 4, 0, 0.001));
        registry.register(make_reg("slow", 1, 4.0, 4, 0, 0.002));
        registry.record_request(&fast.id, 5.0, true);

        let latency = router
            .select_worker_no_checks(
                &registry,
                &ResourceRequirements {
                    strategy: RoutingStrategy::BestLatency,
                    ..req_default()
                },
                None,
            )
            .unwrap();
        assert!(
            latency.reason.to_lowercase().contains("latency"),
            "{}",
            latency.reason
        );
    }

    #[test]
    fn test_round_robin_cycles_through_workers() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("w1", 0, 4.0, 4, 0, 0.001));
        registry.register(make_reg("w2", 1, 4.0, 4, 0, 0.001));
        let balances = balances_for("alice", 10000.0);

        let req = ResourceRequirements {
            strategy: RoutingStrategy::RoundRobin,
            ..req_default()
        };
        let d1 = router
            .select_worker(&registry, &balances, "alice", 10000.0, &req, None)
            .unwrap();
        let d2 = router
            .select_worker(&registry, &balances, "alice", 10000.0, &req, None)
            .unwrap();

        // Two consecutive calls must hit different workers
        assert_ne!(d1.worker.id, d2.worker.id);
    }

    #[test]
    fn test_local_mode_returns_first_worker_free() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("local-w", 0, 4.0, 4, 0, 0.001));

        let req = req_default();
        let decision = router
            .select_worker_no_checks(&registry, &req, None)
            .unwrap();
        assert_eq!(decision.estimated_cost, 0.0);
    }

    #[test]
    fn test_local_mode_no_workers_returns_error() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let err = router
            .select_worker_no_checks(&registry, &req_default(), None)
            .unwrap_err();
        assert_eq!(err.code, "NO_WORKERS");
    }

    // --- Cost estimation ---

    #[test]
    fn test_estimate_cost_returns_min_and_max() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("cheap", 0, 4.0, 4, 0, 0.001));
        registry.register(make_reg("pricey", 1, 4.0, 4, 0, 0.1));

        // Use 1-hour duration: cheap=Â¥0.001, pricey=Â¥0.1
        let req = ResourceRequirements {
            cpus: 1.0,
            estimated_duration_secs: 3600.0,
            ..req_default()
        };
        let (min, max) = router.estimate_cost(&registry, &req).unwrap();
        assert!(min < max);
        // min: 0.001 yen/hour * 1 hour = ¥0.001
        assert!((min - 0.001).abs() < 0.00001);
    }

    #[test]
    fn test_estimate_cost_no_workers_returns_none() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        assert!(router.estimate_cost(&registry, &req_default()).is_none());
    }

    // --- Worker type match ---

    #[test]
    fn test_worker_type_match_routes_correctly() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut reg = make_reg("ray-w", 0, 4.0, 4, 0, 0.001);
        reg.worker_type = "ray".to_string();
        registry.register(reg);
        let balances = balances_for("alice", 1000.0);

        let req = ResourceRequirements {
            worker_type: Some("ray".to_string()),
            ..req_default()
        };
        let decision = router
            .select_worker(&registry, &balances, "alice", 1000.0, &req, None)
            .unwrap();
        assert_eq!(decision.worker.worker_type, "ray");
    }

    // --- Price change scenario ---

    #[test]
    fn test_price_change_affects_routing_decision() {
        let router = Router::new();
        let registry = WorkerRegistry::new();

        // Two workers: w1 initially cheap, w2 initially expensive
        let _w1 = registry.register(make_reg("w1", 0, 4.0, 4, 0, 0.001));
        let _w2 = registry.register(make_reg("w2", 1, 4.0, 4, 0, 0.01));

        let balances = balances_for("alice", 10000.0);
        // Use 1-hour duration so price_per_hour values are directly comparable
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestPrice,
            estimated_duration_secs: 3600.0,
            ..req_default()
        };

        // w1 should win (cheaper)
        let d1 = router
            .select_worker(&registry, &balances, "alice", 10000.0, &req, None)
            .unwrap();
        assert_eq!(d1.worker.name, "w1");

        // Verify min cost matches w1's price_per_hour (Â¥0.001 for 1 hour)
        let (min, _max) = router.estimate_cost(&registry, &req).unwrap();
        assert!((min - 0.001).abs() < 0.00001);
    }

    // --- One selection core: what the four paths used to disagree about ---

    /// `best_availability` was round-robin in disguise wherever billing was
    /// off. The "is there anything to choose between these workers" test
    /// bucketed each score with `(v * 1e6) as u64`, and an availability score
    /// is negated before bucketing — every negative saturates to 0, so a
    /// 32-core machine and a 1-core one always compared equal and the
    /// spread-the-load fallback took over.
    #[test]
    fn best_availability_is_not_round_robin_in_disguise() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("roomy", 0, 32.0, 256, 0, 0.0));
        registry.register(make_reg("cramped", 1, 1.0, 1, 0, 0.0));

        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestAvailability,
            ..req_default()
        };
        for _ in 0..8 {
            let d = router
                .select_worker_no_checks(&registry, &req, None)
                .unwrap();
            assert_eq!(d.worker.name, "roomy", "reason was: {}", d.reason);
        }
    }

    /// The publish-lock path chooses a worker too, and it round-robinned
    /// whatever the caller asked for: `select_local_worker` did not so much as
    /// look at `requirements`. A broker running billing and peering therefore
    /// ignored `-s best_latency` on exactly the traffic it executes itself.
    #[test]
    fn the_local_path_honours_the_strategy_it_was_given() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let fast = registry.register(make_reg("fast", 0, 4.0, 4, 0, 0.001));
        let slow = registry.register(make_reg("slow", 1, 4.0, 4, 0, 0.001));
        registry.record_request(&fast.id, 5.0, true);
        registry.record_request(&slow.id, 900.0, true);

        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestLatency,
            ..req_default()
        };
        for _ in 0..8 {
            let d = router
                .select_local_worker(&registry, None, &req, None)
                .unwrap();
            assert_eq!(d.worker.name, "fast", "reason was: {}", d.reason);
        }
    }

    /// Round-robin picks a worker and then the "is this a tie?" test picked
    /// again, taking a second turn of the same counter: every worker keyed 0,
    /// which read as tied. Consecutive requests landed on the same worker —
    /// the exact opposite of what round-robin is for.
    #[test]
    fn round_robin_visits_every_worker() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        for i in 0..4 {
            registry.register(make_reg(&format!("w{i}"), i, 4.0, 4, 0, 0.001));
        }
        let req = ResourceRequirements {
            strategy: RoutingStrategy::RoundRobin,
            ..req_default()
        };
        let mut seen = std::collections::HashSet::new();
        for _ in 0..8 {
            seen.insert(
                router
                    .select_worker_no_checks(&registry, &req, None)
                    .unwrap()
                    .worker
                    .name,
            );
        }
        assert_eq!(seen.len(), 4, "round-robin reached {seen:?}");
    }

    /// Spreading a tie was written for local mode and stayed there, so a
    /// billed broker whose workers all charge the same handed every job to
    /// whichever one sorted first. Nothing in "best price" says "and always
    /// the same one".
    #[test]
    fn the_billed_path_spreads_what_the_strategy_cannot_separate() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        for i in 0..4 {
            registry.register(make_reg(&format!("w{i}"), i, 4.0, 4, 0, 0.5));
        }
        let balances = balances_for("alice", 10_000.0);
        let req = ResourceRequirements {
            strategy: RoutingStrategy::BestPrice,
            ..req_default()
        };
        let mut seen = std::collections::HashSet::new();
        for _ in 0..16 {
            seen.insert(
                router
                    .select_worker(&registry, &balances, "alice", 10_000.0, &req, None)
                    .unwrap()
                    .worker
                    .name,
            );
        }
        assert_eq!(seen.len(), 4, "every worker took some of it, got {seen:?}");
    }
}

/// What the strategies promise, checked against what they do (#335).
///
/// `zc bench --compare` on a live fleet showed four of six strategies not
/// doing what their own description says: `best_price` was the second MOST
/// expensive, `round_robin` was statistically `random`, and the two
/// resource-aware strategies routed 0% and 1% of work to the free local
/// workers that were also 400x faster. These are the assertions that would
/// have failed then.
#[cfg(test)]
mod strategy_promise_tests {
    use super::tests::make_reg;
    use super::*;
    use crate::broker::worker::WorkerRegistry;

    /// `w` as the registry would hold it, optionally marked as a peer's.
    fn worker(name: &str, port: usize, cpus: f64, gib: u64, price: f64, peer: bool) -> Worker {
        let reg = WorkerRegistry::new();
        let mut r = make_reg(name, port, cpus, gib, 0, price);
        if peer {
            r.source_node = Some("node-6188100f5daf463e".into());
        }
        reg.register(r)
    }

    /// The measured fleet in miniature: one small free local box, two big
    /// billed remote ones.
    fn mixed_fleet() -> Vec<Worker> {
        vec![
            worker("local-small", 1, 8.0, 16, 0.0, false),
            worker("remote-big-a", 2, 32.0, 62, 3.6, true),
            worker("remote-big-b", 3, 32.0, 62, 3.6, true),
        ]
    }

    fn req(strategy: RoutingStrategy) -> ResourceRequirements {
        ResourceRequirements {
            strategy,
            ..Default::default()
        }
    }

    #[test]
    fn best_price_picks_the_free_worker() {
        // The headline inversion: `best_latency` beat `best_price` ON PRICE
        // by an infinite ratio (0.0000 vs ¥0.2239) because the strategy
        // named "lowest cost per compute" could not see that local work is
        // free.
        let router = Router::new();
        let fleet = mixed_fleet();
        let (idx, _) = router.select_by_strategy(&fleet, &req(RoutingStrategy::BestPrice));
        assert_eq!(
            fleet[idx].name, "local-small",
            "best_price must rank free work first"
        );
    }

    #[test]
    fn best_price_is_not_erased_by_the_minimum_charge() {
        // Ranking on estimate_cost(1s) floored every worker at or below
        // 3.6 yen/h to exactly min_charge — 9 of 13 on the measured fleet —
        // so the rate it was comparing did not survive into the comparison.
        let router = Router::new();
        let fleet = vec![
            worker("dearer", 1, 8.0, 16, 3.0, true),
            worker("cheaper", 2, 8.0, 16, 0.5, true),
        ];
        let one_second = fleet[0].pricing.estimate_cost(1.0);
        assert_eq!(
            one_second,
            fleet[1].pricing.estimate_cost(1.0),
            "fixture must be one where the 1s floor hides the difference"
        );
        let (idx, _) = router.select_by_strategy(&fleet, &req(RoutingStrategy::BestPrice));
        assert_eq!(fleet[idx].name, "cheaper");
    }

    #[test]
    fn best_price_breaks_ties_deterministically() {
        // `min_by` returns the first of equals and "first" came from DashMap
        // iteration — shard order, unstable across calls. That is why
        // best_price measured the same as random.
        let router = Router::new();
        let fleet = vec![
            worker("bbb", 1, 8.0, 16, 3.6, true),
            worker("aaa", 2, 8.0, 16, 3.6, true),
        ];
        let first = router
            .select_by_strategy(&fleet, &req(RoutingStrategy::BestPrice))
            .0;
        for _ in 0..20 {
            assert_eq!(
                router
                    .select_by_strategy(&fleet, &req(RoutingStrategy::BestPrice))
                    .0,
                first,
                "equal prices must resolve the same way every time"
            );
        }
    }

    #[test]
    fn round_robin_visits_every_worker_before_repeating() {
        // "Even distribution" is a per-worker fairness claim. Indexing a
        // monotonic counter into a list that permutes between calls is
        // sampling with replacement, and provides no such thing.
        let router = Router::new();
        let fleet = mixed_fleet();
        let mut seen = std::collections::HashSet::new();
        for _ in 0..fleet.len() {
            let (idx, _) = router.select_by_strategy(&fleet, &req(RoutingStrategy::RoundRobin));
            seen.insert(fleet[idx].name.clone());
        }
        assert_eq!(
            seen.len(),
            fleet.len(),
            "three consecutive picks over three workers must touch each once, got {seen:?}"
        );
    }

    #[test]
    fn an_empty_small_box_beats_a_nearly_full_big_one() {
        // The old score added cores to gibibytes. Incommensurable units, and
        // the sum was dominated by whichever number was larger — memory, on a
        // 62 GiB box — so it simply picked the biggest machine however full.
        //
        // Bigger-idle-beats-smaller-idle is still right and still holds (see
        // `best_availability_is_not_round_robin_in_disguise`); what changes is
        // that being big is no longer enough on its own.
        let small_idle = worker("small-idle", 1, 8.0, 16, 0.0, false);
        let mut big_busy = worker("big-busy", 2, 32.0, 62, 3.6, true);
        big_busy.resources.cpus_available = 1.0;
        big_busy.resources.memory_available = 2 * 1024 * 1024 * 1024;

        assert!(
            availability_score(&small_idle) > availability_score(&big_busy),
            "an idle 8-core must beat a 32-core with one core and 2 GiB left"
        );

        let router = Router::new();
        let fleet = vec![big_busy, small_idle];
        let (idx, _) = router.select_by_strategy(&fleet, &req(RoutingStrategy::BestAvailability));
        assert_eq!(fleet[idx].name, "small-idle");
    }

    #[test]
    fn in_flight_work_can_actually_move_the_ranking() {
        // The 0.5-per-request penalty was noise against scores spanning
        // 12.9..94.1: ~160 concurrent requests before it changed anything,
        // so the one dynamic input the strategy had never balanced load.
        let idle = worker("idle", 1, 8.0, 16, 0.0, false);
        let mut loaded = worker("loaded", 2, 8.0, 16, 0.0, false);
        loaded.active_requests = 8;
        assert!(
            availability_score(&idle) > availability_score(&loaded),
            "eight in-flight requests on eight cores must outweigh a tie on capacity"
        );
    }

    #[test]
    fn capacity_weight_does_not_bury_the_small_free_node() {
        // weighted_capacity multiplied cores by gibibytes, giving the local
        // node 1.7% of total weight — and the bench duly reported 1% of work
        // landing free.
        let fleet = mixed_fleet();
        let weights: Vec<f64> = fleet.iter().map(capacity_weight).collect();
        let total: f64 = weights.iter().sum();
        let local_share = weights[0] / total;
        // 8 free cores among 8 + 32 + 32 is 11.1%. The old product formula
        // gave the same node 1.7%, because it multiplied cores BY gibibytes
        // and squared the bias. Proportional to capacity is what "weighted by
        // capacity" means.
        assert!(
            (0.09..0.14).contains(&local_share),
            "an 8-core node among two 32-core nodes should carry ~11% of the \
             weight, not 1.7%; got {:.1}%",
            local_share * 100.0
        );
    }
}

#[cfg(test)]
mod adaptive_tests {
    use super::tests::{make_reg, req_default};
    use super::*;
    use crate::broker::policy::Weights;
    use crate::broker::sampler::Rng;

    /// The whole point: send work where it has been measured to go fastest,
    /// without being told a strategy.
    #[test]
    fn it_prefers_the_worker_that_has_been_fastest() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let fast = registry.register(make_reg("fast", 0, 4.0, 4, 0, 0.001));
        let slow = registry.register(make_reg("slow", 1, 4.0, 4, 0, 0.001));
        for _ in 0..40 {
            registry.record_request(&fast.id, 20.0, true);
            registry.record_request(&slow.id, 900.0, true);
        }

        let mut rng = Rng::seeded(4);
        let w = Weights::default();
        let picks = (0..200)
            .filter(|_| {
                router
                    .select_worker_no_checks(
                        &registry,
                        &req_default(),
                        Some(Adaptive {
                            rng: &mut rng,
                            weights: &w,
                        }),
                    )
                    .map(|d| d.worker.name == "fast")
                    .unwrap_or(false)
            })
            .count();
        assert!(picks > 160, "chose the fast worker {picks}/200 times");
    }

    /// A worker nothing is known about must still be tried, or a new machine
    /// never gets a chance to prove itself.
    #[test]
    fn a_brand_new_worker_is_still_tried() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let known = registry.register(make_reg("known", 0, 4.0, 4, 0, 0.001));
        registry.register(make_reg("brand-new", 1, 4.0, 4, 0, 0.001));
        for _ in 0..40 {
            registry.record_request(&known.id, 200.0, true);
        }

        let mut rng = Rng::seeded(9);
        let w = Weights::default();
        let tried = (0..200)
            .filter(|_| {
                router
                    .select_worker_no_checks(
                        &registry,
                        &req_default(),
                        Some(Adaptive {
                            rng: &mut rng,
                            weights: &w,
                        }),
                    )
                    .map(|d| d.worker.name == "brand-new")
                    .unwrap_or(false)
            })
            .count();
        assert!(
            (10..190).contains(&tried),
            "explored but not favoured blindly: {tried}/200"
        );
    }

    #[test]
    fn it_says_adaptive_in_the_reason_and_charges_nothing() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let w0 = registry.register(make_reg("w0", 0, 4.0, 4, 0, 0.001));
        registry.record_request(&w0.id, 15.0, true);
        let mut rng = Rng::seeded(2);
        let d = router
            .select_worker_no_checks(
                &registry,
                &req_default(),
                Some(Adaptive {
                    rng: &mut rng,
                    weights: &Weights::default(),
                }),
            )
            .unwrap();
        assert!(d.reason.starts_with("Adaptive:"), "{}", d.reason);
        assert_eq!(d.estimated_cost, 0.0, "this path bills nothing");
    }

    #[test]
    fn no_workers_is_an_error_not_a_panic() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut rng = Rng::seeded(1);
        let err = router
            .select_worker_no_checks(
                &registry,
                &req_default(),
                Some(Adaptive {
                    rng: &mut rng,
                    weights: &Weights::default(),
                }),
            )
            .unwrap_err();
        assert_eq!(err.code, "NO_WORKERS");
    }
}

/// `POST /route` (contract zc#345 §4): a preview of `select_worker`'s
/// filtering and strategy ranking that must never execute, reserve, bill or
/// mutate anything.
#[cfg(test)]
mod route_dry_run_tests {
    use super::tests::make_reg;
    use super::*;
    use crate::broker::balance::BalanceManager;
    use crate::broker::worker::{
        HardwareInfo, WorkerPricing, WorkerRegistration, WorkerRegistry, WorkerResources,
    };

    fn balances_for(user: &str, balance: f64) -> BalanceManager {
        let mgr = BalanceManager::new();
        mgr.get_or_create(user, balance);
        mgr
    }

    fn req(strategy: RoutingStrategy) -> ResourceRequirements {
        ResourceRequirements {
            strategy,
            ..Default::default()
        }
    }

    #[test]
    fn best_price_picks_the_cheapest_eligible_worker() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("dearer", 0, 4.0, 4, 0, 5.0));
        registry.register(make_reg("cheapest", 1, 4.0, 4, 0, 1.0));
        registry.register(make_reg("middling", 2, 4.0, 4, 0, 3.0));

        let mut r = req(RoutingStrategy::BestPrice);
        r.estimated_duration_secs = 3600.0;
        let result = router.route_dry_run(&registry, &r).unwrap();

        assert_eq!(result.strategy, RoutingStrategy::BestPrice);
        let chosen = result.chosen.expect("an eligible worker exists");
        assert_eq!(chosen.worker.name, "cheapest");
        assert_eq!(result.candidates[0].worker.name, "cheapest");
        assert_eq!(
            result
                .candidates
                .iter()
                .map(|c| &c.worker.name)
                .collect::<Vec<_>>(),
            vec!["cheapest", "middling", "dearer"],
            "candidates must be ranked cheapest first"
        );
        assert!(result.excluded.is_empty());
    }

    #[test]
    fn best_price_breaks_ties_deterministically() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(make_reg("bbb", 0, 4.0, 4, 0, 3.6));
        registry.register(make_reg("aaa", 1, 4.0, 4, 0, 3.6));

        let r = req(RoutingStrategy::BestPrice);
        let first = router.route_dry_run(&registry, &r).unwrap();
        for _ in 0..10 {
            let again = router.route_dry_run(&registry, &r).unwrap();
            assert_eq!(
                again.chosen.unwrap().worker.name,
                first.chosen.as_ref().unwrap().worker.name,
                "equal prices must resolve to the same worker every call"
            );
        }
    }

    #[test]
    fn best_availability_picks_the_least_loaded_worker() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let roomy = registry.register(make_reg("roomy", 0, 32.0, 256, 0, 0.0));
        let cramped = registry.register(make_reg("cramped", 1, 32.0, 256, 0, 0.0));
        // `cramped` has the same total capacity but is nearly saturated.
        registry.update_resources(
            &cramped.id,
            WorkerResources {
                cpus_total: 32.0,
                cpus_available: 1.0,
                memory_total: 256 * 1024 * 1024 * 1024,
                memory_available: 2 * 1024 * 1024 * 1024,
                gpus_total: 0,
                gpus_available: 0,
            },
            HardwareInfo::default(),
        );
        for _ in 0..4 {
            registry.increment_active(&roomy.id);
        }

        let result = router
            .route_dry_run(&registry, &req(RoutingStrategy::BestAvailability))
            .unwrap();
        assert_eq!(
            result.chosen.unwrap().worker.name,
            "roomy",
            "32 idle cores (minus 4 in flight) must still beat 1 idle core"
        );
    }

    #[test]
    fn min_vram_gb_excludes_small_vram_workers_with_a_reason() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut small = make_reg("small-vram", 0, 4.0, 16, 1, 1.0);
        small.hardware.gpu_vram_gb = Some(8);
        let mut big = make_reg("big-vram", 1, 4.0, 16, 1, 1.0);
        big.hardware.gpu_vram_gb = Some(24);
        let mut unknown = make_reg("no-vram-advertised", 2, 4.0, 16, 1, 1.0);
        unknown.hardware.gpu_vram_gb = None;
        registry.register(small);
        registry.register(big);
        registry.register(unknown);

        let mut r = req(RoutingStrategy::BestPrice);
        r.gpus = 1;
        r.min_vram_gb = Some(16);
        let result = router.route_dry_run(&registry, &r).unwrap();

        assert_eq!(result.chosen.unwrap().worker.name, "big-vram");
        assert_eq!(result.candidates.len(), 1);
        assert_eq!(result.excluded.len(), 2);
        let reasons: std::collections::HashMap<_, _> = result
            .excluded
            .iter()
            .map(|e| (e.worker_id.clone(), e.reason.clone()))
            .collect();
        let registry_ids: std::collections::HashMap<_, _> = registry
            .healthy()
            .into_iter()
            .map(|w| (w.name.clone(), w.id.clone()))
            .collect();
        assert!(
            reasons[&registry_ids["small-vram"]].contains("gpu_vram_gb 8 < min_vram_gb 16"),
            "{:?}",
            reasons
        );
        assert!(
            reasons[&registry_ids["no-vram-advertised"]]
                .contains("no advertised gpu_vram_gb < min_vram_gb 16"),
            "{:?}",
            reasons
        );
    }

    #[test]
    fn nothing_eligible_reports_404_shaped_result_listing_why() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let mut small = make_reg("small-vram", 0, 4.0, 16, 1, 1.0);
        small.hardware.gpu_vram_gb = Some(8);
        registry.register(small);

        let mut r = req(RoutingStrategy::BestPrice);
        r.gpus = 1;
        r.min_vram_gb = Some(80);
        let result = router.route_dry_run(&registry, &r).unwrap();
        assert!(result.chosen.is_none());
        assert!(result.candidates.is_empty());
        assert_eq!(result.excluded.len(), 1);
        assert!(result.excluded[0].reason.contains("min_vram_gb 80"));
    }

    #[test]
    fn route_dry_run_never_advances_the_round_robin_cursor() {
        // Calling /route N times must leave /execute's own round-robin
        // sequence exactly as if /route had never been called. One shared
        // registry (so both routers see identical worker ids -- round-robin
        // orders by id) and two routers: `exercised` takes 25 dry runs first,
        // `untouched` never sees one. If a dry run advanced the cursor,
        // `exercised` would start its real selections mid-cycle instead of
        // at slot 0, same as `untouched`.
        let registry = WorkerRegistry::new();
        for i in 0..4 {
            registry.register(make_reg(&format!("w{i}"), i, 4.0, 4, 0, 0.001));
        }
        let r = req(RoutingStrategy::RoundRobin);

        let exercised = Router::new();
        for _ in 0..25 {
            exercised.route_dry_run(&registry, &r).unwrap();
        }
        let untouched = Router::new();

        for n in 0..8 {
            let a = exercised
                .select_worker_no_checks(&registry, &r, None)
                .unwrap();
            let b = untouched
                .select_worker_no_checks(&registry, &r, None)
                .unwrap();
            assert_eq!(
                a.worker.name, b.worker.name,
                "pick {n}: 25 dry runs must not have moved the real round-robin cursor"
            );
        }
    }

    #[test]
    fn route_dry_run_never_touches_active_requests_or_quota() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        let w = registry.register(make_reg("w0", 0, 4.0, 4, 0, 0.001));
        let r = req(RoutingStrategy::BestPrice);

        for _ in 0..10 {
            router.route_dry_run(&registry, &r).unwrap();
        }
        let after = registry.get(&w.id).unwrap();
        assert_eq!(
            after.active_requests, 0,
            "a dry run must never reserve/execute"
        );
    }

    /// Fixture worker for the parity test below: one row per dimension either
    /// `select()`'s retain chain or `ineligibility_reason` filters on.
    struct ParityWorker {
        name: &'static str,
        worker_type: &'static str,
        tags: &'static [&'static str],
        price_per_hour: f64,
        cpus_total: f64,
        memory_gib: u64,
        gpus_total: u32,
        gpu_vram_gb: Option<u32>,
        max_timeout_secs: f64,
        active_requests: u32,
        latency_ms: f64,
    }

    fn parity_workers() -> Vec<ParityWorker> {
        vec![
            ParityWorker {
                name: "w-std",
                worker_type: "zakuro",
                tags: &[],
                price_per_hour: 1.0,
                cpus_total: 8.0,
                memory_gib: 16,
                gpus_total: 1,
                gpu_vram_gb: Some(24),
                max_timeout_secs: 0.0,
                active_requests: 0,
                latency_ms: 10.0,
            },
            ParityWorker {
                name: "w-gpu-tag",
                worker_type: "zakuro",
                tags: &["gpu", "a100"],
                price_per_hour: 2.0,
                cpus_total: 8.5,
                memory_gib: 16,
                gpus_total: 1,
                gpu_vram_gb: Some(80),
                max_timeout_secs: 0.0,
                active_requests: 2,
                latency_ms: 20.0,
            },
            ParityWorker {
                name: "w-ray",
                worker_type: "ray",
                tags: &[],
                price_per_hour: 0.5,
                cpus_total: 4.0,
                memory_gib: 8,
                gpus_total: 0,
                gpu_vram_gb: None,
                max_timeout_secs: 0.0,
                active_requests: 0,
                latency_ms: 30.0,
            },
            ParityWorker {
                name: "w-small-cpu",
                worker_type: "zakuro",
                tags: &[],
                price_per_hour: 1.5,
                cpus_total: 1.0,
                memory_gib: 2,
                gpus_total: 0,
                gpu_vram_gb: None,
                max_timeout_secs: 0.0,
                active_requests: 0,
                latency_ms: 40.0,
            },
            ParityWorker {
                name: "w-small-vram",
                worker_type: "zakuro",
                tags: &["gpu"],
                price_per_hour: 1.1,
                cpus_total: 9.0,
                memory_gib: 16,
                gpus_total: 1,
                gpu_vram_gb: Some(8),
                max_timeout_secs: 0.0,
                active_requests: 0,
                latency_ms: 50.0,
            },
            ParityWorker {
                name: "w-no-vram-data",
                worker_type: "zakuro",
                tags: &["gpu"],
                price_per_hour: 1.2,
                cpus_total: 10.0,
                memory_gib: 16,
                gpus_total: 1,
                gpu_vram_gb: None,
                max_timeout_secs: 0.0,
                active_requests: 0,
                latency_ms: 60.0,
            },
            ParityWorker {
                name: "w-limited-timeout",
                worker_type: "zakuro",
                tags: &[],
                price_per_hour: 1.3,
                cpus_total: 11.0,
                memory_gib: 16,
                gpus_total: 0,
                gpu_vram_gb: None,
                max_timeout_secs: 30.0,
                active_requests: 0,
                latency_ms: 70.0,
            },
            ParityWorker {
                name: "w-unlimited-timeout",
                worker_type: "zakuro",
                tags: &[],
                price_per_hour: 3.0,
                cpus_total: 12.0,
                memory_gib: 16,
                gpus_total: 0,
                gpu_vram_gb: None,
                max_timeout_secs: 0.0,
                active_requests: 0,
                latency_ms: 80.0,
            },
            ParityWorker {
                name: "w-busy",
                worker_type: "zakuro",
                tags: &[],
                price_per_hour: 2.5,
                cpus_total: 16.0,
                memory_gib: 32,
                gpus_total: 0,
                gpu_vram_gb: None,
                max_timeout_secs: 0.0,
                active_requests: 20,
                latency_ms: 90.0,
            },
            ParityWorker {
                name: "w-cheap-tiny",
                worker_type: "zakuro",
                tags: &[],
                price_per_hour: 0.1,
                cpus_total: 0.5,
                memory_gib: 1,
                gpus_total: 0,
                gpu_vram_gb: None,
                max_timeout_secs: 0.0,
                active_requests: 0,
                latency_ms: 100.0,
            },
        ]
    }

    /// One requirements scenario, exercising one (or more) of the predicates
    /// `ineligibility_reason` duplicates from `select()`'s retain chain.
    struct ParityRequirement {
        label: &'static str,
        cpus: f64,
        memory_gib: u64,
        gpus: u32,
        min_vram_gb: Option<u32>,
        timeout_secs: f64,
        tags: &'static [&'static str],
        worker_type: Option<&'static str>,
    }

    fn parity_requirements() -> Vec<ParityRequirement> {
        vec![
            ParityRequirement {
                label: "default",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 0.0,
                tags: &[],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_gpu",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 1,
                min_vram_gb: None,
                timeout_secs: 0.0,
                tags: &[],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_gpu_min_vram_16",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 1,
                min_vram_gb: Some(16),
                timeout_secs: 0.0,
                tags: &[],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_gpu_min_vram_80",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 1,
                min_vram_gb: Some(80),
                timeout_secs: 0.0,
                tags: &[],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_8_cpu_16gib",
                cpus: 8.0,
                memory_gib: 16,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 0.0,
                tags: &[],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_ray",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 0.0,
                tags: &[],
                worker_type: Some("ray"),
            },
            ParityRequirement {
                label: "needs_tag_gpu",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 0.0,
                tags: &["gpu"],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_tag_gpu_a100",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 0.0,
                tags: &["gpu", "a100"],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_timeout_60_excludes_limited",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 60.0,
                tags: &[],
                worker_type: None,
            },
            ParityRequirement {
                label: "needs_timeout_10_excludes_nobody",
                cpus: 1.0,
                memory_gib: 1,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 10.0,
                tags: &[],
                worker_type: None,
            },
            ParityRequirement {
                label: "impossible",
                cpus: 999.0,
                memory_gib: 1,
                gpus: 0,
                min_vram_gb: None,
                timeout_secs: 0.0,
                tags: &[],
                worker_type: None,
            },
        ]
    }

    /// `/route`'s preview and `/execute`'s real selection (`select_worker`,
    /// with the same `Scope::Any` / capacity+label-checked / uncapped-price
    /// policy `route_dry_run` mirrors, and a balance large enough that
    /// balance sufficiency -- which a dry run cannot know the caller's
    /// balance for and so never checks -- never itself excludes a worker)
    /// must agree on every worker/requirement/strategy combination below, or
    /// on "nothing is eligible". This is NOT guaranteed by sharing code (see
    /// `ineligibility_reason`'s docs): it is what would fail the day a filter
    /// is added to one side and not the other.
    #[test]
    fn route_dry_run_agrees_with_select_worker_everywhere() {
        let workers = parity_workers();
        let req_specs = parity_requirements();
        let strategies = [
            RoutingStrategy::BestPrice,
            RoutingStrategy::BestAvailability,
            RoutingStrategy::BestLatency,
        ];

        let mut cases = 0;
        for req_spec in &req_specs {
            for strategy in strategies {
                cases += 1;
                let registry = WorkerRegistry::new();
                for (i, w) in workers.iter().enumerate() {
                    let registered = registry.register(WorkerRegistration {
                        name: w.name.to_string(),
                        uri: format!("http://127.0.0.1:{}", 21000 + i),
                        worker_type: w.worker_type.to_string(),
                        resources: WorkerResources {
                            cpus_total: w.cpus_total,
                            cpus_available: w.cpus_total,
                            memory_total: w.memory_gib * 1024 * 1024 * 1024,
                            memory_available: w.memory_gib * 1024 * 1024 * 1024,
                            gpus_total: w.gpus_total,
                            gpus_available: w.gpus_total,
                        },
                        pricing: WorkerPricing {
                            price_per_hour: w.price_per_hour,
                            min_charge: 0.001,
                        },
                        tags: w.tags.iter().map(|t| t.to_string()).collect(),
                        max_timeout_secs: w.max_timeout_secs,
                        hardware: HardwareInfo {
                            gpu_vram_gb: w.gpu_vram_gb,
                            ..Default::default()
                        },
                        wireguard_ip: None,
                        is_docker: None,
                        source_node: None,
                        explicit_local: false,
                        provider_type: Default::default(),
                        served_models: vec![],
                        price_per_mtok: 0.0,
                    });
                    for _ in 0..w.active_requests {
                        registry.increment_active(&registered.id);
                    }
                    // Every worker measured, and all distinctly, so neither
                    // ranking hits a tie it would have to spread (which would
                    // make the comparison depend on round-robin state that
                    // the dry run deliberately never touches).
                    registry.record_request(&registered.id, w.latency_ms, true);
                }

                let requirements = ResourceRequirements {
                    cpus: req_spec.cpus,
                    memory_bytes: req_spec.memory_gib * 1024 * 1024 * 1024,
                    gpus: req_spec.gpus,
                    worker_type: req_spec.worker_type.map(str::to_string),
                    tags: req_spec.tags.iter().map(|t| t.to_string()).collect(),
                    estimated_duration_secs: 3600.0,
                    strategy,
                    timeout_secs: req_spec.timeout_secs,
                    min_vram_gb: req_spec.min_vram_gb,
                    ..Default::default()
                };

                let router = Router::new();
                let dry = router.route_dry_run(&registry, &requirements).unwrap();

                let balances = balances_for("parity-user", 1e12);
                let real = router.select_worker(
                    &registry,
                    &balances,
                    "parity-user",
                    1e12,
                    &requirements,
                    None,
                );

                match (dry.chosen, real) {
                    (Some(d), Ok(r)) => assert_eq!(
                        d.worker.id, r.worker.id,
                        "requirement={} strategy={:?}: dry run chose {} but /execute's real                          selection chose {}",
                        req_spec.label, strategy, d.worker.name, r.worker.name
                    ),
                    (None, Err(e)) => {
                        // Both agree nothing is eligible.
                        let _ = e;
                    }
                    (Some(d), Err(e)) => panic!(
                        "requirement={} strategy={:?}: dry run chose {} but the real                          selection found nothing eligible ({})",
                        req_spec.label, strategy, d.worker.name, e.code
                    ),
                    (None, Ok(r)) => panic!(
                        "requirement={} strategy={:?}: dry run found nothing eligible but the                          real selection chose {}",
                        req_spec.label, strategy, r.worker.name
                    ),
                }
            }
        }
        // Sanity: the matrix actually ran as many cases as advertised, so a
        // typo that emptied one of the tables silently can't pass this test
        // by doing nothing.
        assert_eq!(cases, req_specs.len() * strategies.len());
        assert!(workers.len() >= 10, "fixture must cover every dimension");
    }
}

#[cfg(test)]
mod python_routing_tests {
    //! A cloudpickled payload runs only on the CPython minor that built it
    //! (zc#327). zc-broker-0's worker container runs 3.14 while clients run
    //! 3.12: every job placed there died with "A process in the process pool
    //! was terminated abruptly" -- and was billed.
    use super::tests::{make_reg, req_default};
    use super::*;
    use crate::broker::worker::WorkerRegistration;

    fn reg(name: &str, port: usize, py: Option<&str>) -> WorkerRegistration {
        let mut r = make_reg(name, port, 4.0, 4, 0, 0.001);
        r.hardware.python_version = py.map(str::to_string);
        r
    }

    fn req(py: &str) -> ResourceRequirements {
        ResourceRequirements {
            python: Some(py.to_string()),
            ..req_default()
        }
    }

    #[test]
    fn a_payload_runs_only_on_the_same_python_minor() {
        let w = |py: Option<&str>| {
            let mut w = Worker::new(
                "id".into(),
                "w".into(),
                "http://127.0.0.1:3960".into(),
                "zakuro".into(),
            );
            w.hardware.python_version = py.map(str::to_string);
            w
        };
        assert!(runs_payload(&w(Some("3.12.3")), Some("3.12")));
        assert!(
            runs_payload(&w(Some("3.12.12")), Some("3.12.3")),
            "minor, not patch"
        );
        assert!(!runs_payload(&w(Some("3.14.5")), Some("3.12")));
        assert!(
            !runs_payload(&w(Some("3.1")), Some("3.12")),
            "3.1 is not 3.12"
        );
        assert!(
            !runs_payload(&w(None), Some("3.12")),
            "unknown is not compatible"
        );
        assert!(runs_payload(&w(None), None), "no requirement, no filter");
    }

    #[test]
    fn the_dry_run_rules_out_another_interpreter_and_says_why() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(reg("py312", 0, Some("3.12.3")));
        registry.register(reg("py314", 1, Some("3.14.5")));
        let run = router.route_dry_run(&registry, &req("3.12")).unwrap();
        let names: Vec<&str> = run
            .candidates
            .iter()
            .map(|c| c.worker.name.as_str())
            .collect();
        assert_eq!(names, vec!["py312"]);
        assert!(
            run.excluded
                .iter()
                .any(|e| e.reason.contains("python 3.14.5")),
            "{:?}",
            run.excluded
        );
    }

    #[test]
    fn live_selection_never_picks_another_interpreter() {
        let router = Router::new();
        let registry = WorkerRegistry::new();
        registry.register(reg("py314", 0, Some("3.14.5")));
        assert!(router
            .select_local_worker(&registry, None, &req("3.12"), None)
            .is_err());
        registry.register(reg("py312", 1, Some("3.12.3")));
        let d = router
            .select_local_worker(&registry, None, &req("3.12"), None)
            .unwrap();
        assert_eq!(d.worker.name, "py312");
        assert!(
            router
                .select_local_worker(&registry, None, &req_default(), None)
                .is_ok(),
            "no python requirement: unchanged"
        );
    }
}