zc2 0.0.53

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
//! Worker registry for tracking available compute workers.

use chrono::{DateTime, Duration, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::collections::{HashSet, VecDeque};
use std::sync::Mutex;

/// Wildcard `served_models` entry meaning "serves any model" (used by general providers).
pub const MODEL_WILDCARD: &str = "*";

/// Whether a worker serves a fixed catalog of published models (`Specialized`,
/// indexed by model uuid) or can serve any model (`General`, e.g. a generic
/// inference backend).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderType {
    /// Serves any requested model.
    General,
    /// Serves only the models listed in `served_models`.
    #[default]
    Specialized,
}

/// Worker status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WorkerStatus {
    /// Worker is healthy and accepting requests
    Healthy,
    /// Worker is busy but still accepting requests
    Busy,
    /// Worker is unhealthy or unreachable
    Unhealthy,
    /// Worker is draining (not accepting new requests)
    Draining,
}

/// Resource availability on a worker
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerResources {
    /// Total CPU cores
    pub cpus_total: f64,
    /// Available CPU cores
    pub cpus_available: f64,
    /// Total memory in bytes
    pub memory_total: u64,
    /// Available memory in bytes
    pub memory_available: u64,
    /// Total GPUs
    pub gpus_total: u32,
    /// Available GPUs
    pub gpus_available: u32,
}

impl Default for WorkerResources {
    fn default() -> Self {
        Self {
            cpus_total: 1.0,
            cpus_available: 1.0,
            memory_total: 1024 * 1024 * 1024, // 1 GiB
            memory_available: 1024 * 1024 * 1024,
            gpus_total: 0,
            gpus_available: 0,
        }
    }
}

/// Aggregated free-resource snapshot across a broker's healthy local workers.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct BrokerResources {
    /// Sum of available CPU cores across healthy workers (floored to whole cores).
    pub cpus_available: u64,
    /// Sum of available memory (bytes) across healthy workers.
    pub memory_available: u64,
    /// Sum of available GPUs across healthy workers.
    pub gpus_available: u32,
    /// Count of workers included in the aggregation.
    pub healthy_workers: u32,
}

pub(crate) fn default_price_per_hour() -> f64 {
    540.0
}
fn default_min_charge() -> f64 {
    0.15
}

/// Pricing information for a worker
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerPricing {
    /// Flat hourly rate for the worker (in yen)
    #[serde(default = "default_price_per_hour")]
    pub price_per_hour: f64,
    /// Minimum charge per request (in yen)
    #[serde(default = "default_min_charge")]
    pub min_charge: f64,
}

impl Default for WorkerPricing {
    fn default() -> Self {
        Self {
            price_per_hour: default_price_per_hour(), // ¥0.15 per second
            min_charge: default_min_charge(),         // minimum ¥0.15 per request
        }
    }
}

impl WorkerPricing {
    /// Calculate estimated cost for a request
    pub fn estimate_cost(&self, duration_secs: f64) -> f64 {
        (self.price_per_hour / 3600.0 * duration_secs).max(self.min_charge)
    }

    /// Calculate price score for worker selection (lower is better).
    /// Uses a 10-second reference job to weight min_charge fairly against hourly rate.
    pub fn price_score(&self) -> f64 {
        self.estimate_cost(10.0)
    }
}

/// Per-worker request quotas (max requests per time window)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerQuotas {
    /// Max requests allowed in a rolling 5-hour window (0 = unlimited)
    pub per_5h: u64,
    /// Max requests allowed in a rolling 7-day window (0 = unlimited)
    pub per_week: u64,
    /// Max requests allowed in a rolling 30-day window (0 = unlimited)
    pub per_month: u64,
}

impl Default for WorkerQuotas {
    fn default() -> Self {
        Self {
            per_5h: std::env::var("ZAKURO_QUOTA_5H")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0),
            per_week: std::env::var("ZAKURO_QUOTA_WEEK")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0),
            per_month: std::env::var("ZAKURO_QUOTA_MONTH")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0),
        }
    }
}

/// Hardware details reported by the worker's /info endpoint
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HardwareInfo {
    /// GPU model name (e.g. "A100 80GB", "RTX 4090")
    #[serde(default)]
    pub gpu_model: Option<String>,
    /// GPU VRAM in GiB
    #[serde(default)]
    pub gpu_vram_gb: Option<u32>,
    /// CPU model name (e.g. "AMD EPYC 7543")
    #[serde(default)]
    pub cpu_model: Option<String>,
    /// Total storage in GiB
    #[serde(default)]
    pub storage_gb: Option<u32>,
    /// Total RAM in GiB (zak-forge runners report it; L'Atelier's quote-time fit check sizes a CPU
    /// runner -- `gpu_vram_gb` 0 -- by it). `None` from a worker that does not report it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ram_gb: Option<f64>,
    /// The CPython this worker runs, e.g. "3.12.3" (zc#327).
    ///
    /// Every other field here describes hardware. This one decides whether the
    /// worker can run the payload at all: a cloudpickled function carries raw
    /// CPython bytecode, and opcode numbers are renumbered between minor
    /// versions -- `LOAD_FAST` is 124 up to 3.12 and 85 from 3.13. A worker on
    /// a different minor version answers EVERY request with
    /// `SystemError: unknown opcode` while being perfectly healthy, and the
    /// broker had no way to know, so it routed there anyway. Measured on a
    /// ten-node mesh: four workers on 3.13.9, the rest on 3.12.3, 13 of 19
    /// requests failing with nothing wrong on either side.
    ///
    /// `None` from a worker too old to report it -- which is a real answer,
    /// not a missing one, and must not be read as "compatible".
    #[serde(default)]
    pub python_version: Option<String>,
    /// CPython, PyPy, ... Bytecode portability is an implementation concern as
    /// much as a version one.
    #[serde(default)]
    pub python_implementation: Option<String>,
}

/// The identifier a worker is known by OUTSIDE this broker.
///
/// A worker has two, and they are not interchangeable:
///
/// - `Worker.id` is a UUID `WorkerRegistry::register` mints fresh on every
///   registration. It is the registry's private key — for quota reservations,
///   in-flight counts and instance affinity — and it means nothing to anyone
///   else. It also changes every time the worker re-registers.
/// - `Worker.name` is what `sync_workers_via_api` registers with the hub and
///   what a peer's `/workers` advertises. It is stable, and it is the only one
///   another machine can resolve.
///
/// Publishing the first where the second was meant left 43% of one broker's
/// jobs unattributable (#272), and the identical mistake was live on the
/// payout RPC afterwards (#283). This is a newtype so that passing the wrong
/// field is a compile error rather than a value nobody can trace.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WorkerName<'a>(&'a str);

impl<'a> WorkerName<'a> {
    /// The name this broker holds the worker under. For a peer-synced worker
    /// this is the name its OWN broker advertised, which is what that broker's
    /// hub knows it by — so it is the right thing to send back for payment.
    pub fn of(worker: &'a Worker) -> Self {
        Self(&worker.name)
    }

    /// A name an executor reported back on a task result, already a name.
    pub fn reported(name: &'a str) -> Self {
        Self(name)
    }

    /// No worker is involved — e.g. a card purchase.
    pub fn none() -> Self {
        Self("")
    }

    pub fn as_str(&self) -> &'a str {
        self.0
    }
}

impl std::fmt::Display for WorkerName<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0)
    }
}

/// Worker information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Worker {
    /// Unique worker ID
    pub id: String,
    /// Worker name/label
    pub name: String,
    /// Worker endpoint URI
    pub uri: String,
    /// Worker type (ray, dask, spark, zakuro)
    pub worker_type: String,
    /// Current status
    pub status: WorkerStatus,
    /// Available resources
    pub resources: WorkerResources,
    /// Pricing information
    pub pricing: WorkerPricing,
    /// Last heartbeat timestamp
    pub last_heartbeat: DateTime<Utc>,
    /// Number of active requests
    pub active_requests: u32,
    /// Total requests processed
    pub total_requests: u64,
    /// Average request duration in milliseconds
    pub avg_latency_ms: f64,
    /// What this worker has been like, as additive sufficient statistics.
    /// Serialisation skips it: it is the broker's own estimate, not part of
    /// the worker's advertised identity, and `/workers` is a public surface.
    #[serde(skip)]
    pub stats: crate::broker::estimator::Stats,
    /// Requests handed to this worker before it had completed any, whose
    /// replies are not yet in. Their timings are left out of `stats`: the
    /// first one pays the worker's start-up (a fresh Python worker importing
    /// what the payload needs took ~1 s on staging, against ~4 ms warm), and
    /// the rest queued behind it. One such reply used to park an identical
    /// worker far below its siblings for good, because a worker the policy
    /// stops choosing never gets a new observation (#438).
    #[serde(skip)]
    pub warmup_pending: u32,
    /// Tags for filtering
    pub tags: Vec<String>,
    /// Maximum timeout this worker allows per request (seconds), 0 = unlimited
    #[serde(default)]
    pub max_timeout_secs: f64,
    /// Hardware details (GPU model, CPU model, etc.)
    #[serde(default)]
    pub hardware: HardwareInfo,
    /// WireGuard IP extracted from worker's URI
    #[serde(default)]
    pub wireguard_ip: Option<String>,
    /// Whether worker is running inside a Docker container
    #[serde(default)]
    pub is_docker: Option<bool>,
    /// Node that owns this worker (its broker's node_name), for peer workers.
    /// None for a locally-registered worker (it belongs to this node).
    #[serde(default)]
    pub source_node: Option<String>,
    /// True when the operator declared this address as one of THIS broker's own
    /// workers via ZAKURO_WORKERS. Needed when the worker is not reachable on
    /// loopback -- e.g. a broker in a WireGuard sidecar's network namespace
    /// reaching its own worker through the container gateway (172.17.0.1).
    #[serde(default)]
    pub explicit_local: bool,
    /// Node fingerprint this worker was registered under, for key-derived URIs.
    #[serde(default)]
    pub node_fp: String,
    /// Stable discriminator within a node (e.g. listen port), for key-derived URIs.
    #[serde(default)]
    pub slot: String,
    /// Whether this worker serves a fixed model catalog or any model.
    #[serde(default)]
    pub provider_type: ProviderType,
    /// Model uuids this worker serves (or `["*"]` for a general provider).
    #[serde(default)]
    pub served_models: Vec<String>,
    /// Price per 1,000,000 tokens (model-inference billing), in yen.
    #[serde(default)]
    pub price_per_mtok: f64,
    /// This worker's own price (from `/info` or the default) from before the
    /// hub first overrode it. `sync-workers` keeps reporting this, and the hub
    /// stores it as `reported_price_per_hour`. None until the hub sets a price.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reported_price_per_hour: Option<f64>,
}

impl Worker {
    /// Opaque, IP-free, key-derived handle for this worker: `zc://worker-{node_fp}-{slot}`.
    pub fn zc_uri(&self) -> String {
        format!("zc://worker-{}-{}", self.node_fp, self.slot)
    }

    /// Create a new worker
    pub fn new(id: String, name: String, uri: String, worker_type: String) -> Self {
        Self {
            stats: crate::broker::estimator::Stats::new(),
            warmup_pending: 0,
            id,
            name,
            uri,
            worker_type,
            status: WorkerStatus::Healthy,
            resources: WorkerResources::default(),
            pricing: WorkerPricing::default(),
            last_heartbeat: Utc::now(),
            active_requests: 0,
            total_requests: 0,
            avg_latency_ms: 0.0,
            tags: Vec::new(),
            max_timeout_secs: 0.0, // 0 = unlimited
            hardware: HardwareInfo::default(),
            wireguard_ip: None,
            is_docker: None,
            source_node: None,
            explicit_local: false,
            node_fp: String::new(),
            slot: String::new(),
            provider_type: ProviderType::default(),
            served_models: Vec::new(),
            price_per_mtok: 0.0,
            reported_price_per_hour: None,
        }
    }

    /// Check if worker can handle the requested resources
    pub fn can_handle(&self, cpus: f64, memory_bytes: u64, gpus: u32) -> bool {
        self.status == WorkerStatus::Healthy
            && self.resources.cpus_available >= cpus
            && self.resources.memory_available >= memory_bytes
            && self.resources.gpus_available >= gpus
    }

    /// Update heartbeat timestamp
    pub fn heartbeat(&mut self) {
        self.last_heartbeat = Utc::now();
    }

    /// Check if worker is stale (no heartbeat within timeout)
    pub fn is_stale(&self, timeout_secs: i64) -> bool {
        let elapsed = Utc::now().signed_duration_since(self.last_heartbeat);
        elapsed.num_seconds() > timeout_secs
    }
}

/// Worker registration request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerRegistration {
    pub name: String,
    pub uri: String,
    pub worker_type: String,
    #[serde(default)]
    pub resources: WorkerResources,
    #[serde(default)]
    pub pricing: WorkerPricing,
    #[serde(default)]
    pub tags: Vec<String>,
    /// Maximum timeout this worker allows per request (seconds), 0 = unlimited
    #[serde(default)]
    pub max_timeout_secs: f64,
    /// Hardware details from the worker
    #[serde(default)]
    pub hardware: HardwareInfo,
    /// WireGuard IP (optional, extracted from URI if not provided)
    #[serde(default)]
    pub wireguard_ip: Option<String>,
    /// Whether worker is running inside a Docker container
    #[serde(default)]
    pub is_docker: Option<bool>,
    /// Owning node (for peer workers); None for a local registration.
    #[serde(default)]
    pub source_node: Option<String>,
    /// Declared as this broker's own worker via ZAKURO_WORKERS (see Worker).
    #[serde(default)]
    pub explicit_local: bool,
    /// Whether this worker serves a fixed model catalog or any model.
    #[serde(default)]
    pub provider_type: ProviderType,
    /// Model uuids this worker serves (or `["*"]` for a general provider).
    #[serde(default)]
    pub served_models: Vec<String>,
    /// Price per 1,000,000 tokens (model-inference billing), in yen.
    #[serde(default)]
    pub price_per_mtok: f64,
}

/// Build a `WorkerRegistration` with neutral defaults for tests, varying only
/// name, uri and price. Shared across broker test modules so each doesn't
/// hand-roll its own literal.
#[cfg(test)]
pub(crate) fn test_registration(name: &str, uri: String, price: f64) -> WorkerRegistration {
    WorkerRegistration {
        name: name.to_string(),
        uri,
        worker_type: "zakuro".to_string(),
        resources: WorkerResources::default(),
        pricing: WorkerPricing {
            price_per_hour: price,
            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: ProviderType::Specialized,
        served_models: vec![],
        price_per_mtok: 0.0,
    }
}

/// Worker heartbeat request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerHeartbeat {
    pub worker_id: String,
    #[serde(default)]
    pub resources: Option<WorkerResources>,
    #[serde(default)]
    pub active_requests: Option<u32>,
    #[serde(default)]
    pub status: Option<WorkerStatus>,
    #[serde(default)]
    pub max_timeout_secs: Option<f64>,
}

/// Thread-safe worker registry
/// How fast a worker's posterior forgets. At 0.98 an observation still
/// carries about a third of its weight fifty requests later, so the estimate
/// tracks a mesh that changes without thrashing on a single slow response.
const STATS_DECAY: f64 = 0.98;

/// How long a departed worker's posterior stays parked, in seconds.
///
/// The decay below is the real regulator; this is the backstop against the
/// other failure, which is not stale evidence but *substitution* -- the box
/// behind an address being replaced rather than restarted. Ten minutes is
/// where the decay has already settled the question: `0.98^600` is about
/// 5.4e-6, so even a worker carrying a hundred thousand observations returns
/// below the single observation [`crate::broker::policy::sample_service_ms`]
/// needs before it prefers a measured posterior to the class prior. Past that
/// the entry can only cost something -- it widens the window in which a
/// replaced machine inherits its predecessor's reputation -- and can no
/// longer buy anything.
const POSTERIOR_TTL_SECS: i64 = 600;

/// How many departed workers' posteriors a broker keeps at once.
///
/// Unbounded, this grows with every address the broker has ever seen: a mesh
/// where workers churn would leak a `Stats` per address forever, and the one
/// thing this cache must not do is turn a flapping fleet into a memory leak.
/// 4096 entries is well under a megabyte all told -- an order of magnitude
/// less than the live `Worker` records for a fleet that size -- and is far
/// more than a single broker's cell can shed inside one TTL window.
const MAX_PARKED_POSTERIORS: usize = 4096;

/// What one worker's posterior looks like while the worker is gone.
#[derive(Debug, Clone, Copy)]
struct ParkedPosterior {
    stats: crate::broker::estimator::Stats,
    /// When the worker was last known alive -- its last heartbeat, NOT the
    /// moment the stale sweeper happened to notice. The evidence is as old as
    /// the worker's silence either way, and keying on the sweep would make how
    /// much a posterior decays depend on `health_check_interval`, a knob about
    /// polling frequency and not about how fast evidence ages.
    last_seen: DateTime<Utc>,
}

/// Posteriors of workers that have left, kept for a bounded while.
///
/// A worker that flaps -- drops out and comes back -- used to be relearned
/// from nothing: `remove`/`remove_stale` dropped the whole `Worker`, and
/// `Worker::new` starts at `Stats::new()`, so a node that left for ninety
/// seconds returned as a stranger and the router had to re-explore it from
/// the class prior. This parks the posterior instead (#270).
///
/// Every method takes `now` rather than reading the clock, so the TTL and the
/// decay are tested on an injected timeline instead of with sleeps.
#[derive(Debug, Default)]
pub(crate) struct PosteriorCache {
    parked: DashMap<String, ParkedPosterior>,
}

/// How much of a parked posterior survives a gap of `elapsed_secs`.
///
/// One knob, not two. [`STATS_DECAY`] is applied once per completed request;
/// here it is applied once per second of absence. Equating the two keeps a
/// single forgetting rate for a worker whether it is answering slowly or not
/// answering at all, and it puts the half-life of an absent posterior at
/// `ln(0.5)/ln(0.98)` ≈ 34 s -- just under the 60 s of silence the broker
/// already sits through before it removes a worker at all (`worker_timeout`
/// is 30 s and the sweeper removes at 2x). So a worker that flaps for half a
/// minute past that comes back with roughly a quarter of its confidence and
/// all of its shape, and one gone for five minutes comes back with its median
/// and almost no weight -- which is precisely what puts it back into
/// exploration rather than straight back into rotation.
fn posterior_gap_decay(elapsed_secs: f64) -> f64 {
    STATS_DECAY.powf(elapsed_secs.max(0.0))
}

/// The identity a posterior is parked under.
///
/// Not the worker `id`: that is a fresh uuid on every registration, which is
/// the whole reason #282 exists. Not `zc_uri()` either, tempting as it is --
/// `node_fp` is stamped by `set_node_fp` *after* `register` returns, so at the
/// moment a re-registering worker needs its posterior back the uri still reads
/// `zc://worker--{slot}` and every local worker on every node would collide on
/// one key.
///
/// What does survive a re-register is the pair discovery already dedups on:
/// the owning node and the endpoint. `uri` is the local path's "already
/// registered" check (re-probing the same host:port), and `(source node, uri)`
/// is what `is_same_peer_worker` matches for a peer-synced one. Name is
/// deliberately not part of it: on a fleet where every host is called `lxd`
/// every worker is `worker-lxd`, and discovery gave up name-based dedup for
/// exactly that reason -- handing one machine's history to another is worse
/// than starting blank.
///
/// `source_node` is in the key rather than ignored because a posterior records
/// a whole round trip, so it is only evidence about the path it was measured
/// over. The same box reached through a peer broker is a different path and
/// must not inherit the local measurement.
fn posterior_key(source_node: Option<&str>, uri: &str) -> String {
    let node = source_node
        .map(|sn| sn.strip_prefix("node-").unwrap_or(sn))
        .unwrap_or("");
    format!("{node}|{uri}")
}

impl PosteriorCache {
    pub(crate) fn new() -> Self {
        Self {
            parked: DashMap::new(),
        }
    }

    /// Keep `stats` for a worker last seen at `last_seen`.
    ///
    /// A posterior with nothing in it is not parked: it would spend an entry
    /// to remember nothing, and on a broker whose workers churn before they
    /// are ever used that is the common case.
    fn park(
        &self,
        key: String,
        stats: crate::broker::estimator::Stats,
        last_seen: DateTime<Utc>,
        now: DateTime<Utc>,
    ) {
        if stats == crate::broker::estimator::Stats::new() {
            return;
        }
        if self.parked.len() >= MAX_PARKED_POSTERIORS {
            self.evict(now);
        }
        self.parked
            .insert(key, ParkedPosterior { stats, last_seen });
    }

    /// Hand back the posterior for `key`, aged by how long the worker has been
    /// away, or `None` if there is none or it is past the TTL. The entry is
    /// consumed: a worker gets its own posterior back once, and a second
    /// registration at the same address starts from what it then measures.
    fn take(&self, key: &str, now: DateTime<Utc>) -> Option<crate::broker::estimator::Stats> {
        let (_, entry) = self.parked.remove(key)?;
        let elapsed = now.signed_duration_since(entry.last_seen);
        if elapsed.num_seconds() > POSTERIOR_TTL_SECS {
            return None;
        }
        let mut stats = entry.stats;
        stats.decay(posterior_gap_decay(
            elapsed.num_milliseconds() as f64 / 1000.0,
        ));
        Some(stats)
    }

    /// Drop any posterior parked for `key` without handing it back.
    fn forget(&self, key: &str) {
        self.parked.remove(key);
    }

    /// Make room: expired entries first, then the worker seen longest ago --
    /// which is also the one the decay has already reduced the most, so it is
    /// the entry whose loss costs least.
    fn evict(&self, now: DateTime<Utc>) {
        self.parked.retain(|_, e| {
            now.signed_duration_since(e.last_seen).num_seconds() <= POSTERIOR_TTL_SECS
        });
        while self.parked.len() >= MAX_PARKED_POSTERIORS {
            let Some(oldest) = self
                .parked
                .iter()
                .min_by_key(|e| e.value().last_seen)
                .map(|e| e.key().clone())
            else {
                return;
            };
            self.parked.remove(&oldest);
        }
    }

    fn len(&self) -> usize {
        self.parked.len()
    }
}

#[derive(Debug)]
pub struct WorkerRegistry {
    workers: DashMap<String, Worker>,
    /// Per-worker request timestamps for time-windowed counts.
    /// Each entry is a ring-buffer of UTC timestamps; entries older than
    /// 30 days are pruned on every write.
    request_history: DashMap<String, Mutex<VecDeque<DateTime<Utc>>>>,
    /// Per-worker quotas (max requests per time window)
    quotas: DashMap<String, WorkerQuotas>,
    /// Model uuid -> worker ids of SPECIALIZED workers serving that model.
    model_index: DashMap<String, HashSet<String>>,
    /// Worker ids of GENERAL providers (serve any model uuid).
    general_workers: DashMap<String, ()>,
    /// Hub-set effective prices, by worker NAME (stable across re-registration,
    /// unlike the per-registration `id`), so a worker's own restart/re-probe
    /// doesn't forget the hub's price for it (spec §6.6). Applied both when
    /// `apply_hub_prices` runs and when `register` builds a fresh `Worker` for
    /// a name this map already knows about.
    hub_prices: DashMap<String, f64>,
    /// Posteriors of workers that have left, so a flapping node is not
    /// relearned from nothing every time it comes back (#270). Keyed by
    /// [`posterior_key`], bounded by [`MAX_PARKED_POSTERIORS`], and aged on
    /// the way back out by [`posterior_gap_decay`].
    posteriors: PosteriorCache,
}

impl WorkerRegistry {
    /// Create a new empty registry
    pub fn new() -> Self {
        Self {
            workers: DashMap::new(),
            request_history: DashMap::new(),
            quotas: DashMap::new(),
            model_index: DashMap::new(),
            general_workers: DashMap::new(),
            hub_prices: DashMap::new(),
            posteriors: PosteriorCache::new(),
        }
    }

    /// Insert `worker` into the model index according to its `provider_type`/`served_models`.
    fn index_worker(&self, worker: &Worker) {
        match worker.provider_type {
            ProviderType::General => {
                self.general_workers.insert(worker.id.clone(), ());
            }
            ProviderType::Specialized => {
                for model_uuid in &worker.served_models {
                    if model_uuid == MODEL_WILDCARD {
                        // Specialized worker with a wildcard entry behaves like a general one.
                        self.general_workers.insert(worker.id.clone(), ());
                        continue;
                    }
                    self.model_index
                        .entry(model_uuid.clone())
                        .or_default()
                        .insert(worker.id.clone());
                }
            }
        }
    }

    /// Remove `worker_id` from every model-index entry and the general-worker set.
    fn deindex_worker(&self, worker_id: &str) {
        self.general_workers.remove(worker_id);
        self.model_index.retain(|_, ids| {
            ids.remove(worker_id);
            !ids.is_empty()
        });
    }

    /// Workers that can serve `model_uuid`: SPECIALIZED workers whose `served_models`
    /// contains it, UNION all GENERAL providers. Resolution/ordering among the
    /// candidates is left to the caller.
    pub fn workers_serving(&self, model_uuid: &str) -> Vec<Worker> {
        let mut ids: HashSet<String> = self
            .model_index
            .get(model_uuid)
            .map(|entry| entry.clone())
            .unwrap_or_default();
        for entry in self.general_workers.iter() {
            ids.insert(entry.key().clone());
        }
        ids.into_iter().filter_map(|id| self.get(&id)).collect()
    }

    /// Register a new worker
    pub fn register(&self, registration: WorkerRegistration) -> Worker {
        self.register_at(registration, Utc::now())
    }

    /// `register`, with the clock passed in so the posterior TTL can be tested
    /// on a timeline rather than with sleeps. Production always passes
    /// `Utc::now()`.
    pub(crate) fn register_at(
        &self,
        registration: WorkerRegistration,
        now: DateTime<Utc>,
    ) -> Worker {
        let id = uuid::Uuid::new_v4().to_string();

        // Extract IP from URI if wireguard_ip not explicitly provided.
        // If the extracted IP is loopback (127.x or ::1), fall back to
        // the auto-detected WireGuard IP so Docker nodes show their real IP.
        let wireguard_ip = registration.wireguard_ip.clone().or_else(|| {
            let uri_ip = registration
                .uri
                .strip_prefix("http://")
                .or_else(|| registration.uri.strip_prefix("https://"))
                .and_then(|rest| {
                    let host = rest.split('/').next().unwrap_or(rest);
                    let ip = host.split(':').next().unwrap_or(host);
                    if ip.is_empty() {
                        None
                    } else {
                        Some(ip.to_string())
                    }
                });
            match uri_ip.as_deref() {
                Some("127.0.0.1") | Some("::1") | Some("localhost") => {
                    super::discovery::get_mesh_ip().or(uri_ip)
                }
                _ => uri_ip,
            }
        });

        let mut worker = Worker::new(
            id.clone(),
            registration.name,
            registration.uri,
            registration.worker_type,
        );
        worker.resources = registration.resources;
        worker.pricing = registration.pricing;
        worker.tags = registration.tags;
        worker.max_timeout_secs = registration.max_timeout_secs;
        worker.hardware = registration.hardware;
        worker.wireguard_ip = wireguard_ip;
        // Auto-detect is_docker from broker environment if not explicitly provided by worker:
        // if /.dockerenv exists the broker itself is running in Docker, so its workers are too.
        worker.is_docker = registration
            .is_docker
            .or_else(|| Some(std::path::Path::new("/.dockerenv").exists()));
        worker.source_node = registration.source_node;
        // A registration that names an owning node IS that node's worker, and
        // `node_fp` is the field every settlement site reads to decide whose
        // machine ran a job. Carrying the identity in `source_node` and
        // leaving `node_fp` empty makes a peer's worker indistinguishable from
        // our own: `ran_on_our_hardware` falls back to the address, which on
        // loopback — or on any broker in local mode — says "ours", and the
        // peer is never paid (#297).
        //
        // `discovery` has always called `set_node_fp` immediately after
        // registering, which is the same fact written at one call site
        // instead of where it belongs. Doing it here means every path that
        // registers a peer worker gets it, not just the one that remembered.
        if worker.node_fp.is_empty() {
            if let Some(fp) = worker
                .source_node
                .as_deref()
                .map(super::node_identity::strip_node_arg)
                .filter(|fp| !fp.is_empty())
            {
                worker.node_fp = fp.to_string();
            }
        }
        worker.explicit_local = registration.explicit_local;
        worker.provider_type = registration.provider_type;
        worker.served_models = registration.served_models;
        worker.price_per_mtok = registration.price_per_mtok;
        // Stable discriminator within a node for key-derived worker uris:
        // the worker's listen port, extracted from its uri.
        worker.slot = worker
            .uri
            .strip_prefix("http://")
            .or_else(|| worker.uri.strip_prefix("https://"))
            .and_then(|rest| rest.split('/').next())
            .and_then(|host| host.rsplit(':').next())
            .unwrap_or_default()
            .to_string();

        // A hub price previously applied for THIS name survives re-registration
        // (a worker restart re-probes and rebuilds `pricing` from scratch).
        // Peer workers are never repriced by this broker's own hub_prices map.
        if worker.source_node.is_none() {
            if let Some(hub_price) = self.hub_prices.get(&worker.name).map(|p| *p) {
                worker.reported_price_per_hour = Some(worker.pricing.price_per_hour);
                worker.pricing.price_per_hour = hub_price;
            }
        }

        // A posterior parked when this address last went stale comes back with
        // the worker, aged by how long it was away. This is a better warmup
        // than any class prior -- it is the worker's own measurements, not an
        // assumption about its kind -- so it is applied last and wins over the
        // `Stats::new()` `Worker::new` started from.
        if let Some(stats) = self.posteriors.take(
            &posterior_key(worker.source_node.as_deref(), &worker.uri),
            now,
        ) {
            worker.stats = stats;
        }

        self.workers.insert(id.clone(), worker.clone());
        // Initialise time-series and quota buckets for the new worker
        self.request_history
            .insert(id.clone(), Mutex::new(VecDeque::new()));
        self.quotas.insert(id.clone(), WorkerQuotas::default());
        self.index_worker(&worker);
        worker
    }

    /// Set the owning node's fingerprint on a registered worker (key-derived uri
    /// identity). Called at local worker registration with this broker's own
    /// `NodeKey::fingerprint()`.
    pub fn set_node_fp(&self, worker_id: &str, node_fp: &str) -> Option<Worker> {
        self.workers.get_mut(worker_id).map(|mut w| {
            w.node_fp = node_fp.to_string();
            w.clone()
        })
    }

    /// Return the number of requests completed by a worker in the last `window` duration.
    pub fn requests_in_window(&self, worker_id: &str, window: Duration) -> u64 {
        let cutoff = Utc::now() - window;
        self.request_history
            .get(worker_id)
            .map(|entry| {
                let ring = entry.lock().unwrap();
                ring.iter().filter(|&&ts| ts >= cutoff).count() as u64
            })
            .unwrap_or(0)
    }

    /// Return the quota limits configured for a worker.
    pub fn get_quotas(&self, worker_id: &str) -> WorkerQuotas {
        self.quotas
            .get(worker_id)
            .map(|q| q.clone())
            .unwrap_or_default()
    }

    /// Update worker from heartbeat
    pub fn heartbeat(&self, heartbeat: WorkerHeartbeat) -> Option<Worker> {
        self.workers.get_mut(&heartbeat.worker_id).map(|mut w| {
            w.heartbeat();
            if let Some(resources) = heartbeat.resources {
                w.resources = resources;
            }
            if let Some(active) = heartbeat.active_requests {
                w.active_requests = active;
            }
            if let Some(status) = heartbeat.status {
                // A worker's own heartbeat must never undo a drain its owner
                // asked for: that would route new jobs to a worker being stopped.
                if w.status != WorkerStatus::Draining {
                    w.status = status;
                }
            }
            if let Some(max_timeout) = heartbeat.max_timeout_secs {
                w.max_timeout_secs = max_timeout;
            }
            w.clone()
        })
    }

    /// Refresh heartbeat for a worker by ID (used by discovery to keep workers alive)
    pub fn refresh_heartbeat(&self, id: &str) {
        if let Some(mut w) = self.workers.get_mut(id) {
            w.heartbeat();
            // Also mark as healthy if it was marked unhealthy due to timeout
            if w.status == WorkerStatus::Unhealthy {
                w.status = WorkerStatus::Healthy;
            }
        }
    }

    /// Update live resources and storage for an existing worker (called on each discovery scan).
    /// Refreshes heartbeat, updates all resource fields, and updates storage_gb (dynamic value).
    /// Static hardware fields (cpu_model, gpu_model, gpu_vram_gb) are left unchanged.
    pub fn update_resources(&self, id: &str, resources: WorkerResources, hardware: HardwareInfo) {
        if let Some(mut w) = self.workers.get_mut(id) {
            w.heartbeat();
            w.resources = resources;
            // storage_gb is dynamic (free disk space); update it on each probe
            if hardware.storage_gb.is_some() {
                w.hardware.storage_gb = hardware.storage_gb;
            }
            if w.status == WorkerStatus::Unhealthy {
                w.status = WorkerStatus::Healthy;
            }
        }
    }

    /// Get a worker by ID
    pub fn get(&self, id: &str) -> Option<Worker> {
        self.workers.get(id).map(|w| w.clone())
    }

    /// Remove a worker, deliberately.
    ///
    /// This is the `DELETE /workers/{id}` path: an operator saying the worker
    /// is gone on purpose, which is a different statement from the sweeper
    /// guessing that it is (see [`remove_stale`](Self::remove_stale)). Only
    /// the guess is worth reversing later, so a deliberate delete also drops
    /// any parked posterior for that address -- delete-and-re-add is the one
    /// move an operator has for "forget what you think you know about this
    /// address", and it would be useless if the history came back with it.
    pub fn remove(&self, id: &str) -> Option<Worker> {
        self.deindex_worker(id);
        let removed = self.workers.remove(id).map(|(_, w)| w);
        if let Some(w) = &removed {
            self.posteriors
                .forget(&posterior_key(w.source_node.as_deref(), &w.uri));
        }
        removed
    }

    /// List all workers
    pub fn list(&self) -> Vec<Worker> {
        self.workers.iter().map(|w| w.clone()).collect()
    }

    /// Aggregate free-resource snapshot summed over all currently healthy workers.
    /// Uses saturating adds so pathological worker resource values can't overflow.
    pub fn aggregate_available(&self) -> BrokerResources {
        self.healthy()
            .into_iter()
            .fold(BrokerResources::default(), |mut acc, w| {
                let cpus = w.resources.cpus_available.max(0.0) as u64;
                acc.cpus_available = acc.cpus_available.saturating_add(cpus);
                acc.memory_available = acc
                    .memory_available
                    .saturating_add(w.resources.memory_available);
                acc.gpus_available = acc
                    .gpus_available
                    .saturating_add(w.resources.gpus_available);
                acc.healthy_workers = acc.healthy_workers.saturating_add(1);
                acc
            })
    }

    /// List healthy workers
    pub fn healthy(&self) -> Vec<Worker> {
        self.workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Healthy)
            .map(|w| w.clone())
            .collect()
    }

    /// IDs of healthy workers — a cheap alternative to `healthy()` for the
    /// routing hot path, which only needs to clone the *selected* worker, not
    /// every candidate. Avoids N full `Worker` deep-clones per request.
    pub fn healthy_ids(&self) -> Vec<String> {
        self.workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Healthy)
            .map(|w| w.key().clone())
            .collect()
    }

    /// Find workers that can handle the request. `min_vram_gb` is an
    /// additional filter on advertised GPU VRAM (zc#345); a worker that
    /// advertises none is excluded once a minimum is set.
    pub fn find_capable(
        &self,
        cpus: f64,
        memory_bytes: u64,
        gpus: u32,
        min_vram_gb: Option<u32>,
    ) -> Vec<Worker> {
        self.workers
            .iter()
            .filter(|w| {
                w.can_handle(cpus, memory_bytes, gpus)
                    && min_vram_gb
                        .is_none_or(|min| w.hardware.gpu_vram_gb.is_some_and(|v| v >= min))
            })
            .map(|w| w.clone())
            .collect()
    }

    /// Mark stale workers as unhealthy
    pub fn mark_stale(&self, timeout_secs: i64) {
        for mut entry in self.workers.iter_mut() {
            if entry.is_stale(timeout_secs) && entry.status == WorkerStatus::Healthy {
                entry.status = WorkerStatus::Unhealthy;
            }
        }
    }

    /// Remove workers that have been stale (unhealthy) for longer than `timeout_secs`.
    /// Returns the IDs of removed workers.
    ///
    /// This is the broker *guessing* a worker is gone -- it has heard nothing
    /// for 2x `worker_timeout`, which a restart, a network blip or a reboot
    /// all produce. A worker that comes back from any of those is the same
    /// machine, so its posterior is parked on the way out rather than dropped
    /// with the rest of the record, and [`register_at`](Self::register_at)
    /// hands it back if the address reappears inside the TTL (#270).
    pub fn remove_stale(&self, timeout_secs: i64) -> Vec<String> {
        let now = Utc::now();
        let to_remove: Vec<String> = self
            .workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Unhealthy && w.is_stale(timeout_secs))
            .map(|w| w.id.clone())
            .collect();
        for id in &to_remove {
            self.deindex_worker(id);
            if let Some((_, w)) = self.workers.remove(id) {
                self.posteriors.park(
                    posterior_key(w.source_node.as_deref(), &w.uri),
                    w.stats,
                    w.last_heartbeat,
                    now,
                );
            }
            self.request_history.remove(id);
            self.quotas.remove(id);
        }
        to_remove
    }

    /// Atomically reserve one quota slot for the given worker.
    ///
    /// Checks all configured quota windows under the ring-buffer mutex, then
    /// pre-commits by pushing the current timestamp if every window has room.
    /// Returns `true` if the slot was reserved; `false` if any quota is full.
    ///
    /// On success the caller MUST eventually call either `record_request`
    /// (keeps the pre-committed slot) or `cancel_quota_reservation` (removes it).
    pub fn try_reserve_quota(&self, worker_id: &str) -> bool {
        let quotas = self.get_quotas(worker_id);
        let all_unlimited = quotas.per_5h == 0 && quotas.per_week == 0 && quotas.per_month == 0;

        match self.request_history.get(worker_id) {
            None => true, // new worker with no history — allow
            Some(entry) => {
                let mut ring = entry.lock().unwrap();
                let now = Utc::now();

                if !all_unlimited {
                    if quotas.per_5h > 0 {
                        let cutoff = now - Duration::hours(5);
                        let count = ring.iter().filter(|&&ts| ts >= cutoff).count() as u64;
                        if count >= quotas.per_5h {
                            return false;
                        }
                    }
                    if quotas.per_week > 0 {
                        let cutoff = now - Duration::weeks(1);
                        let count = ring.iter().filter(|&&ts| ts >= cutoff).count() as u64;
                        if count >= quotas.per_week {
                            return false;
                        }
                    }
                    if quotas.per_month > 0 {
                        let cutoff = now - Duration::days(30);
                        let count = ring.iter().filter(|&&ts| ts >= cutoff).count() as u64;
                        if count >= quotas.per_month {
                            return false;
                        }
                    }
                }

                // All checks passed — pre-commit the slot
                ring.push_back(now);
                // Prune entries older than 30 days while the mutex is held
                let prune_cutoff = now - Duration::days(30);
                while ring.front().map(|&ts| ts < prune_cutoff).unwrap_or(false) {
                    ring.pop_front();
                }
                true
            }
        }
    }

    /// Cancel a previously reserved quota slot (call on request failure).
    /// Removes the last pre-committed timestamp from the worker's ring buffer.
    pub fn cancel_quota_reservation(&self, worker_id: &str) {
        if let Some(entry) = self.request_history.get(worker_id) {
            let mut ring = entry.lock().unwrap();
            ring.pop_back();
        }
    }

    /// Update worker stats after request completion.
    ///
    /// NOTE: does NOT push a timestamp to the ring buffer — that was already
    /// done atomically by `try_reserve_quota` at dispatch time.
    pub fn record_request(&self, worker_id: &str, duration_ms: f64, _success: bool) {
        if let Some(mut worker) = self.workers.get_mut(worker_id) {
            worker.total_requests += 1;
            // Exponential moving average for latency
            let alpha = 0.1;
            worker.avg_latency_ms = alpha * duration_ms + (1.0 - alpha) * worker.avg_latency_ms;
            // The same observation, into the posterior the adaptive policy
            // reads. Decay first, so the estimate follows recent behaviour
            // rather than averaging over the worker's whole history. A reply
            // to a request sent while the worker was still warming up counts
            // for success, not for timing (see `Worker::warmup_pending`).
            if worker.warmup_pending > 0 {
                worker.warmup_pending -= 1;
                worker.stats.observe_outcome(_success);
            } else {
                worker.stats.decay(STATS_DECAY);
                worker.stats.observe(duration_ms, _success);
            }
            if worker.active_requests > 0 {
                worker.active_requests -= 1;
            }
        }
    }

    /// Record one completed request against the worker with this stable NAME,
    /// without touching the in-flight counter.
    ///
    /// For the peer-dispatch path (`server::dispatch_to_peers`), which knows
    /// the executor only by the name the peer reports and never took an
    /// in-flight slot on it. Without this, a job sent to a peer taught the
    /// router nothing: `total_requests` stayed 0, so `best_latency` read the
    /// worker as "no measurement yet" forever and the adaptive policy's
    /// posterior stayed empty. On a mesh, where most jobs leave the node, that
    /// is nearly every observation thrown away -- every candidate tied at
    /// unmeasured, so the first one won every time and routing never moved.
    ///
    /// Returns whether a worker by that name was found.
    pub fn observe_latency_by_name(&self, name: &str, duration_ms: f64, success: bool) -> bool {
        let Some(id) = self
            .workers
            .iter()
            .find(|e| e.value().name == name)
            .map(|e| e.key().clone())
        else {
            return false;
        };
        let Some(mut worker) = self.workers.get_mut(&id) else {
            return false;
        };
        worker.total_requests += 1;
        let alpha = 0.1;
        worker.avg_latency_ms = alpha * duration_ms + (1.0 - alpha) * worker.avg_latency_ms;
        worker.stats.decay(STATS_DECAY);
        worker.stats.observe(duration_ms, success);
        true
    }

    /// Increment active request count for a worker
    pub fn increment_active(&self, worker_id: &str) {
        if let Some(mut worker) = self.workers.get_mut(worker_id) {
            worker.active_requests += 1;
            // Nothing has come back from it yet: this request either pays its
            // start-up or waits behind the one that does.
            if worker.total_requests == 0 {
                worker.warmup_pending += 1;
            }
        }
    }

    /// A job was just handed to this worker through the Atelier relay: show it
    /// busy now. Its next heartbeat (every 10 s, reporting its own load)
    /// overwrites this, so a job that ends is seen free again without a call.
    pub fn mark_busy(&self, worker_id: &str) {
        if let Some(mut worker) = self.workers.get_mut(worker_id) {
            worker.active_requests = worker.active_requests.max(1);
            worker.resources.gpus_available = 0;
            worker.resources.cpus_available = 0.0;
        }
    }

    /// Decrement a worker's in-flight counter, flooring at 0 (idempotent).
    pub fn decrement_active(&self, worker_id: &str) {
        if let Some(mut worker) = self.workers.get_mut(worker_id) {
            if worker.active_requests > 0 {
                worker.active_requests -= 1;
            }
            // A warm-up request that failed is not coming back to
            // `record_request`; it must not hold a later reply's timing out.
            worker.warmup_pending = worker.warmup_pending.saturating_sub(1);
        }
    }

    /// RAII in-flight counter: increments now, and decrements on drop UNLESS
    /// disarmed. The execute path arms one of these at dispatch so every
    /// early-return/error/timeout path releases the slot; the success path
    /// (where `record_request` already decremented) calls `disarm()` to avoid a
    /// double-decrement. Fixes the active_requests leak that biased
    /// best_availability routing against workers that ever failed (audit M2).
    pub fn active_guard(&self, worker_id: &str) -> ActiveGuard<'_> {
        self.increment_active(worker_id);
        ActiveGuard {
            registry: self,
            worker_id: worker_id.to_string(),
            armed: true,
        }
    }

    /// Get worker count
    pub fn count(&self) -> usize {
        self.workers.len()
    }

    /// Mark a worker as unhealthy. Leaves a `Draining` worker untouched:
    /// otherwise a failed forward to a draining worker would flip it to
    /// `Unhealthy`, and the next discovery scan would lift it back to
    /// `Healthy`, putting a drained worker back in rotation.
    pub fn mark_unhealthy(&self, worker_id: &str) {
        if let Some(mut worker) = self.workers.get_mut(worker_id) {
            if worker.status != WorkerStatus::Draining {
                worker.status = WorkerStatus::Unhealthy;
            }
        }
    }

    /// Stop routing new work to `id` (status `Draining`) so its owner can stop
    /// it without killing a job. Selection only ever picks `Healthy` workers,
    /// and neither discovery refreshes nor heartbeats lift `Draining`.
    /// Returns the updated worker, or None when `id` is unknown.
    pub fn drain(&self, id: &str) -> Option<Worker> {
        self.workers.get_mut(id).map(|mut w| {
            w.status = WorkerStatus::Draining;
            w.clone()
        })
    }

    /// Adopt the hub's effective prices (spec 2026-09-13-macos-widget §6.6) for
    /// THIS broker's own workers, matched by name (the `worker_id` sync sends).
    /// The first override remembers the worker's own price in
    /// `reported_price_per_hour`. Peer workers (`source_node` set) are never
    /// touched. Returns how many workers changed price.
    ///
    /// Every name in `prices` is also remembered in `hub_prices` (regardless of
    /// whether a live worker with that name exists right now), so a worker that
    /// re-registers later -- after a restart, or a fresh discovery probe -- has
    /// the hub's price reapplied by `register` immediately, with no sync round
    /// trip in between (fix round 1, Finding 1).
    pub fn apply_hub_prices(&self, prices: &std::collections::HashMap<String, f64>) -> usize {
        for (name, &price) in prices.iter() {
            self.hub_prices.insert(name.clone(), price);
        }
        let mut changed = 0;
        for mut w in self.workers.iter_mut() {
            if w.source_node.is_some() {
                continue;
            }
            if let Some(&price) = prices.get(&w.name) {
                if w.reported_price_per_hour.is_none() {
                    w.reported_price_per_hour = Some(w.pricing.price_per_hour);
                }
                if w.pricing.price_per_hour != price {
                    w.pricing.price_per_hour = price;
                    changed += 1;
                }
            }
        }
        changed
    }

    /// Resolve the best worker to serve `model_uuid`.
    ///
    /// Candidates come from [`workers_serving`], filtered to the same
    /// HEALTHY criterion the registry already applies elsewhere (`status ==
    /// WorkerStatus::Healthy`, as used by [`healthy`]/[`healthy_ids`]).
    /// Specialized providers pinned to this uuid are preferred over general
    /// providers; within the chosen tier the cheapest `price_per_mtok` wins,
    /// ties broken deterministically by worker `name`.
    pub fn resolve_model(&self, model_uuid: &str) -> Result<Worker, ModelResolveError> {
        let candidates: Vec<Worker> = self
            .workers_serving(model_uuid)
            .into_iter()
            .filter(|w| w.status == WorkerStatus::Healthy)
            .collect();

        let (specialized, general): (Vec<Worker>, Vec<Worker>) = candidates
            .into_iter()
            .partition(|w| w.provider_type == ProviderType::Specialized);

        let pick_cheapest = |mut tier: Vec<Worker>| -> Option<Worker> {
            tier.sort_by(|a, b| {
                a.price_per_mtok
                    .partial_cmp(&b.price_per_mtok)
                    .unwrap_or(std::cmp::Ordering::Equal)
                    .then_with(|| a.name.cmp(&b.name))
            });
            tier.into_iter().next()
        };

        if !specialized.is_empty() {
            return Ok(pick_cheapest(specialized).expect("non-empty specialized tier"));
        }
        if !general.is_empty() {
            return Ok(pick_cheapest(general).expect("non-empty general tier"));
        }
        Err(ModelResolveError::NoProvider {
            model_uuid: model_uuid.to_string(),
        })
    }
}

/// Errors from [`WorkerRegistry::resolve_model`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModelResolveError {
    /// No healthy worker (specialized or general) serves this model uuid.
    NoProvider { model_uuid: String },
}

impl std::fmt::Display for ModelResolveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoProvider { model_uuid } => {
                write!(f, "no provider serving zc://{}", model_uuid)
            }
        }
    }
}

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

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

/// RAII guard returned by [`WorkerRegistry::active_guard`]. Decrements the
/// worker's in-flight counter on drop unless [`ActiveGuard::disarm`] was called.
pub struct ActiveGuard<'a> {
    registry: &'a WorkerRegistry,
    worker_id: String,
    armed: bool,
}

impl<'a> ActiveGuard<'a> {
    /// Disarm so `Drop` will NOT decrement — call on the success path where
    /// `record_request` has already released the slot.
    pub fn disarm(&mut self) {
        self.armed = false;
    }
}

impl<'a> Drop for ActiveGuard<'a> {
    fn drop(&mut self) {
        if self.armed {
            self.registry.decrement_active(&self.worker_id);
        }
    }
}

/// Identity carried into registration has to reach the field that decides
/// money, or a peer's machine works for nothing.
#[cfg(test)]
mod peer_worker_identity_tests {
    /// A runner registers its RAM (zak-forge `ram_gb`, L'Atelier plan Task 8) and `/route` hands it back in
    /// each candidate's hardware: the hub sizes a CPU runner (gpu_vram_gb 0) by RAM.
    #[test]
    fn hardware_carries_ram_gb_through_serde() {
        let hw: HardwareInfo =
            serde_json::from_str(r#"{"gpu_vram_gb": 0, "ram_gb": 31.3, "cpu_model": "x"}"#)
                .unwrap();
        assert_eq!(hw.ram_gb, Some(31.3));
        assert_eq!(
            serde_json::to_value(&hw).unwrap()["ram_gb"],
            serde_json::json!(31.3)
        );
        let old: HardwareInfo = serde_json::from_str(r#"{"gpu_vram_gb": 8}"#).unwrap();
        assert_eq!(old.ram_gb, None);
    }

    use super::*;

    fn peer_registration(source_node: &str) -> WorkerRegistration {
        let mut r = test_registration("peer-w0", "http://127.0.0.1:39617".to_string(), 36.0);
        r.source_node = Some(source_node.to_string());
        r
    }

    #[test]
    fn a_registration_that_names_an_owning_node_carries_its_fingerprint() {
        // `node_fp` is what every settlement site reads. Leaving it empty
        // while `source_node` holds the identity made a peer's worker
        // indistinguishable from our own: the charge decision falls back to
        // the address, which on loopback says "ours", and the peer is never
        // paid (#297).
        let registry = WorkerRegistry::new();
        let w = registry.register(peer_registration("zc://node-feedfacedeadbeef"));
        assert_eq!(w.node_fp, "feedfacedeadbeef");
    }

    #[test]
    fn a_bare_fingerprint_is_accepted_too() {
        let registry = WorkerRegistry::new();
        let w = registry.register(peer_registration("feedfacedeadbeef"));
        assert_eq!(w.node_fp, "feedfacedeadbeef");
    }

    #[test]
    fn a_local_registration_claims_no_node() {
        // No `source_node` means this broker's own worker, and its identity
        // is stamped elsewhere — registration must not invent one.
        let registry = WorkerRegistry::new();
        let w = registry.register(test_registration(
            "local-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        assert!(w.node_fp.is_empty());
    }
}

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

    #[test]
    fn worker_zc_uri_and_source_node_default() {
        let mut w = Worker::new(
            "id1".into(),
            "worker-abc123".into(),
            "http://10.13.13.21:3960".into(),
            "zakuro".into(),
        );
        w.node_fp = "abc123".into();
        w.slot = "3960".into();
        assert_eq!(w.zc_uri(), "zc://worker-abc123-3960");
        assert!(w.source_node.is_none());
        w.source_node = Some("node-i9".into());
        assert_eq!(w.source_node.as_deref(), Some("node-i9"));
    }

    #[test]
    fn worker_zc_uri_is_key_derived_and_collision_free() {
        let mut w1 = Worker::new(
            "id1".into(),
            "worker-lxd".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        let mut w2 = Worker::new(
            "id2".into(),
            "worker-lxd".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        w1.node_fp = "aaaaaaaaaaaaaaaa".into();
        w1.slot = "3960".into();
        w2.node_fp = "bbbbbbbbbbbbbbbb".into();
        w2.slot = "3960".into();
        assert_eq!(w1.zc_uri(), "zc://worker-aaaaaaaaaaaaaaaa-3960");
        assert_ne!(w1.zc_uri(), w2.zc_uri()); // same name "worker-lxd", different nodes -> distinct
    }

    fn registration(name: &str, uri: &str) -> WorkerRegistration {
        WorkerRegistration {
            name: name.to_string(),
            uri: uri.to_string(),
            worker_type: "zakuro".to_string(),
            resources: WorkerResources::default(),
            pricing: WorkerPricing::default(),
            tags: vec![],
            max_timeout_secs: 0.0,
            hardware: HardwareInfo::default(),
            wireguard_ip: None,
            is_docker: None,
            source_node: None,
            explicit_local: false,
            provider_type: ProviderType::default(),
            served_models: vec![],
            price_per_mtok: 0.0,
        }
    }

    /// Registration helper with explicit provider_type/served_models, for model-index tests.
    fn model_registration(
        name: &str,
        uri: &str,
        provider_type: ProviderType,
        served_models: Vec<&str>,
    ) -> WorkerRegistration {
        let mut r = registration(name, uri);
        r.provider_type = provider_type;
        r.served_models = served_models.into_iter().map(String::from).collect();
        r
    }

    // --- Model index / workers_serving ---

    #[test]
    fn test_workers_serving_specialized_matches_only_its_model() {
        let reg = WorkerRegistry::new();
        let w = reg.register(model_registration(
            "specialist",
            "http://127.0.0.1:4001",
            ProviderType::Specialized,
            vec!["uuid-a"],
        ));

        let matches = reg.workers_serving("uuid-a");
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].id, w.id);

        let no_matches = reg.workers_serving("uuid-b");
        assert!(no_matches.is_empty());
    }

    #[test]
    fn test_workers_serving_general_matches_any_model() {
        let reg = WorkerRegistry::new();
        let w = reg.register(model_registration(
            "generalist",
            "http://127.0.0.1:4002",
            ProviderType::General,
            vec!["*"],
        ));

        for uuid in ["uuid-a", "uuid-b", "any-random-uuid"] {
            let matches = reg.workers_serving(uuid);
            assert_eq!(matches.len(), 1, "general worker should serve {uuid}");
            assert_eq!(matches[0].id, w.id);
        }
    }

    #[test]
    fn test_workers_serving_unions_specialized_and_general() {
        let reg = WorkerRegistry::new();
        let specialist = reg.register(model_registration(
            "specialist",
            "http://127.0.0.1:4003",
            ProviderType::Specialized,
            vec!["uuid-a"],
        ));
        let generalist = reg.register(model_registration(
            "generalist",
            "http://127.0.0.1:4004",
            ProviderType::General,
            vec![],
        ));

        let mut ids: Vec<String> = reg
            .workers_serving("uuid-a")
            .into_iter()
            .map(|w| w.id)
            .collect();
        ids.sort();
        let mut expected = vec![specialist.id.clone(), generalist.id.clone()];
        expected.sort();
        assert_eq!(ids, expected);
    }

    #[test]
    fn test_reregister_updates_model_index() {
        let reg = WorkerRegistry::new();
        let w1 = reg.register(model_registration(
            "flip",
            "http://127.0.0.1:4005",
            ProviderType::Specialized,
            vec!["uuid-old"],
        ));
        assert_eq!(reg.workers_serving("uuid-old").len(), 1);

        // Simulate re-registration: remove the old registration then register
        // the same worker (by name) with a different served_models set.
        reg.remove(&w1.id);
        assert!(
            reg.workers_serving("uuid-old").is_empty(),
            "removed worker must drop out of the old model's index entry"
        );

        let w2 = reg.register(model_registration(
            "flip",
            "http://127.0.0.1:4005",
            ProviderType::Specialized,
            vec!["uuid-new"],
        ));
        assert!(reg.workers_serving("uuid-old").is_empty());
        let matches = reg.workers_serving("uuid-new");
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].id, w2.id);
    }

    #[test]
    fn test_remove_drops_worker_from_general_index() {
        let reg = WorkerRegistry::new();
        let w = reg.register(model_registration(
            "generalist",
            "http://127.0.0.1:4006",
            ProviderType::General,
            vec![],
        ));
        assert_eq!(reg.workers_serving("any-uuid").len(), 1);
        reg.remove(&w.id);
        assert!(reg.workers_serving("any-uuid").is_empty());
    }

    #[test]
    fn test_legacy_worker_json_without_new_fields_defaults_back_compat() {
        // Legacy payload predating provider_type/served_models/price_per_mtok.
        let legacy_json = r#"{
            "id": "legacy-id",
            "name": "legacy-worker",
            "uri": "http://127.0.0.1:3960",
            "worker_type": "zakuro",
            "status": "healthy",
            "resources": {
                "cpus_total": 1.0,
                "cpus_available": 1.0,
                "memory_total": 1073741824,
                "memory_available": 1073741824,
                "gpus_total": 0,
                "gpus_available": 0
            },
            "pricing": {
                "price_per_hour": 3.6,
                "min_charge": 0.001
            },
            "last_heartbeat": "2026-01-01T00:00:00Z",
            "active_requests": 0,
            "total_requests": 0,
            "avg_latency_ms": 0.0,
            "tags": []
        }"#;

        let w: Worker = serde_json::from_str(legacy_json).expect("legacy JSON must deserialize");
        assert_eq!(w.provider_type, ProviderType::Specialized);
        assert!(w.served_models.is_empty());
        assert_eq!(w.price_per_mtok, 0.0);
    }

    #[test]
    fn test_legacy_worker_registration_json_without_new_fields_defaults_back_compat() {
        let legacy_json = r#"{
            "name": "legacy-worker",
            "uri": "http://127.0.0.1:3960",
            "worker_type": "zakuro"
        }"#;

        let r: WorkerRegistration =
            serde_json::from_str(legacy_json).expect("legacy JSON must deserialize");
        assert_eq!(r.provider_type, ProviderType::Specialized);
        assert!(r.served_models.is_empty());
        assert_eq!(r.price_per_mtok, 0.0);
    }

    // --- WorkerRegistry ---

    #[test]
    fn test_register_assigns_unique_id() {
        let reg = WorkerRegistry::new();
        let w1 = reg.register(registration("w1", "http://127.0.0.1:3960"));
        let w2 = reg.register(registration("w2", "http://127.0.0.1:3961"));
        assert!(!w1.id.is_empty());
        assert_ne!(w1.id, w2.id);
        assert_eq!(reg.count(), 2);
    }

    #[test]
    fn test_register_stores_fields() {
        let reg = WorkerRegistry::new();
        let worker = reg.register(registration("my-worker", "http://10.0.0.1:3960"));
        let got = reg.get(&worker.id).unwrap();
        assert_eq!(got.name, "my-worker");
        assert_eq!(got.uri, "http://10.0.0.1:3960");
        assert_eq!(got.status, WorkerStatus::Healthy);
        assert_eq!(got.active_requests, 0);
    }

    #[test]
    fn test_remove_worker() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w", "http://127.0.0.1:3960"));
        assert!(reg.get(&w.id).is_some());
        let removed = reg.remove(&w.id);
        assert!(removed.is_some());
        assert!(reg.get(&w.id).is_none());
        assert_eq!(reg.count(), 0);
    }

    #[test]
    fn test_heartbeat_updates_resources_and_status() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w", "http://127.0.0.1:3960"));

        let hb = WorkerHeartbeat {
            worker_id: w.id.clone(),
            resources: Some(WorkerResources {
                cpus_total: 8.0,
                cpus_available: 4.0,
                memory_total: 16 * 1024 * 1024 * 1024,
                memory_available: 8 * 1024 * 1024 * 1024,
                gpus_total: 2,
                gpus_available: 1,
            }),
            active_requests: Some(5),
            status: Some(WorkerStatus::Busy),
            max_timeout_secs: Some(120.0),
        };

        let updated = reg.heartbeat(hb).unwrap();
        assert_eq!(updated.resources.cpus_available, 4.0);
        assert_eq!(updated.resources.gpus_available, 1);
        assert_eq!(updated.active_requests, 5);
        assert_eq!(updated.status, WorkerStatus::Busy);
        assert_eq!(updated.max_timeout_secs, 120.0);
    }

    #[test]
    fn test_heartbeat_unknown_worker_returns_none() {
        let reg = WorkerRegistry::new();
        let hb = WorkerHeartbeat {
            worker_id: "nonexistent".to_string(),
            resources: None,
            active_requests: None,
            status: None,
            max_timeout_secs: None,
        };
        assert!(reg.heartbeat(hb).is_none());
    }

    #[test]
    fn test_mark_stale_sets_unhealthy() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w", "http://127.0.0.1:3960"));
        // timeout=-1 means every worker is immediately stale (elapsed >= 0 > -1)
        reg.mark_stale(-1);
        let got = reg.get(&w.id).unwrap();
        assert_eq!(got.status, WorkerStatus::Unhealthy);
    }

    #[test]
    fn test_refresh_heartbeat_restores_healthy() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w", "http://127.0.0.1:3960"));
        reg.mark_stale(-1);
        assert_eq!(reg.get(&w.id).unwrap().status, WorkerStatus::Unhealthy);
        reg.refresh_heartbeat(&w.id);
        assert_eq!(reg.get(&w.id).unwrap().status, WorkerStatus::Healthy);
    }

    #[test]
    fn aggregate_available_sums_healthy_workers() {
        let reg = WorkerRegistry::new();
        let mut r1 = registration("w1", "http://127.0.0.1:3960");
        r1.resources = WorkerResources {
            cpus_total: 4.0,
            cpus_available: 4.0,
            memory_total: 8_000_000_000,
            memory_available: 8_000_000_000,
            gpus_total: 1,
            gpus_available: 1,
        };
        let mut r2 = registration("w2", "http://127.0.0.1:3961");
        r2.resources = WorkerResources {
            cpus_total: 2.0,
            cpus_available: 2.0,
            memory_total: 4_000_000_000,
            memory_available: 4_000_000_000,
            gpus_total: 0,
            gpus_available: 0,
        };
        reg.register(r1);
        reg.register(r2);

        let agg = reg.aggregate_available();
        assert_eq!(agg.cpus_available, 6);
        assert_eq!(agg.memory_available, 12_000_000_000);
        assert_eq!(agg.gpus_available, 1);
        assert_eq!(agg.healthy_workers, 2);
    }

    #[test]
    fn aggregate_available_excludes_unhealthy_and_ignores_empty() {
        let reg = WorkerRegistry::new();
        let empty = reg.aggregate_available();
        assert_eq!(empty, BrokerResources::default());

        let w = reg.register(registration("sick", "http://127.0.0.1:3962"));
        reg.mark_unhealthy(&w.id);
        let agg = reg.aggregate_available();
        assert_eq!(agg.healthy_workers, 0);
        assert_eq!(agg.cpus_available, 0);
    }

    #[test]
    fn test_healthy_list_excludes_unhealthy() {
        let reg = WorkerRegistry::new();
        let w1 = reg.register(registration("healthy", "http://127.0.0.1:3960"));
        let w2 = reg.register(registration("sick", "http://127.0.0.1:3961"));
        reg.mark_unhealthy(&w2.id);

        let healthy = reg.healthy();
        assert_eq!(healthy.len(), 1);
        assert_eq!(healthy[0].id, w1.id);
    }

    #[test]
    fn test_increment_active_and_decrement_on_record() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w", "http://127.0.0.1:3960"));
        reg.increment_active(&w.id);
        reg.increment_active(&w.id);
        assert_eq!(reg.get(&w.id).unwrap().active_requests, 2);
        reg.record_request(&w.id, 100.0, true);
        assert_eq!(reg.get(&w.id).unwrap().active_requests, 1);
    }

    /// #438: replies to requests sent before a worker had answered anything
    /// pay its start-up or wait behind the one that does, so they count for
    /// success but not for timing. The first request sent after a reply is
    /// timed as usual, and a warm-up request that fails frees its slot.
    #[test]
    fn warm_up_replies_are_left_out_of_the_latency_posterior() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w", "http://127.0.0.1:3960"));
        // Three requests in flight before the worker has answered once.
        for _ in 0..3 {
            reg.increment_active(&w.id);
        }
        reg.record_request(&w.id, 1000.0, true); // the cold one
                                                 // Sent after a reply came back: a normal, timed request.
        reg.increment_active(&w.id);
        reg.record_request(&w.id, 990.0, true); // queued behind the cold one
        reg.record_request(&w.id, 985.0, true);
        let got = reg.get(&w.id).unwrap();
        assert_eq!(
            got.stats.weight(),
            0.0,
            "no warm-up timing may reach the posterior"
        );
        assert!(
            got.stats.success_rate() > 0.7,
            "but the successes still count"
        );
        assert_eq!(got.total_requests, 3);

        reg.record_request(&w.id, 4.0, true);
        let got = reg.get(&w.id).unwrap();
        assert_eq!(got.stats.weight(), 1.0);
        assert!((got.stats.median_service_ms().unwrap() - 4.0).abs() < 1e-9);
        assert_eq!(got.active_requests, 0);

        // A warm-up request that fails does not hold a later reply's timing out.
        let v = reg.register(registration("v", "http://127.0.0.1:3961"));
        {
            let _failed = reg.active_guard(&v.id);
        }
        reg.increment_active(&v.id);
        reg.record_request(&v.id, 1000.0, true);
        reg.increment_active(&v.id);
        reg.record_request(&v.id, 5.0, true);
        let got = reg.get(&v.id).unwrap();
        assert_eq!(got.stats.weight(), 1.0);
        assert!((got.stats.median_service_ms().unwrap() - 5.0).abs() < 1e-9);
    }

    #[test]
    fn active_guard_decrements_on_drop_even_without_record() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w1", "http://127.0.0.1:3960"));
        {
            let _g = reg.active_guard(&w.id);
            assert_eq!(reg.get(&w.id).unwrap().active_requests, 1);
        } // guard dropped here (simulates an error path with no record_request)
        assert_eq!(
            reg.get(&w.id).unwrap().active_requests,
            0,
            "active_requests must return to 0 when the guard drops on an error path"
        );
    }

    #[test]
    fn active_guard_disarm_skips_decrement() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w2", "http://127.0.0.1:3960"));
        {
            let mut g = reg.active_guard(&w.id);
            assert_eq!(reg.get(&w.id).unwrap().active_requests, 1);
            // Success path: record_request decremented, so disarm the guard.
            reg.record_request(&w.id, 10.0, true);
            g.disarm();
        }
        assert_eq!(
            reg.get(&w.id).unwrap().active_requests,
            0,
            "disarmed guard must not double-decrement after record_request"
        );
    }

    #[test]
    fn test_record_request_latency_ema() {
        let reg = WorkerRegistry::new();
        let w = reg.register(registration("w", "http://127.0.0.1:3960"));
        // First recording: EMA = 0.1 * 200 + 0.9 * 0 = 20
        reg.record_request(&w.id, 200.0, true);
        let got = reg.get(&w.id).unwrap();
        assert!((got.avg_latency_ms - 20.0).abs() < 0.001);
        assert_eq!(got.total_requests, 1);
    }

    #[test]
    fn test_find_capable_filters_by_resources() {
        let reg = WorkerRegistry::new();
        let mut r_small = registration("small", "http://127.0.0.1:3960");
        r_small.resources = WorkerResources {
            cpus_total: 2.0,
            cpus_available: 2.0,
            memory_total: 2 * 1024 * 1024 * 1024,
            memory_available: 2 * 1024 * 1024 * 1024,
            gpus_total: 0,
            gpus_available: 0,
        };
        let mut r_large = registration("large", "http://127.0.0.1:3961");
        r_large.resources = WorkerResources {
            cpus_total: 32.0,
            cpus_available: 32.0,
            memory_total: 128 * 1024 * 1024 * 1024,
            memory_available: 128 * 1024 * 1024 * 1024,
            gpus_total: 4,
            gpus_available: 4,
        };

        reg.register(r_small);
        reg.register(r_large);

        // Only large can serve 16 CPUs
        let capable = reg.find_capable(16.0, 1024 * 1024 * 1024, 0, None);
        assert_eq!(capable.len(), 1);
        assert_eq!(capable[0].name, "large");

        // Both can serve 1 CPU
        assert_eq!(reg.find_capable(1.0, 512 * 1024 * 1024, 0, None).len(), 2);

        // None can serve 8 GPUs
        assert_eq!(reg.find_capable(1.0, 512 * 1024 * 1024, 8, None).len(), 0);
    }

    #[test]
    fn test_find_capable_filters_by_min_vram_gb() {
        let reg = WorkerRegistry::new();
        let mut small_vram = registration("small-vram", "http://127.0.0.1:3962");
        small_vram.hardware.gpu_vram_gb = Some(8);
        let mut big_vram = registration("big-vram", "http://127.0.0.1:3963");
        big_vram.hardware.gpu_vram_gb = Some(24);
        let no_vram = registration("no-vram", "http://127.0.0.1:3964");

        reg.register(small_vram);
        reg.register(big_vram);
        reg.register(no_vram);

        let capable = reg.find_capable(0.1, 1024, 0, Some(16));
        assert_eq!(
            capable.len(),
            1,
            "only the 24 GiB worker clears a 16 GiB floor"
        );
        assert_eq!(capable[0].name, "big-vram");

        // No minimum: a worker that advertises no VRAM at all is still fine.
        assert_eq!(reg.find_capable(0.1, 1024, 0, None).len(), 3);
    }

    // --- Worker::can_handle ---

    #[test]
    fn test_can_handle_exact_match() {
        let w = Worker::new(
            "id".to_string(),
            "w".to_string(),
            "http://x".to_string(),
            "zakuro".to_string(),
        );
        // default: 1 CPU, 1 GiB, 0 GPU
        assert!(w.can_handle(1.0, 1024 * 1024 * 1024, 0));
    }

    #[test]
    fn test_can_handle_over_cpu_fails() {
        let w = Worker::new(
            "id".to_string(),
            "w".to_string(),
            "http://x".to_string(),
            "zakuro".to_string(),
        );
        assert!(!w.can_handle(2.0, 512 * 1024 * 1024, 0));
    }

    #[test]
    fn test_can_handle_over_memory_fails() {
        let w = Worker::new(
            "id".to_string(),
            "w".to_string(),
            "http://x".to_string(),
            "zakuro".to_string(),
        );
        assert!(!w.can_handle(0.5, 2 * 1024 * 1024 * 1024, 0));
    }

    #[test]
    fn test_can_handle_gpu_required_but_none_fails() {
        let w = Worker::new(
            "id".to_string(),
            "w".to_string(),
            "http://x".to_string(),
            "zakuro".to_string(),
        );
        assert!(!w.can_handle(0.5, 512 * 1024 * 1024, 1));
    }

    #[test]
    fn test_can_handle_unhealthy_worker_fails() {
        let mut w = Worker::new(
            "id".to_string(),
            "w".to_string(),
            "http://x".to_string(),
            "zakuro".to_string(),
        );
        w.status = WorkerStatus::Unhealthy;
        assert!(!w.can_handle(0.1, 1024, 0));
    }

    // --- WorkerPricing ---

    #[test]
    fn test_pricing_cost_formula() {
        let p = WorkerPricing {
            price_per_hour: 3.6,
            min_charge: 0.001,
        };
        // 10s at 3.6 yen/hour = 3.6/3600 * 10 = 0.010 > min_charge
        let cost = p.estimate_cost(10.0);
        assert!((cost - 0.010).abs() < 0.0001);
    }

    #[test]
    fn test_pricing_min_charge_enforced() {
        let p = WorkerPricing {
            price_per_hour: 0.0,
            min_charge: 0.005,
        };
        let cost = p.estimate_cost(0.001);
        assert_eq!(cost, 0.005);
    }

    // --- resolve_model ---

    fn priced_model_registration(
        name: &str,
        uri: &str,
        provider_type: ProviderType,
        served_models: Vec<&str>,
        price_per_mtok: f64,
    ) -> WorkerRegistration {
        let mut r = model_registration(name, uri, provider_type, served_models);
        r.price_per_mtok = price_per_mtok;
        r
    }

    #[test]
    fn test_resolve_model_prefers_specialized_over_general() {
        let reg = WorkerRegistry::new();
        let specialized = reg.register(priced_model_registration(
            "specialist",
            "http://127.0.0.1:5001",
            ProviderType::Specialized,
            vec!["uuid-a"],
            10.0,
        ));
        reg.register(priced_model_registration(
            "generalist",
            "http://127.0.0.1:5002",
            ProviderType::General,
            vec![],
            1.0, // cheaper, but general should lose to specialized
        ));

        let resolved = reg.resolve_model("uuid-a").unwrap();
        assert_eq!(resolved.id, specialized.id);
    }

    #[test]
    fn test_resolve_model_cheapest_among_specialized() {
        let reg = WorkerRegistry::new();
        reg.register(priced_model_registration(
            "expensive",
            "http://127.0.0.1:5003",
            ProviderType::Specialized,
            vec!["uuid-a"],
            20.0,
        ));
        let cheap = reg.register(priced_model_registration(
            "cheap",
            "http://127.0.0.1:5004",
            ProviderType::Specialized,
            vec!["uuid-a"],
            5.0,
        ));

        let resolved = reg.resolve_model("uuid-a").unwrap();
        assert_eq!(resolved.id, cheap.id);
    }

    #[test]
    fn test_resolve_model_general_fallback_cheapest() {
        let reg = WorkerRegistry::new();
        reg.register(priced_model_registration(
            "general-expensive",
            "http://127.0.0.1:5005",
            ProviderType::General,
            vec![],
            8.0,
        ));
        let cheap_general = reg.register(priced_model_registration(
            "general-cheap",
            "http://127.0.0.1:5006",
            ProviderType::General,
            vec![],
            2.0,
        ));

        let resolved = reg.resolve_model("uuid-z").unwrap();
        assert_eq!(resolved.id, cheap_general.id);
    }

    #[test]
    fn test_resolve_model_excludes_unhealthy_specialized_falls_back_to_general() {
        let reg = WorkerRegistry::new();
        let stale_specialist = reg.register(priced_model_registration(
            "stale-specialist",
            "http://127.0.0.1:5007",
            ProviderType::Specialized,
            vec!["uuid-a"],
            1.0, // cheapest, but stale/unhealthy so must be excluded
        ));
        reg.mark_unhealthy(&stale_specialist.id);

        let healthy_general = reg.register(priced_model_registration(
            "healthy-general",
            "http://127.0.0.1:5008",
            ProviderType::General,
            vec![],
            5.0,
        ));

        let resolved = reg.resolve_model("uuid-a").unwrap();
        assert_eq!(resolved.id, healthy_general.id);
    }

    #[test]
    fn test_resolve_model_no_provider_when_no_healthy_candidate() {
        let reg = WorkerRegistry::new();
        let w = reg.register(priced_model_registration(
            "only-specialist",
            "http://127.0.0.1:5009",
            ProviderType::Specialized,
            vec!["uuid-a"],
            1.0,
        ));
        reg.mark_unhealthy(&w.id);

        let err = reg.resolve_model("uuid-a").unwrap_err();
        assert_eq!(
            err,
            ModelResolveError::NoProvider {
                model_uuid: "uuid-a".to_string()
            }
        );
        assert_eq!(err.to_string(), "no provider serving zc://uuid-a");
    }

    #[test]
    fn test_pricing_price_score_weighted() {
        // 10s at ¥540/h = ¥1.5 > min_charge (¥0.15) → score = 1.5
        let p = WorkerPricing::default();
        let score = p.price_score();
        assert!((score - 1.5).abs() < 0.0001);
    }
}

/// Drain and hub-price behaviour the zc agent relies on
/// (spec 2026-09-13-macos-widget §6.5-6.6).
#[cfg(test)]
mod drain_and_price_tests {
    use super::*;

    #[test]
    fn drain_marks_draining_and_leaves_the_routable_set() {
        let r = WorkerRegistry::new();
        let w = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        assert_eq!(r.drain(&w.id).unwrap().status, WorkerStatus::Draining);
        assert!(
            r.healthy_ids().is_empty(),
            "a draining worker is never selected"
        );
        assert!(r.healthy().is_empty());
    }

    #[test]
    fn discovery_refresh_does_not_undo_a_drain() {
        let r = WorkerRegistry::new();
        let w = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        r.drain(&w.id);
        r.refresh_heartbeat(&w.id);
        r.update_resources(&w.id, WorkerResources::default(), HardwareInfo::default());
        assert_eq!(r.get(&w.id).unwrap().status, WorkerStatus::Draining);
    }

    #[test]
    fn a_worker_heartbeat_does_not_undo_a_drain() {
        let r = WorkerRegistry::new();
        let w = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        r.drain(&w.id);
        r.heartbeat(WorkerHeartbeat {
            worker_id: w.id.clone(),
            resources: None,
            active_requests: Some(1),
            status: Some(WorkerStatus::Healthy),
            max_timeout_secs: None,
        });
        let got = r.get(&w.id).unwrap();
        assert_eq!(got.status, WorkerStatus::Draining);
        assert_eq!(
            got.active_requests, 1,
            "the rest of the heartbeat still applies"
        );
    }

    #[test]
    fn draining_an_unknown_worker_is_none() {
        assert!(WorkerRegistry::new().drain("nope").is_none());
    }

    /// A failed forward must not undo a drain — otherwise the next
    /// discovery scan lifts a merely-Unhealthy worker back to Healthy and a
    /// drained-then-stopping worker is put back in rotation.
    #[test]
    fn mark_unhealthy_does_not_undo_a_drain() {
        let r = WorkerRegistry::new();
        let w = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        r.drain(&w.id);
        r.mark_unhealthy(&w.id);
        assert_eq!(r.get(&w.id).unwrap().status, WorkerStatus::Draining);
    }

    #[test]
    fn hub_price_overrides_billing_and_remembers_the_workers_own_price() {
        use std::collections::HashMap;
        let r = WorkerRegistry::new();
        let w = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));

        assert_eq!(
            r.apply_hub_prices(&HashMap::from([("fp-w0".to_string(), 18.0)])),
            1
        );
        let got = r.get(&w.id).unwrap();
        assert_eq!(got.pricing.price_per_hour, 18.0);
        assert_eq!(got.reported_price_per_hour, Some(3.6));

        // A later override keeps the ORIGINAL reported price.
        r.apply_hub_prices(&HashMap::from([("fp-w0".to_string(), 25.0)]));
        let got = r.get(&w.id).unwrap();
        assert_eq!(got.pricing.price_per_hour, 25.0);
        assert_eq!(got.reported_price_per_hour, Some(3.6));

        // Re-applying the same price is a no-op.
        assert_eq!(
            r.apply_hub_prices(&HashMap::from([("fp-w0".to_string(), 25.0)])),
            0
        );
    }

    #[test]
    fn discovery_refresh_keeps_the_hub_price() {
        use std::collections::HashMap;
        let r = WorkerRegistry::new();
        let w = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        r.apply_hub_prices(&HashMap::from([("fp-w0".to_string(), 18.0)]));
        r.update_resources(&w.id, WorkerResources::default(), HardwareInfo::default());
        r.refresh_heartbeat(&w.id);
        assert_eq!(r.get(&w.id).unwrap().pricing.price_per_hour, 18.0);
    }

    #[test]
    fn peer_workers_are_never_repriced() {
        use std::collections::HashMap;
        let r = WorkerRegistry::new();
        let mut peer = test_registration("fp-w0", "http://127.0.0.1:3960".to_string(), 3.6);
        peer.source_node = Some("node-other".to_string());
        let w = r.register(peer);
        assert_eq!(
            r.apply_hub_prices(&HashMap::from([("fp-w0".to_string(), 18.0)])),
            0
        );
        assert_eq!(r.get(&w.id).unwrap().pricing.price_per_hour, 3.6);
    }

    /// Fix round 1, Finding 1: a re-registration under the same name (a worker
    /// restart re-probing and rebuilding `pricing` from scratch) must not lose
    /// the hub's price, even with no sync in between the two registrations.
    #[test]
    fn hub_price_survives_re_registration_with_no_sync_in_between() {
        use std::collections::HashMap;
        let r = WorkerRegistry::new();
        let w1 = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        r.apply_hub_prices(&HashMap::from([("fp-w0".to_string(), 18.0)]));
        assert_eq!(r.get(&w1.id).unwrap().pricing.price_per_hour, 18.0);

        // Re-register the SAME name: a fresh record (new id), freshly-probed
        // pricing (a different probed price, to prove it is the one recorded
        // as `reported_price_per_hour`, not just echoed back).
        let w2 = r.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3961".to_string(),
            4.2,
        ));
        assert_ne!(w1.id, w2.id, "re-registration creates a new record");

        let got = r.get(&w2.id).unwrap();
        assert_eq!(
            got.pricing.price_per_hour, 18.0,
            "billing must use the hub price immediately, no sync needed"
        );
        assert_eq!(
            got.reported_price_per_hour,
            Some(4.2),
            "sync must keep reporting the freshly-probed price, not the hub price"
        );
    }
}

/// A departed worker's posterior, and what happens to it while it is away
/// (#270, "Posterior TTL for departed workers").
#[cfg(test)]
mod posterior_ttl_tests {
    use super::*;
    use crate::broker::estimator::Stats;
    use crate::broker::policy::{self, Candidate, Weights};

    fn measured(median_ms: f64, n: usize) -> Stats {
        let mut s = Stats::new();
        for _ in 0..n {
            s.observe(median_ms, true);
        }
        s
    }

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(1_700_000_000 + secs, 0).expect("valid timestamp")
    }

    /// The point of the cache: a worker that leaves and comes straight back is
    /// the same worker, and its posterior is the best thing known about it.
    #[test]
    fn a_posterior_taken_back_at_once_is_the_one_that_was_parked() {
        let cache = PosteriorCache::new();
        let stats = measured(40.0, 30);
        cache.park("k".into(), stats, at(0), at(0));

        let back = cache.take("k", at(0)).expect("parked a moment ago");
        assert!(back.close_to(&stats), "{back:?} vs {stats:?}");
        assert!(
            cache.take("k", at(0)).is_none(),
            "taken means taken: the entry is not handed out twice"
        );
    }

    /// Time away is evidence going stale. A posterior that comes back with the
    /// confidence it left with would pin a returning worker to a measurement of
    /// a mesh that has moved on, and `decay` is how this codebase already says
    /// "older evidence counts for less".
    #[test]
    fn a_posterior_loses_confidence_in_proportion_to_how_long_it_was_gone() {
        let cache = PosteriorCache::new();
        let stats = measured(40.0, 100);
        cache.park("k".into(), stats, at(0), at(0));

        let back = cache.take("k", at(240)).expect("inside the ttl");

        // The shape survives: the median is a ratio of decayed sums, so it is
        // untouched. Only the weight behind it falls.
        assert!(
            (back.median_service_ms().unwrap() - 40.0).abs() < 1e-9,
            "the median it learned is still the median: {back:?}"
        );
        let expected = 100.0 * STATS_DECAY.powi(240);
        assert!(
            (back.weight() - expected).abs() < 1e-9,
            "four minutes away should leave {expected}, got {}",
            back.weight()
        );
        assert!(
            back.weight() < 1.0,
            "four minutes is long enough that the policy re-explores it"
        );
    }

    /// The gap is measured from when the worker was last alive, not from when
    /// the sweeper happened to notice it was gone -- otherwise how much a
    /// posterior decays depends on `health_check_interval`, a knob that has
    /// nothing to do with how fast evidence ages.
    #[test]
    fn the_gap_is_measured_from_when_the_worker_was_last_seen() {
        let cache = PosteriorCache::new();
        let stats = measured(40.0, 100);
        // Last heartbeat at t=0; the sweeper only removed it at t=60.
        cache.park("k".into(), stats, at(0), at(60));

        let back = cache.take("k", at(120)).expect("inside the ttl");
        let expected = 100.0 * STATS_DECAY.powi(120);
        assert!(
            (back.weight() - expected).abs() < 1e-9,
            "120s of silence, not 60s since removal: want {expected}, got {}",
            back.weight()
        );
    }

    /// Past the TTL the address is more likely to be a different machine than
    /// the same one returning, and by then the decay has left nothing worth
    /// the risk.
    #[test]
    fn a_posterior_older_than_the_ttl_is_not_restored() {
        let cache = PosteriorCache::new();
        cache.park("k".into(), measured(40.0, 100), at(0), at(0));

        assert!(
            cache.take("k", at(POSTERIOR_TTL_SECS)).is_some(),
            "on the boundary it still counts"
        );
        cache.park("k".into(), measured(40.0, 100), at(0), at(0));
        assert!(cache.take("k", at(POSTERIOR_TTL_SECS + 1)).is_none());
    }

    /// The TTL is a backstop, not the regulator: by the time it fires, even an
    /// implausibly well-measured worker is below the single observation
    /// `policy::sample_service_ms` needs before it prefers a measured
    /// posterior to the class prior. That is what makes 10 minutes the right
    /// place to stop keeping the entry at all.
    #[test]
    fn nothing_survives_to_the_ttl_that_the_policy_would_still_believe() {
        let cache = PosteriorCache::new();
        cache.park("k".into(), measured(40.0, 100_000), at(0), at(0));
        let back = cache
            .take("k", at(POSTERIOR_TTL_SECS))
            .expect("on the boundary");
        assert!(
            back.weight() < 1.0,
            "a hundred thousand observations still decay below one in {POSTERIOR_TTL_SECS}s, \
             got {}",
            back.weight()
        );
    }

    /// A broker that has seen a lot of churn must not pay for it forever.
    #[test]
    fn the_parked_cache_does_not_grow_without_bound() {
        let cache = PosteriorCache::new();
        for i in 0..(MAX_PARKED_POSTERIORS * 2) {
            cache.park(
                format!("k{i}"),
                measured(40.0, 5),
                at(i as i64),
                at(i as i64),
            );
        }
        assert!(
            cache.len() <= MAX_PARKED_POSTERIORS,
            "{} entries parked, cap is {MAX_PARKED_POSTERIORS}",
            cache.len()
        );
        // What is dropped is the oldest, which is also the most decayed.
        assert!(
            cache.take("k0", at(0)).is_none(),
            "the first one went first"
        );
        let newest = format!("k{}", MAX_PARKED_POSTERIORS * 2 - 1);
        assert!(cache.take(&newest, at(0)).is_some(), "the newest is kept");
    }

    /// Parking a blank posterior would spend an entry to remember nothing, and
    /// on a broker whose workers churn before they are ever used that is the
    /// common case.
    #[test]
    fn an_unmeasured_worker_has_no_posterior_worth_parking() {
        let cache = PosteriorCache::new();
        cache.park("k".into(), Stats::new(), at(0), at(0));
        assert_eq!(cache.len(), 0);
        assert!(cache.take("k", at(0)).is_none());
    }

    /// Identity, end to end: a worker drops out, is swept, and re-registers at
    /// the same address under a fresh uuid. That uuid is the thing that does
    /// NOT survive (#282), so the posterior has to be keyed on something that
    /// does.
    #[test]
    fn a_worker_that_flaps_comes_back_with_what_it_had_learned() {
        let reg = WorkerRegistry::new();
        let w = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        for _ in 0..40 {
            reg.record_request(&w.id, 12.0, true);
        }
        let learned = reg.get(&w.id).unwrap().stats;
        assert!(learned.weight() > 1.0);

        reg.mark_stale(-1);
        assert_eq!(reg.remove_stale(-1), vec![w.id.clone()]);

        let again = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        assert_ne!(again.id, w.id, "the id is a fresh uuid every registration");
        assert!(
            (again.stats.median_service_ms().unwrap() - 12.0).abs() < 1e-6,
            "it came back knowing what it had measured: {:?}",
            again.stats
        );
        assert!(
            again.stats.weight() > 1.0,
            "and enough weight to be believed"
        );
    }

    /// Deleting a worker is an operator saying it is gone on purpose. Going
    /// stale is the broker guessing that it is. Only the guess is worth
    /// reversing: a deliberate delete-and-re-add is the one move an operator
    /// has for "forget what you think you know about this address".
    #[test]
    fn a_worker_deleted_on_purpose_comes_back_a_stranger() {
        let reg = WorkerRegistry::new();
        let w = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        for _ in 0..40 {
            reg.record_request(&w.id, 12.0, true);
        }
        reg.remove(&w.id).expect("removed");

        let again = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        assert_eq!(
            again.stats.median_service_ms(),
            None,
            "an explicit delete forgets the posterior too"
        );
    }

    /// A deliberate delete must also clear a posterior parked EARLIER by the
    /// stale sweeper, or "delete it and add it again" would silently restore
    /// the history the operator asked to be rid of.
    #[test]
    fn deleting_a_worker_clears_a_posterior_parked_before_it() {
        let reg = WorkerRegistry::new();
        let first = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        for _ in 0..40 {
            reg.record_request(&first.id, 12.0, true);
        }
        reg.mark_stale(-1);
        reg.remove_stale(-1);

        let second = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        assert!(second.stats.weight() > 1.0, "restored by the flap path");
        reg.remove(&second.id).expect("removed");

        let third = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        assert_eq!(third.stats.median_service_ms(), None);
    }

    /// Two workers on two boxes are routinely called the same thing -- on a
    /// fleet where every host is `lxd`, every worker is `worker-lxd`. A key
    /// that cannot tell them apart would hand one machine's history to
    /// another, which is worse than starting blank.
    #[test]
    fn a_posterior_is_never_restored_onto_a_different_worker() {
        let reg = WorkerRegistry::new();
        let w = reg.register(test_registration(
            "worker-lxd",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        for _ in 0..40 {
            reg.record_request(&w.id, 12.0, true);
        }
        reg.mark_stale(-1);
        reg.remove_stale(-1);

        let elsewhere = reg.register(test_registration(
            "worker-lxd",
            "http://10.13.13.99:3960".to_string(),
            3.6,
        ));
        assert_eq!(
            elsewhere.stats.median_service_ms(),
            None,
            "same name, different box: not the same worker"
        );
    }

    /// A posterior is a record of a whole round trip, so it is only about the
    /// path it was measured over. The same box reached through a peer broker
    /// is not the same measurement, and must not inherit one.
    #[test]
    fn a_posterior_does_not_cross_from_a_local_worker_to_a_peer_one() {
        let reg = WorkerRegistry::new();
        let w = reg.register(test_registration(
            "w0",
            "http://10.13.13.21:3960".to_string(),
            3.6,
        ));
        for _ in 0..40 {
            reg.record_request(&w.id, 12.0, true);
        }
        reg.mark_stale(-1);
        reg.remove_stale(-1);

        let mut peer = test_registration("w0", "http://10.13.13.21:3960".to_string(), 3.6);
        peer.source_node = Some("node-i9".to_string());
        let as_peer = reg.register(peer);
        assert_eq!(as_peer.stats.median_service_ms(), None);
    }

    /// The whole TTL, through the registry, on an injected clock -- no sleeps.
    #[test]
    fn a_returning_worker_is_believed_less_the_longer_it_was_away() {
        let after = |gap_secs: i64| {
            let reg = WorkerRegistry::new();
            let w = reg.register(test_registration(
                "w0",
                "http://10.13.13.21:3960".to_string(),
                3.6,
            ));
            for _ in 0..100 {
                reg.record_request(&w.id, 12.0, true);
            }
            let last_seen = reg.get(&w.id).unwrap().last_heartbeat;
            reg.mark_stale(-1);
            reg.remove_stale(-1);
            reg.register_at(
                test_registration("w0", "http://10.13.13.21:3960".to_string(), 3.6),
                last_seen + Duration::seconds(gap_secs),
            )
            .stats
        };

        let straight_back = after(1).weight();
        let four_minutes = after(240).weight();
        let past_the_ttl = after(POSTERIOR_TTL_SECS + 1);

        assert!(
            straight_back > four_minutes,
            "{straight_back} vs {four_minutes}"
        );
        assert!(four_minutes < 1.0, "four minutes away costs its confidence");
        assert!(four_minutes > 0.0, "but not its shape");
        assert_eq!(
            past_the_ttl.median_service_ms(),
            None,
            "past the ttl it is a stranger again"
        );
    }

    /// The interaction #270 asks to keep straight: a restored posterior is a
    /// better warmup than any class prior, so it has to win over one. A peer
    /// that measured 12 ms and has been away two minutes still outranks the
    /// 500 ms an unmeasured peer is assumed to cost.
    #[test]
    fn a_restored_posterior_beats_the_class_prior_it_would_otherwise_start_from() {
        let cache = PosteriorCache::new();
        cache.park("k".into(), measured(12.0, 100), at(0), at(0));
        let restored = cache.take("k", at(120)).expect("inside the ttl");

        let w = Weights::default();
        let returning = Candidate {
            stats: restored,
            in_flight: 0,
            price_per_hour: 3.6,
            local: false,
        };
        let stranger = Candidate {
            stats: Stats::new(),
            in_flight: 0,
            price_per_hour: 3.6,
            local: false,
        };
        assert!(
            policy::table_weight(&returning, &w) > policy::table_weight(&stranger, &w),
            "a worker measured at 12ms two minutes ago must outrank one merely \
             assumed at {}ms",
            w.unmeasured_ms + w.mesh_hop_ms
        );
    }
}