zc2 0.0.38

P2P compute broker with credit-based billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
//! HTTP server for the broker API using tiny_http.
//! Request handling runs on separated threads (async_exec) so the server stays responsive.

use std::io::Read;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Instant;

use crate::async_exec;

use chrono::Local;
use colored::Colorize;
use serde::{Deserialize, Serialize};
use tiny_http::{Header, Method};

use super::http_adapter::{BrokerRequest, BrokerResponse};
use super::{
    discovery::{detect_discovery_mode, Discovery, DiscoveryMode},
    flush::{BufferedTransaction, ANONYMOUS_USER},
    ledger, node_identity,
    peer::{self, Authority},
    recovery,
    router::{self, ExcludedWorker, ResourceRequirements, RoutingDecision},
    stats::{StatsResponse, TaskOfferRecord, TransactionRecord, TransactionStatus, WorkerStats},
    task_board,
    wal::{WalEntry, WalStatus},
    worker::{
        self, ModelResolveError, Worker, WorkerHeartbeat, WorkerName, WorkerRegistration,
        WorkerStatus,
    },
    BrokerConfig, BrokerState,
};
use crate::model_uri::parse_model_uri;

/// Global request counter for transaction IDs
static REQUEST_COUNTER: AtomicU64 = AtomicU64::new(0);

/// TTL for a two-phase peer offer reserved but not yet committed/cancelled.
/// Past this, the background sweep releases the held worker slot.
const PENDING_OFFER_TTL_SECS: u64 = 10;

/// Build a `(name, value)` header pair, falling back to a safe marker header
/// when the name/value bytes would be rejected by HTTP header validation (e.g.
/// peer-supplied worker names containing CR/LF/NUL). Never panics on
/// attacker-controlled data — the returned pair is always safe to emit.
fn header_or(name: &str, value: &str) -> (String, String) {
    // Reuse tiny_http's validation: if it accepts the bytes, the pair is safe;
    // otherwise fall back to the inert marker header.
    if Header::from_bytes(name.as_bytes(), value.as_bytes()).is_ok() {
        (name.to_string(), value.to_string())
    } else {
        ("X-Zakuro-Invalid".to_string(), "1".to_string())
    }
}

/// How many characters of a `RoutingDecision`'s reason are worth putting on
/// the wire. Every reason produced today is well under this; the cap exists
/// so an adversarial worker/peer name interpolated into a reason string (e.g.
/// "Instance affinity: pinned to {name}") can't inflate the response.
const REASON_HEADER_MAX_LEN: usize = 200;

/// Bound and sanitize a routing decision's reason before it goes out as
/// `X-Zakuro-Reason`: fold any CR/LF to a space (a worker or peer name
/// embedded in the reason is not fully trusted input) and cap the length.
/// `header_or`'s own tiny_http validation is the final backstop — this just
/// keeps a legitimate-but-long or newline-bearing reason from either being
/// truncated to the generic `X-Zakuro-Invalid` marker or silently dropping
/// the header's usefulness.
fn sanitize_reason_header(reason: &str) -> String {
    reason
        .chars()
        .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
        .take(REASON_HEADER_MAX_LEN)
        .collect()
}

/// Clamp a computed charge to [0, reserved]: a non-finite or negative computed
/// value charges nothing; an over-large value is capped at what was reserved,
/// so a timeout (charged on elapsed time) can never bill more than was held.
fn capped_charge(computed: f64, reserved: f64) -> f64 {
    if computed.is_finite() {
        computed.clamp(0.0, reserved.max(0.0))
    } else {
        0.0
    }
}

/// Format credits with color based on amount
fn format_credits(amount: f64) -> String {
    if amount >= 1.0 {
        format!("{:.4}", amount).green().to_string()
    } else if amount >= 0.01 {
        format!("{:.4}", amount).yellow().to_string()
    } else {
        format!("{:.6}", amount).cyan().to_string()
    }
}

/// Log a transaction in live mode and record to stats
#[allow(clippy::too_many_arguments)]
fn log_transaction(
    state: &Arc<BrokerState>,
    verbose: bool,
    tx_num: u64,
    user: &str,
    action: &str,
    cost: f64,
    balance: f64,
    worker: Option<&str>,
    duration_ms: f64,
    status: &str,
) {
    log_transaction_with_worker_info(
        state,
        verbose,
        tx_num,
        user,
        action,
        cost,
        balance,
        worker,
        duration_ms,
        status,
        None,
        None,
        None,
        None,
        None,
    );
}

/// Log a transaction with optional request_id (for trace), price, and worker identity
#[allow(clippy::too_many_arguments)]
fn log_transaction_with_worker_info(
    state: &Arc<BrokerState>,
    verbose: bool,
    tx_num: u64,
    user: &str,
    action: &str,
    cost: f64,
    balance: f64,
    worker: Option<&str>,
    duration_ms: f64,
    status: &str,
    price_per_hour: Option<f64>,
    owner_id: Option<&str>,
    worker_pid: Option<&str>,
    worker_ip: Option<&str>,
    request_id: Option<&str>,
) {
    let now = Local::now();

    let tx_status = match status {
        "OK" => TransactionStatus::Ok,
        "FAIL" => TransactionStatus::Fail,
        "PENDING" => TransactionStatus::Pending,
        _ => TransactionStatus::Pending,
    };

    let record = TransactionRecord {
        tx_num,
        timestamp: now,
        user_id: user.to_string(),
        action: action.to_string(),
        cost,
        balance,
        worker: worker.map(|s| s.to_string()),
        duration_ms,
        status: tx_status,
        price_per_hour,
        owner_id: owner_id.map(|s| s.to_string()),
        worker_pid: worker_pid.map(|s| s.to_string()),
        worker_ip: worker_ip.map(|s| s.to_string()),
        request_id: request_id.map(|s| s.to_string()),
    };
    state.stats.record_transaction(record);

    // Console logging (verbose mode only)
    if !verbose {
        return;
    }

    let time_str = now.format("%H:%M:%S").to_string();

    let status_icon = match status {
        "OK" => "✓".green(),
        "FAIL" => "✗".red(),
        "PENDING" => "⋯".yellow(),
        _ => "•".white(),
    };

    let worker_str = worker
        .map(|w| format!(" → {}", w.cyan()))
        .unwrap_or_default();

    println!(
        "  {} {} #{:<4} {:>12} {:>8}  cost:{} bal:{} {:>6.1}ms{}",
        time_str.dimmed(),
        status_icon,
        tx_num,
        user.blue(),
        action.bold(),
        format_credits(cost),
        format_credits(balance),
        duration_ms,
        worker_str,
    );
}

/// Worker list response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerListResponse {
    pub workers: Vec<WorkerInfo>,
    pub total: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerInfo {
    pub id: String,
    pub name: String,
    pub uri: String,
    pub worker_type: String,
    pub status: String,
    pub cpus_available: f64,
    pub cpus_total: f64,
    pub memory_available_gib: f64,
    pub memory_total_gib: f64,
    pub gpus_available: u32,
    pub gpus_total: u32,
    pub price_per_hour: f64,
    pub min_charge: f64,
    pub active_requests: u32,
    pub avg_latency_ms: f64,
    pub max_timeout_secs: f64,
    pub gpu_model: Option<String>,
    pub gpu_vram_gb: Option<u32>,
    pub cpu_model: Option<String>,
    /// The interpreter this worker runs (zc#327). Unlike every other field
    /// here it is not a capacity but a capability: a cloudpickled payload
    /// built on a different CPython minor version cannot execute here at all.
    /// `None` from a worker too old to report it -- which is an answer, and
    /// must not be read as "compatible".
    pub python_version: Option<String>,
    pub python_implementation: Option<String>,
    pub storage_gb: Option<u32>,
    // Time-windowed request counts
    pub requests_5h: u64,
    pub requests_1w: u64,
    pub requests_1m: u64,
    // Quota limits (0 = unlimited)
    pub quota_5h: u64,
    pub quota_1w: u64,
    pub quota_1m: u64,
    pub wireguard_ip: Option<String>,
    pub is_docker: Option<bool>,
    /// Owning node's zc:// handle (`zc://node-…`). Present on client-facing responses.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node: Option<String>,
    /// Whether this worker serves a fixed model catalog or any model. Carried
    /// on /peer/workers so a peer broker can rebuild its model index for this
    /// provider (zc#172: without these three fields the index stayed per-pod).
    #[serde(default)]
    pub provider_type: worker::ProviderType,
    /// Model uuids this worker serves (`["*"]` for a general provider).
    #[serde(default)]
    pub served_models: Vec<String>,
    /// Price per 1,000,000 tokens for model inference, in credits.
    #[serde(default)]
    pub price_per_mtok: f64,
    /// Display name, carried alongside the opaque key-derived `uri`/`node` handles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// The broker's posterior for this worker's service time — median,
    /// spread, and how many (decayed) observations back it. `None` unless
    /// the caller asked for it (`GET /workers?estimate=1`): it is the
    /// broker's own belief, not part of the worker's advertised identity,
    /// and costs a field on every listed worker, so it stays opt-in rather
    /// than riding along on every `/workers` response and every peer sync.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub estimate: Option<WorkerEstimate>,
    /// Capability tags (`apple-silicon`, ...) a request can require. Additive:
    /// omitted when empty, ignored by peers that predate it (zc#403).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
}

/// What the broker currently believes about one worker's service time,
/// derived from `estimator::Stats`. "Never measured" is `None` on the two
/// posterior fields, never `Some(0.0)` — zero looks like a confident,
/// blazing-fast answer, and that confusion is exactly what let an unmeasured
/// worker outrank one measured at 5ms.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub struct WorkerEstimate {
    /// Discounted observation count. 0.0 means never measured.
    pub observations: f64,
    /// Posterior median service time in ms. `None` until at least one
    /// observation exists.
    pub median_service_ms: Option<f64>,
    /// Spread of log service time. `None` until at least two observations
    /// exist (one point has no spread to speak of).
    pub log_sd: Option<f64>,
}

impl From<&crate::broker::estimator::Stats> for WorkerEstimate {
    fn from(stats: &crate::broker::estimator::Stats) -> Self {
        WorkerEstimate {
            observations: stats.weight(),
            median_service_ms: stats.median_service_ms(),
            log_sd: stats.log_sd(),
        }
    }
}

/// Price estimate response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceEstimateResponse {
    pub min_cost: f64,
    pub max_cost: f64,
    pub matching_workers: usize,
}

/// One worker as `POST /route` (contract zc#345 §4) reports it.
#[derive(Debug, Clone, Serialize)]
struct RouteCandidateView {
    worker_id: String,
    node_fingerprint: String,
    address: String,
    gpu_model: Option<String>,
    gpu_vram_gb: Option<u32>,
    price_per_hour: f64,
    estimated_cost: f64,
    active_requests: u32,
    /// The worker's `atelier-runner=<url>` tag, if it advertises one.
    #[serde(skip_serializing_if = "Option::is_none")]
    atelier_runner: Option<String>,
}

/// `POST /route`'s success body (contract zc#345 §4).
#[derive(Debug, Clone, Serialize)]
struct RouteResponse {
    strategy: String,
    chosen: RouteCandidateView,
    candidates: Vec<RouteCandidateView>,
    excluded: Vec<ExcludedWorker>,
}

/// A worker's `atelier-runner=<url>` tag value, if it has one.
fn atelier_runner_tag(tags: &[String]) -> Option<String> {
    tags.iter()
        .find_map(|t| t.strip_prefix("atelier-runner=").map(str::to_string))
}

/// `RouteCandidate` (router.rs) -> the client-facing shape contract zc#345
/// §4 specifies. IP-free like every other client-facing worker view in
/// this file: `address` is the opaque `zc://worker-...` handle, never the raw
/// mesh URI.
fn route_candidate_view(
    rc: &router::RouteCandidate,
    node_key: &super::node_identity::NodeKey,
) -> RouteCandidateView {
    let w = &rc.worker;
    let bare = |n: &str| n.strip_prefix("node-").unwrap_or(n).to_string();
    let node_fingerprint = match &w.source_node {
        Some(n) => bare(n),
        None => node_key.fingerprint(),
    };
    RouteCandidateView {
        worker_id: w.id.clone(),
        node_fingerprint,
        address: w.zc_uri(),
        gpu_model: w.hardware.gpu_model.clone(),
        gpu_vram_gb: w.hardware.gpu_vram_gb,
        price_per_hour: w.pricing.price_per_hour,
        estimated_cost: rc.estimated_cost,
        active_requests: w.active_requests,
        atelier_runner: atelier_runner_tag(&w.tags),
    }
}

/// Credit balance response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreditBalanceResponse {
    pub user_id: String,
    pub balance: f64,
    pub total_spent: f64,
    pub rate_limit: u32,
    pub rate_limit_per_second: Option<u32>,
    pub rate_limit_per_day: Option<u32>,
    pub rate_limit_per_month: Option<u32>,
}

#[derive(Debug, Serialize)]
struct ErrorResponse {
    error: String,
    code: String,
}

#[derive(Debug, Deserialize)]
struct AddCreditsRequest {
    amount: f64,
    #[serde(default)]
    description: Option<String>,
}

fn json_response<T: Serialize>(data: &T, status: u16) -> BrokerResponse {
    let body = serde_json::to_vec(data).unwrap_or_default();
    BrokerResponse::json_bytes(body, status)
}

fn error_response(error: &str, code: &str, status: u16) -> BrokerResponse {
    json_response(
        &ErrorResponse {
            error: error.to_string(),
            code: code.to_string(),
        },
        status,
    )
}

/// Send a task offer to a peer over QUIC using its advertised QUIC port.
fn quic_offer(
    qt: &std::sync::Arc<super::quic::QuicTransport>,
    peer_http_url: &str,
    quic_port: u16,
    offer: &task_board::TaskOffer,
) -> Result<task_board::TaskResult, String> {
    let url_trimmed = peer_http_url
        .trim_start_matches("http://")
        .trim_start_matches("https://");
    let host = url_trimmed.split(':').next().unwrap_or("127.0.0.1");

    // On loopback, connect via 127.0.0.1 because Linux rewrites source IPs
    let connect_host = if host.starts_with("127.") {
        "127.0.0.1"
    } else {
        host
    };

    let addr: SocketAddr = format!("{}:{}", connect_host, quic_port)
        .parse()
        .map_err(|e| format!("bad quic addr: {}", e))?;
    qt.offer_task(addr, offer)
}

/// Whether this broker starts its QUIC transport (mesh-routes §4). Not when
/// `ZAKURO_DISABLE_QUIC` is `1`/`true`, and not on the proxy route, whose
/// container relay carries TCP only.
pub(crate) fn quic_wanted(disable_env: Option<&str>, route: &crate::vpn::Route) -> bool {
    !matches!(disable_env, Some("1" | "true")) && !route.is_proxy()
}

/// How a task offer reaches one peer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OfferTransport {
    Quic(u16),
    Http,
}

/// QUIC only when this broker runs it and the peer advertised a port;
/// otherwise HTTP, through the proxy-aware `PeerClient`. That makes it always
/// HTTP on the proxy route, where QUIC is never started.
pub(crate) fn offer_transport(quic_started: bool, peer_quic_port: u16) -> OfferTransport {
    if quic_started && peer_quic_port > 0 {
        OfferTransport::Quic(peer_quic_port)
    } else {
        OfferTransport::Http
    }
}

/// Offer a task to one peer over the transport [`offer_transport`] picks, and
/// name the transport used (`"quic"`, `"http"`, or empty for an unknown peer).
/// `quic` is this broker's own transport: without one the offer goes over
/// HTTP, even to a peer whose cached QUIC port is set.
fn offer_to_peer(
    state: &BrokerState,
    quic: Option<&std::sync::Arc<super::quic::QuicTransport>>,
    peer_url: &str,
    offer: &task_board::TaskOffer,
) -> (Result<task_board::TaskResult, String>, String) {
    let peer_quic_port = state.peer_manager.get_quic_port(peer_url);
    match (offer_transport(quic.is_some(), peer_quic_port), quic) {
        (OfferTransport::Quic(p), Some(qt)) => {
            (quic_offer(qt, peer_url, p, offer), "quic".to_string())
        }
        _ => match state.peer_manager.get_client(peer_url) {
            Some(client) => (client.offer_task(offer), "http".to_string()),
            None => (Err("peer unreachable".into()), String::new()),
        },
    }
}

#[cfg(test)]
mod quic_route_tests {
    use super::{
        offer_to_peer, offer_transport, quic_wanted, start_quic_transport, OfferTransport,
    };
    use crate::broker::http_adapter::BrokerRequest;
    use crate::broker::peer::PeerManager;
    use crate::broker::task_board;
    use crate::broker::{BrokerConfig, BrokerState};
    use crate::vpn::fixtures::{host_route, proxy_route};
    use crate::vpn::Route;
    use std::sync::{Arc, Mutex};

    #[test]
    fn quic_runs_on_the_host_route_and_with_no_route() {
        assert!(quic_wanted(None, &host_route()));
        assert!(quic_wanted(None, &Route::None));
    }

    #[test]
    fn quic_is_off_on_the_proxy_route() {
        assert!(!quic_wanted(None, &proxy_route()));
    }

    #[test]
    fn the_disable_env_still_turns_quic_off() {
        assert!(!quic_wanted(Some("1"), &host_route()));
        assert!(!quic_wanted(Some("true"), &host_route()));
        assert!(quic_wanted(Some("0"), &host_route()));
    }

    #[test]
    fn offers_go_over_http_when_this_broker_runs_no_quic() {
        assert_eq!(offer_transport(false, 9001), OfferTransport::Http);
    }

    #[test]
    fn offers_use_quic_only_when_the_peer_advertises_a_port() {
        assert_eq!(offer_transport(true, 9001), OfferTransport::Quic(9001));
        assert_eq!(offer_transport(true, 0), OfferTransport::Http);
    }

    /// A broker with P2P on and no QUIC transport yet. The config keeps
    /// `enable_p2p` off so `with_config` scans nothing; the peer manager is
    /// swapped in afterwards.
    fn p2p_state(config: BrokerConfig) -> Arc<BrokerState> {
        let mut st = BrokerState::with_config(BrokerConfig {
            enable_p2p: false,
            ..config
        });
        st.peer_manager = PeerManager::new(Some("10.13.13.5"), &[], 9000, "k".into(), true);
        Arc::new(st)
    }

    fn offer(task_id: &str) -> task_board::TaskOffer {
        serde_json::from_str(&format!(
            r#"{{"task_id":"{task_id}","payload_b64":"","max_price_per_hour":100.0,"estimated_duration_secs":1.0,"timeout_secs":10.0,"requester_user_id":"u","source_broker":"n"}}"#
        ))
        .unwrap()
    }

    /// A fake peer broker on the proxy route: HTTP only, so `/peer/identity`
    /// advertises `quic_port` 0, and it accepts every offer. It records the
    /// path of each request it serves.
    fn spawn_http_peer() -> (String, Arc<Mutex<Vec<String>>>) {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let url = format!(
            "http://127.0.0.1:{}",
            server.server_addr().to_ip().unwrap().port()
        );
        let hits = Arc::new(Mutex::new(Vec::new()));
        let hits_srv = Arc::clone(&hits);
        std::thread::spawn(move || {
            for req in server.incoming_requests() {
                hits_srv.lock().unwrap().push(req.url().to_string());
                let body = if req.url() == "/peer/identity" {
                    r#"{"owner_user_id":"o","node_name":"proxy-peer","verified":false,"workers":[],"quic_port":0,"supports_two_phase":true}"#
                } else {
                    r#"{"task_id":"t-http","payload_b64":"","duration_ms":1.0,"actual_cost":0.0,"worker_name":"w","worker_uri":"zc://worker-aaaaaaaaaaaaaaaa-3960","price_per_hour":1.0,"executor_owner":"o"}"#
                };
                let resp = tiny_http::Response::from_data(body.as_bytes().to_vec()).with_header(
                    tiny_http::Header::from_bytes("Content-Type", "application/json").unwrap(),
                );
                let _ = req.respond(resp);
            }
        });
        (url, hits)
    }

    /// With no QUIC transport, as on the proxy route, an offer goes over HTTP
    /// even to a peer whose cached QUIC port is set: this broker has nothing to
    /// send QUIC with.
    #[test]
    fn with_no_quic_transport_an_offer_goes_over_http_despite_a_cached_quic_port() {
        let (peer_url, hits) = spawn_http_peer();
        let st = p2p_state(BrokerConfig::default());
        st.peer_manager.register_peer(peer_url.clone());
        st.peer_manager.set_quic_port(&peer_url, 9001);

        let (result, transport) = offer_to_peer(&st, None, &peer_url, &offer("t-http"));

        assert_eq!(transport, "http");
        assert_eq!(result.expect("the HTTP peer accepts").task_id, "t-http");
        assert_eq!(*hits.lock().unwrap(), vec!["/peer/tasks/offer".to_string()]);
    }

    /// R9 through the real path. A peer whose QUIC port is cached moved to
    /// the proxy route, and its `/peer/identity` now says `quic_port` 0.
    /// `discover_quic_ports` must clear the cached port, so even a broker
    /// that runs QUIC offers to that peer over HTTP. A failed handshake would
    /// leave the seeded port in place and fail this test.
    #[test]
    fn discovery_clears_the_cached_port_of_a_peer_advertising_quic_port_0() {
        let (peer_url, hits) = spawn_http_peer();
        let pm = PeerManager::new(Some("10.13.13.5"), &[], 9000, "k".into(), true);
        pm.register_peer(peer_url.clone());
        pm.set_quic_port(&peer_url, 9001);

        pm.discover_quic_ports();

        assert_eq!(*hits.lock().unwrap(), vec!["/peer/identity".to_string()]);
        assert_eq!(pm.get_quic_port(&peer_url), 0, "stale QUIC port survived");
        assert_eq!(
            offer_transport(true, pm.get_quic_port(&peer_url)),
            OfferTransport::Http
        );
    }

    /// A broker started on the proxy route runs no QUIC transport and
    /// advertises `quic_port` 0 in `/peer/identity`. `quic_port: Some(0)`
    /// asks for an ephemeral port, so a start that ignored the route would
    /// bind one and fail here instead of hiding behind a taken port.
    #[test]
    fn a_broker_on_the_proxy_route_starts_no_quic_and_advertises_quic_port_0() {
        let st = p2p_state(BrokerConfig {
            quic_port: Some(0),
            ..Default::default()
        });

        start_quic_transport(&st, &st.config, &proxy_route(), None);

        assert!(st.quic.get().is_none(), "QUIC started on the proxy route");
        let req = BrokerRequest {
            method: tiny_http::Method::Get,
            path: "/peer/identity".into(),
            query: "".into(),
            // A peer asks with the shared key, as `PeerClient::handshake` does.
            headers: vec![("X-Peer-Key".into(), "k".into())],
            body: vec![],
            peer_addr: None,
        };
        let resp = super::handle_peer_identity(&st, &req);
        assert_eq!(resp.status, 200);
        let id: task_board::PeerIdentity = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(id.quic_port, 0);
    }
}

/// Maximum accepted request-body size for synchronous HTTP endpoints.
/// Shared with the transport adapters so an over-cap body produces the
/// identical 413 regardless of frontend.
use super::http_adapter::MAX_BODY_BYTES;

/// Body access with the `MAX_BODY_BYTES` cap. The body is pre-read into
/// `BrokerRequest` by the transport adapter; this enforces the size cap,
/// returning a ready-to-send 413 when the body exceeds it.
fn body_or_413(req: &BrokerRequest) -> Result<&[u8], BrokerResponse> {
    if req.body.len() > MAX_BODY_BYTES {
        Err(error_response(
            "Request body too large",
            "PAYLOAD_TOO_LARGE",
            413,
        ))
    } else {
        Ok(&req.body)
    }
}

/// Authenticate via Bearer token. Returns zakuro_user_id (or "admin" for master key).
fn authenticate_bearer(
    request: &BrokerRequest,
    state: &BrokerState,
) -> Result<String, BrokerResponse> {
    match request.header("Authorization") {
        Some(auth) => match auth.strip_prefix("Bearer ") {
            Some(token) => state
                .ledger
                .resolve_user_from_api_key(token)
                .map_err(|e| error_response(&e.to_string(), e.auth_code(), e.auth_status())),
            None => Err(error_response(
                "Invalid Authorization header",
                "UNAUTHORIZED",
                401,
            )),
        },
        None => Err(error_response(
            "Authorization required. Set Authorization: Bearer <key>",
            "UNAUTHORIZED",
            401,
        )),
    }
}

/// Verify worker key header. Returns true if no key is configured OR the key matches.
fn verify_worker_key(request: &BrokerRequest, state: &BrokerState) -> bool {
    match &state.config.worker_key {
        None => true, // No key configured — allow (local dev)
        Some(expected) => request
            .header("X-Worker-Key")
            .map(|k| k == *expected)
            .unwrap_or(false),
    }
}

/// Key-derived node handle for this broker's own node: `zc://node-{fingerprint}`.
/// The `label` (e.g. hostname) is display-only and never part of the identity.
fn node_handle_for(key: &super::node_identity::NodeKey, _label: Option<&str>) -> String {
    key.node_uri()
}

fn worker_to_info(
    w: &worker::Worker,
    registry: &worker::WorkerRegistry,
    node_key: &super::node_identity::NodeKey,
    client_facing: bool,
    include_estimate: bool,
) -> WorkerInfo {
    use chrono::Duration as CDuration;
    let reqs_5h = registry.requests_in_window(&w.id, CDuration::hours(5));
    let reqs_1w = registry.requests_in_window(&w.id, CDuration::weeks(1));
    let reqs_1m = registry.requests_in_window(&w.id, CDuration::days(30));
    let quotas = registry.get_quotas(&w.id);
    // Node handle: a peer worker carries its source node; a local worker belongs
    // to this broker's node. Always a key-derived zc:// handle, never an IP or
    // hostname — the hostname (if any) only ever appears in `label`.
    let bare = |n: &str| n.strip_prefix("node-").unwrap_or(n).to_string();
    let node = Some(match &w.source_node {
        Some(n) => format!("zc://node-{}", bare(n)),
        None => node_handle_for(node_key, Some(&super::node_name_or_default())),
    });
    // Client-facing surfaces are IP-free: opaque zc:// uri, no wireguard_ip. The
    // peer channel keeps the real uri so peers can route.
    let (uri, wireguard_ip) = if client_facing {
        (w.zc_uri(), None)
    } else {
        (w.uri.clone(), w.wireguard_ip.clone())
    };
    WorkerInfo {
        id: w.id.clone(),
        name: w.name.clone(),
        uri,
        worker_type: w.worker_type.clone(),
        status: format!("{:?}", w.status).to_lowercase(),
        cpus_available: w.resources.cpus_available,
        cpus_total: w.resources.cpus_total,
        memory_available_gib: w.resources.memory_available as f64 / (1024.0 * 1024.0 * 1024.0),
        memory_total_gib: w.resources.memory_total as f64 / (1024.0 * 1024.0 * 1024.0),
        gpus_available: w.resources.gpus_available,
        gpus_total: w.resources.gpus_total,
        price_per_hour: w.pricing.price_per_hour,
        min_charge: w.pricing.min_charge,
        active_requests: w.active_requests,
        avg_latency_ms: w.avg_latency_ms,
        max_timeout_secs: w.max_timeout_secs,
        gpu_model: w.hardware.gpu_model.clone(),
        gpu_vram_gb: w.hardware.gpu_vram_gb,
        cpu_model: w.hardware.cpu_model.clone(),
        python_version: w.hardware.python_version.clone(),
        python_implementation: w.hardware.python_implementation.clone(),
        storage_gb: w.hardware.storage_gb,
        requests_5h: reqs_5h,
        requests_1w: reqs_1w,
        requests_1m: reqs_1m,
        quota_5h: quotas.per_5h,
        quota_1w: quotas.per_week,
        quota_1m: quotas.per_month,
        wireguard_ip,
        is_docker: w.is_docker,
        node,
        provider_type: w.provider_type,
        served_models: w.served_models.clone(),
        price_per_mtok: w.price_per_mtok,
        label: Some(w.name.clone()),
        estimate: include_estimate.then(|| WorkerEstimate::from(&w.stats)),
        // `atelier-runner=<url>` carries a mesh address; client-facing views
        // are IP-free (it is surfaced separately by `/route`).
        tags: w
            .tags
            .iter()
            .filter(|t| !(client_facing && t.starts_with("atelier-runner=")))
            .cloned()
            .collect(),
    }
}

/// Build this node's advertised endpoint from its mesh IP and bound port.
pub(crate) fn mesh_endpoint_for(mesh_ip: Option<String>, port: u16) -> Option<String> {
    mesh_ip.map(|ip| format!("{ip}:{port}"))
}

/// How often the node-sync tick's "no mesh endpoint" line may repeat while
/// the condition persists (it does not rate-limit the initial transition,
/// which always logs).
const NO_MESH_ENDPOINT_LOG_INTERVAL_SECS: u64 = 30 * 60;

/// What [`MeshEndpointLogGate::on_tick`] says to do this tick.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MeshEndpointLogAction {
    /// Nothing changed worth logging.
    None,
    /// No mesh endpoint this tick, and it's either a fresh transition or the
    /// rate-limit interval has elapsed — log loudly (error-ish, `eprintln!`).
    NoEndpoint,
    /// A mesh endpoint just reappeared after an absence — log a recovery
    /// line (info-ish, `println!`).
    Recovered,
}

/// Rate-limits the node-sync tick's "no mesh endpoint" log line.
///
/// The tick this feeds runs every 12 ticks (5s default interval) = every
/// ~60s, so an unconditional log there — Fix 1's failure mode when a broker
/// never gets a tunnel — fires forever, unrate-limited, straight to stderr:
/// a paging hazard if stderr is scraped. This keeps it loud on the
/// transition into/out of the no-endpoint state, then at most once every
/// [`NO_MESH_ENDPOINT_LOG_INTERVAL_SECS`] while it persists.
///
/// `/health`'s `mesh_tunnel` field is unaffected — it re-probes the mesh IP
/// on every request and stays the machine-readable signal regardless of this
/// gate's log suppression.
pub(crate) struct MeshEndpointLogGate {
    had_endpoint: AtomicBool,
    last_no_endpoint_log_secs: AtomicU64,
}

impl MeshEndpointLogGate {
    pub(crate) const fn new() -> Self {
        Self {
            // Optimistic default: a broker that has a tunnel from its very
            // first tick must not log a bogus "Recovered" line, so the
            // "previous" state is "had one".
            had_endpoint: AtomicBool::new(true),
            last_no_endpoint_log_secs: AtomicU64::new(0),
        }
    }

    /// Call once per node-sync tick with whether this tick has a mesh
    /// endpoint and the current unix time (injectable so tests don't depend
    /// on wall-clock timing).
    pub(crate) fn on_tick(&self, has_endpoint: bool, now_secs: u64) -> MeshEndpointLogAction {
        let had_before = self.had_endpoint.swap(has_endpoint, Ordering::SeqCst);
        if has_endpoint {
            return if had_before {
                MeshEndpointLogAction::None
            } else {
                MeshEndpointLogAction::Recovered
            };
        }
        if had_before {
            // Fresh transition into the no-endpoint state: always loud.
            self.last_no_endpoint_log_secs
                .store(now_secs, Ordering::SeqCst);
            return MeshEndpointLogAction::NoEndpoint;
        }
        let last = self.last_no_endpoint_log_secs.load(Ordering::SeqCst);
        if now_secs.saturating_sub(last) >= NO_MESH_ENDPOINT_LOG_INTERVAL_SECS {
            self.last_no_endpoint_log_secs
                .store(now_secs, Ordering::SeqCst);
            MeshEndpointLogAction::NoEndpoint
        } else {
            MeshEndpointLogAction::None
        }
    }
}

static MESH_ENDPOINT_LOG_GATE: MeshEndpointLogGate = MeshEndpointLogGate::new();

/// One peer the roster says this broker should dial: its key-derived
/// fingerprint plus the `http://`-prefixed base URL to reach it at.
///
/// The fingerprint travels WITH the URL because identity, not address, is
/// what the caller must reason about: the same physical broker is spelled
/// `http://zc-broker-1.zc-broker...:9000` by `ZAKURO_PEERS` and
/// `http://10.13.13.7:9000` by the roster, and only the fingerprint reveals
/// that those are one broker rather than two.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RosterPeer {
    /// Bare 16-hex-char fingerprint of the node's public key.
    pub fp: String,
    /// `http://ip:port` base URL, the spelling `PeerManager` registers under.
    pub url: String,
}

/// Turn a roster snapshot into the peers the node-sync tick loop should dial.
///
/// Non-revoked entries only, resolved to their advertised endpoint via
/// `endpoint_for_fingerprint` (which itself already excludes revoked nodes —
/// the `!revoked` filter here is a harmless, deliberately-kept double guard),
/// and empty/whitespace-only endpoints dropped so a malformed roster entry
/// never turns into a garbage `"http://"` peer.
///
/// # Excluding self
///
/// The primary self-filter is on IDENTITY: any roster row whose pubkey — or
/// whose pubkey's fingerprint — is this node's own is dropped, via
/// `self_pubkey`.
///
/// It must be identity-based, because the address-based filter fails in
/// precisely the case that matters. `self_endpoint` is derived from
/// `mesh_ip()`, so it is `None` exactly when this node's tunnel is down; but
/// registration deliberately treats an omitted endpoint as "unchanged", so
/// this node's own STALE endpoint is still sitting on the roster during that
/// flap. The address filter therefore switched itself off at the one moment
/// it had something to filter, and the broker registered itself as its own
/// peer: a self-dialing PeerClient, self health-checks, and a `zc brokers`
/// listing containing itself.
///
/// `self_endpoint` is still honoured as a second, belt-and-braces guard — it
/// costs nothing and covers a node whose roster row is somehow keyed by a
/// pubkey this process does not recognise as its own.
pub(crate) fn roster_peer_entries(
    cache: &super::roster_cache::RosterCache,
    self_pubkey: Option<&str>,
    self_endpoint: Option<&str>,
) -> Vec<RosterPeer> {
    let self_fp = self_pubkey.and_then(super::node_identity::fingerprint_of_pubkey_b64);
    cache
        .entries()
        .iter()
        .filter(|(_, revoked)| !revoked)
        // Identity self-filter (primary), on both the pubkey and its
        // fingerprint, independent of tunnel state.
        .filter(|(pk, _)| Some(pk.as_str()) != self_pubkey)
        .filter_map(|(pk, _)| {
            let fp = super::node_identity::fingerprint_of_pubkey_b64(pk)?;
            if self_fp.as_deref() == Some(fp.as_str()) {
                return None;
            }
            let addr = cache.endpoint_for_fingerprint(&fp)?;
            Some((fp, addr))
        })
        // Address self-filter (secondary), on the bare "ip:port" form that
        // `mesh_endpoint_for` produced for `self_endpoint`.
        .filter(|(_, addr)| Some(addr.as_str()) != self_endpoint)
        .filter(|(_, addr)| !addr.trim().is_empty())
        .map(|(fp, addr)| {
            let url = if addr.contains("://") {
                addr
            } else {
                format!("http://{addr}")
            };
            RosterPeer { fp, url }
        })
        .collect()
}

/// Merge one roster snapshot into the live peer set; returns the URLs of the
/// roster-derived peers evicted for having left the roster.
///
/// This is what makes a node that advertised its mesh endpoint AFTER this
/// broker started reachable without restarting either side: the node-sync tick
/// runs it every round against a freshly fetched roster.
///
/// Callers must have resolved configured peers' identities
/// (`PeerManager::ensure_fingerprints_cached`) BEFORE calling this — the dedup
/// below asks `configured_url_for_fingerprint` whether a roster row is just a
/// second spelling of a `ZAKURO_PEERS` peer, and an unprobed configured peer
/// answers `None`.
pub(crate) fn merge_roster_peers(
    peer_manager: &super::peer::PeerManager,
    roster_peers: &[RosterPeer],
) -> Vec<String> {
    let mut keep: std::collections::HashSet<String> = std::collections::HashSet::new();
    for rp in roster_peers {
        // Same broker already registered under its configured spelling: keep
        // that one and add nothing. Omitting the roster spelling from `keep`
        // also evicts a duplicate that an earlier round registered while this
        // peer was still unreachable (below).
        if peer_manager
            .configured_url_for_fingerprint(&rp.fp)
            .is_some()
        {
            continue;
        }
        // Either a genuinely new broker, or a configured peer whose
        // fingerprint is not resolved yet (never successfully probed).
        // Register the roster spelling: an unresolved fingerprint is a
        // REACHABILITY failure, and treating it as "different broker" is the
        // safe direction — the alternative is refusing to dial a peer we
        // cannot yet identify. Any duplicate this creates is bounded by the
        // roster size (registration is idempotent, so this cannot loop) and is
        // reconciled away on the first round after the configured peer answers
        // a probe.
        peer_manager.register_roster_peer(rp.url.clone());
        // Seed the peer's key-derived identity from the roster row that just
        // supplied its address. Registering the URL alone does NOT make a peer
        // routable: everything that addresses a broker by identity reads
        // `PeerClient::fingerprint()`, and until a signed `/peer/health` probe
        // lands that is `None` — so `/brokers` omits the peer entirely, and
        // `get_url_for_fingerprint` resolves nothing for it (the executor-
        // settlement lookup then pays nobody for real remote work). A broker
        // whose probes are failing never learns it at all, leaving a node that
        // joined the mesh after this process started invisible indefinitely.
        // `PeerManager::load_persisted_from` already seeds identity the same
        // way from `peers.json`; the roster path is strictly better evidence
        // (it is the hub's live answer, and `rp.fp` is derived from the very
        // roster entry that supplied `rp.url`, so this asserts nothing the
        // address did not already assert).
        //
        // Gap-filling only. A fingerprint some probe actually observed is
        // never overwritten: a probe reports who IS at that address, the
        // roster only who SHOULD be, and the probe must win if they disagree.
        // Seeding also never marks the peer reachable — that still takes a
        // successful probe, so an unreachable node cannot be offered work on
        // the strength of a roster row alone.
        if peer_manager.peer_fingerprint(&rp.url).is_none() {
            peer_manager.set_peer_fingerprint(&rp.url, &rp.fp);
        }
        keep.insert(rp.url.clone());
    }

    // Peers are removable, not just addable: a roster-derived peer that has
    // left the roster is dropped instead of being health-checked forever.
    // ZAKURO_PEERS-configured peers are never evicted (enforced inside
    // `remove_roster_peer`), so a roster carrying no endpoints leaves the
    // cluster-native fallback exactly as it was.
    peer_manager.retain_roster_peers(&keep)
}

pub fn handle(state: Arc<BrokerState>, req: &BrokerRequest, verbose: bool) -> BrokerResponse {
    // Reconstruct the full request target (path + query) so the existing
    // string-based route matching (e.g. `/stats?user=`, `/peer/balance?...`)
    // behaves exactly as it did against tiny_http's `request.url()`.
    let path = if req.query.is_empty() {
        req.path.clone()
    } else {
        format!("{}?{}", req.path, req.query)
    };
    let method = req.method.clone();

    let response = match (method, path.as_str()) {
        // Deployment-reconciler reverse proxy: ANY method, `/serve/:id/*path`.
        // Matched by prefix (not an exact path) since the tail is arbitrary —
        // see `deploy::serve::parse_serve_path`. Kept ahead of every other
        // arm below since none of them use this prefix, so ordering here is
        // just for readability, not correctness.
        (_, p) if p.starts_with("/serve/") => super::deploy::serve::handle_serve(&state, req),

        // The adaptive policy's shadow ledger (ZC-0011, zc#365): what it would
        // have saved against the live routing, since this broker started.
        // Aggregates only -- no worker, user or address -- so it sits beside
        // /health and /workers without a key.
        (Method::Get, "/shadow") => {
            json_response(&state.shadow.snapshot(adaptive_routing_enabled()), 200)
        }

        // Health check
        (Method::Get, "/health") => {
            // Re-probe the WireGuard mesh IP on every health check (the tunnel may
            // come up after startup). WireGuard is decommissioned; mesh = 10.13.13.0/24.
            //
            // Fix E: `wireguard_connected` and `mesh_tunnel` are two renderings
            // of THIS ONE value, never two independent probes. They used to be
            // computed from two different detectors -- `discovery::get_mesh_ip()`
            // here and `vpn::native::mesh_ip()` below -- which disagreed in
            // exactly the container this endpoint is scraped in, so /health
            // contradicted itself. Fix A made those detectors the same function;
            // sharing the resolved value here makes the contradiction
            // structurally impossible rather than merely unlikely, including via
            // the `own_wireguard_ip` fallback (which `mesh_tunnel` never saw).
            let live_ts_ip =
                super::discovery::get_mesh_ip().or_else(|| state.own_wireguard_ip.clone());
            let ts_connected = live_ts_ip
                .as_ref()
                .map(|ip| ip.starts_with("10.13.13."))
                .unwrap_or(false);
            // Client body is IP-free: report connectivity as a bool, never the
            // raw mesh IP. `node_name` may stay — display label only, never
            // used for resolution/routing.
            json_response(
                &serde_json::json!({
                    "status": "healthy",
                    "service": "zakuro-broker",
                    "wireguard_connected": ts_connected,
                    "node_name": state.config.node_name,
                    // Key-derived identity (not an address): lets `zc://node-<fp>`
                    // resolve against a local broker by id, and `zc brokers`
                    // recognise this machine's own broker in the directory.
                    "node_id": state.node_key.node_uri(),
                    "mesh_tunnel": if ts_connected { "up" } else { "down" },
                    // Which zc binary is answering (zc#305). Address-free and
                    // secret-free, so it is safe on this client-facing body,
                    // and it is what lets a scraper reconcile mesh-wide skew
                    // without a key.
                    "build": crate::build_id::current(),
                    // Which account owns this node. A marketplace has to be
                    // able to say whose machine it is offering, and `zc ls` /
                    // `zc brokers` have to be able to show it without a peer
                    // key — `/peer/identity` carries it but is authenticated.
                    // It is an opaque account id, never an email or an address,
                    // so it does not widen what this body already discloses
                    // beyond the node's own identity. `null` when the broker
                    // has no owner configured, which is itself worth seeing.
                    "owner_user_id": state.config.owner_user_id,
                    // Transactions permanently given up on since this broker
                    // started. Non-zero means money that was owed was never
                    // recorded — and every other signal a node has (agent
                    // status, this endpoint's `status`, `zc bench`'s billed
                    // column) reads exactly the same whether it is 0 or
                    // 475 MB worth (#330). `status` is deliberately left
                    // alone so existing scrapers keep their meaning.
                    "settlement_quarantined": state.tx_buffer.total_quarantined(),
                    // Transactions charged to a client and not yet delivered,
                    // and how long since the flush path last ran at all.
                    //
                    // Quarantine counts what a broker gave up on. These two
                    // count the case it could not see: on #341 the flush
                    // shared a thread with blocking hub calls, that thread
                    // wedged, and for eight hours this broker charged for work
                    // it never delivered. `settlement_quarantined` stayed 0 —
                    // nothing had failed, nothing had run — and `/health` said
                    // `ok` throughout. `settlement_pending` climbing while
                    // `settlement_last_flush_secs` grows is that state, and it
                    // is visible here without the admin key `/ledger/status`
                    // demands.
                    "settlement_pending": state.tx_buffer.pending_count(),
                    "settlement_last_flush_secs": state.tx_buffer.seconds_since_flush(),
                    // Opt-in self-update (ZAKURO_AUTO_UPDATE); see `auto_update`.
                    "auto_update": super::auto_update::health_json(),
                }),
                200,
            )
        }

        // Stats endpoint (supports ?user= filter)
        (Method::Get, path) if path == "/stats" || path.starts_with("/stats?") => {
            // Require Bearer auth
            match authenticate_bearer(req, &state) {
                Err(resp) => resp,
                Ok(caller) => {
                    let is_admin = caller == "admin";

                    // Parse ?user= query parameter
                    let mut user_filter: Option<String> = path.find('?').and_then(|qpos| {
                        let query = &path[qpos + 1..];
                        query
                            .split('&')
                            .find(|p| p.starts_with("user="))
                            .map(|p| p[5..].to_string())
                    });

                    // Non-admin callers can only see their own transactions
                    if !is_admin {
                        user_filter = Some(caller.clone());
                    }

                    let workers = state.workers.list();
                    let active = workers
                        .iter()
                        .filter(|w| w.status == WorkerStatus::Healthy)
                        .count();

                    let worker_stats: Vec<WorkerStats> = workers
                        .iter()
                        .map(|w| WorkerStats {
                            id: w.id.clone(),
                            name: w.name.clone(),
                            // Client-facing: key-derived zc:// uri, never the raw
                            // mesh uri (which leaks the 10.13.13.x IP).
                            uri: w.zc_uri(),
                            status: format!("{:?}", w.status).to_lowercase(),
                            cpus_available: w.resources.cpus_available,
                            memory_available_gib: w.resources.memory_available as f64
                                / (1024.0 * 1024.0 * 1024.0),
                            gpus_available: w.resources.gpus_available,
                            price_per_hour: w.pricing.price_per_hour,
                            active_requests: w.active_requests,
                            avg_latency_ms: w.avg_latency_ms,
                        })
                        .collect();

                    // Connectivity is reported as a bool only; the raw mesh IP
                    // (10.13.13.x) is never placed in the client-facing body.
                    let wireguard_connected = state.own_wireguard_ip.is_some();
                    let metrics = state.stats.metrics(
                        active,
                        workers.len(),
                        state.is_local_mode(),
                        state.is_billing_enabled(),
                        None,
                    );

                    let mut transactions = state.stats.recent_transactions(50);
                    if let Some(ref uid) = user_filter {
                        transactions.retain(|tx| tx.user_id == *uid);
                    }

                    let stats_resp = StatsResponse {
                        host: state.config.host.clone(),
                        port: state.config.port,
                        transactions,
                        task_offers: state.stats.recent_task_offers(30),
                        workers: worker_stats,
                        metrics,
                        rps_history: state.stats.rps_history(),
                        wireguard_ip: None,
                        wireguard_connected,
                    };

                    json_response(&stats_resp, 200)
                }
            }
        }

        // List workers
        (Method::Get, path) if path == "/workers" || path.starts_with("/workers?") => {
            // Optional `?node=zc://node-{fingerprint}` (or bare `node-{fingerprint}`)
            // filter. Resolved by fingerprint only (node_identity::fp_matches_node_arg) —
            // a hostname/label never matches, even if it happens to look like a handle.
            let node_filter = req.query.split('&').find_map(|kv| kv.strip_prefix("node="));
            // Opt-in: the posterior is the broker's own estimate, not part of
            // a worker's advertised identity, and costs a field per worker on
            // every response, so it rides along only when asked for.
            let include_estimate = req
                .query
                .split('&')
                .any(|kv| matches!(kv, "estimate=1" | "estimate=true"));
            // A reserved P2P offer counts as activity until its commit runs:
            // the local agent reads this count before stopping a draining worker.
            let reserved = pending_reservations(&state);
            let infos: Vec<WorkerInfo> = state
                .workers
                .list()
                .iter()
                .map(|w| {
                    let mut info =
                        worker_to_info(w, &state.workers, &state.node_key, true, include_estimate);
                    info.active_requests += reserved.get(&w.id).copied().unwrap_or(0);
                    info
                })
                .filter(|wi| {
                    node_filter.is_none_or(|nf| {
                        wi.node.as_deref().is_some_and(|n| {
                            node_identity::fp_matches_node_arg(node_identity::strip_node_arg(n), nf)
                        })
                    })
                })
                .collect();

            json_response(
                &WorkerListResponse {
                    total: infos.len(),
                    workers: infos,
                },
                200,
            )
        }

        // Register worker (requires worker key when configured)
        (Method::Post, "/workers") => {
            if !verify_worker_key(req, &state) {
                error_response(
                    "Worker key required. Set X-Worker-Key header",
                    "UNAUTHORIZED",
                    401,
                )
            } else {
                match body_or_413(req) {
                    Err(resp) => resp,
                    Ok(body) => match serde_json::from_slice::<WorkerRegistration>(body) {
                        Ok(registration) => {
                            if registration.pricing.price_per_hour < 0.0 {
                                error_response("price_per_hour must be >= 0", "BAD_REQUEST", 400)
                            } else {
                                println!(
                                    "  [BROKER] Registering worker: {} at {}",
                                    registration.name, registration.uri
                                );
                                let mut worker = state.workers.register(registration);
                                // Locally-registered workers (no source_node) belong to
                                // this broker's node: stamp its key-derived fingerprint
                                // so worker.zc_uri() is `zc://worker-{node_fp}-{slot}`.
                                if worker.source_node.is_none() {
                                    if let Some(updated) = state
                                        .workers
                                        .set_node_fp(&worker.id, &state.node_key.fingerprint())
                                    {
                                        worker = updated;
                                    }
                                }

                                // Sync worker immediately (don't wait for periodic sync)
                                if let Some(ref owner_id) = state.config.owner_user_id {
                                    let node_name = state.config.node_name.as_deref();
                                    let node_pubkey = state.node_key.public_b64();

                                    // Prefer API sync if configured
                                    if let (Some(ref api_url), Some(ref api_key)) =
                                        (&state.config.api_url, &state.config.api_key)
                                    {
                                        match super::ledger::Ledger::sync_workers_via_api(
                                            owner_id,
                                            std::slice::from_ref(&worker),
                                            api_url,
                                            api_key,
                                            node_name,
                                            state.own_wireguard_ip.as_deref(),
                                            Some(node_pubkey.as_str()),
                                        ) {
                                            Ok(outcome) => {
                                                state.workers.apply_hub_prices(&outcome.prices);
                                                println!("  [WORKER_SYNC] Worker {} synced to dashboard via API", worker.name)
                                            }
                                            Err(e) => {
                                                eprintln!(
                                                    "  [WORKER_SYNC] API sync failed for {}: {}",
                                                    worker.name, e
                                                );
                                            }
                                        }
                                    }
                                }
                                json_response(&worker, 201)
                            } // else
                        }
                        Err(e) => {
                            error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400)
                        }
                    },
                }
            }
        }

        // Worker heartbeat (requires worker key when configured)
        (Method::Post, "/workers/heartbeat") => {
            if !verify_worker_key(req, &state) {
                error_response(
                    "Worker key required. Set X-Worker-Key header",
                    "UNAUTHORIZED",
                    401,
                )
            } else {
                match body_or_413(req) {
                    Err(resp) => resp,
                    Ok(body) => match serde_json::from_slice::<WorkerHeartbeat>(body) {
                        Ok(heartbeat) => match state.workers.heartbeat(heartbeat) {
                            Some(worker) => json_response(
                                &serde_json::json!({"status": "ok", "worker_id": worker.id}),
                                200,
                            ),
                            None => error_response("Worker not found", "NOT_FOUND", 404),
                        },
                        Err(e) => {
                            error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400)
                        }
                    },
                }
            }
        }

        // Placement dry run (atelier phase-1 — zc#345 §4): runs the
        // real router end to end — same filtering, same strategy ranking
        // — and returns what it WOULD choose, without executing,
        // reserving, billing or mutating anything (no quota reservation, no
        // round-robin cursor advance, no in-flight counters touched).
        // Unauthenticated like `/price`: it discloses no more than `/workers`
        // already does.
        //
        // `chosen` is the policy's first eligible choice, not a dispatch
        // guarantee: the live `/execute` path retries past a first choice
        // that turns out to be at quota and tries the rest (see
        // `Router::select`'s `first_choice_was_full`), which this preview
        // has no request to reserve against and so cannot reproduce.
        (Method::Post, "/route") => match body_or_413(req) {
            Err(resp) => resp,
            Ok(body) => match serde_json::from_slice::<ResourceRequirements>(body) {
                Ok(requirements) => match state.router.route_dry_run(&state.workers, &requirements)
                {
                    Ok(result) => {
                        let candidates: Vec<RouteCandidateView> = result
                            .candidates
                            .iter()
                            .map(|c| route_candidate_view(c, &state.node_key))
                            .collect();
                        match result.chosen {
                            Some(ref chosen) if !candidates.is_empty() => json_response(
                                &RouteResponse {
                                    strategy: result.strategy.as_str().to_string(),
                                    chosen: route_candidate_view(chosen, &state.node_key),
                                    candidates,
                                    excluded: result.excluded,
                                },
                                200,
                            ),
                            // Every healthy worker was excluded: a 404-shaped
                            // error, but still carrying `excluded` so the
                            // caller can see why.
                            _ => json_response(
                                &serde_json::json!({
                                    "error": "No eligible worker for these requirements",
                                    "code": "NO_CAPACITY",
                                    "strategy": result.strategy.as_str(),
                                    "excluded": result.excluded,
                                }),
                                404,
                            ),
                        }
                    }
                    Err(e) => error_response(&e.message, &e.code, 404),
                },
                Err(e) => error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400),
            },
        },

        // Price estimation
        (Method::Post, "/price") => match body_or_413(req) {
            Err(resp) => resp,
            Ok(body) => match serde_json::from_slice::<ResourceRequirements>(body) {
                Ok(requirements) => {
                    match state.router.estimate_cost(&state.workers, &requirements) {
                        Some((min_cost, max_cost)) => {
                            let matching =
                                state.router.list_matching(&state.workers, &requirements);
                            json_response(
                                &PriceEstimateResponse {
                                    min_cost,
                                    max_cost,
                                    matching_workers: matching.len(),
                                },
                                200,
                            )
                        }
                        None => error_response("No workers available", "NO_CAPACITY", 503),
                    }
                }
                Err(e) => error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400),
            },
        },

        // Peer list — this node's known peers, for transitive network discovery.
        // Unauthenticated (topology only, no secrets): crawl a node, get its
        // peers, recurse to map the whole mesh.
        (Method::Get, "/peers") => {
            // Topology is sensitive: gate with the same handshake auth as
            // /peer/health|identity — a configured peer key is required;
            // keyless brokers still answer from loopback for local discovery
            // (audit M4: was unauthenticated reconnaissance).
            //
            // IP-free: like /brokers, this must never expose peer_url/IP or
            // this node's hostname to a client-facing caller — the auth gate
            // here (peer_handshake_auth) is a shared-secret/loopback check,
            // not true peer identity auth, so this endpoint is effectively
            // client-reachable. Peer entries and self are both reduced to
            // key-derived `zc://node-<fp>` ids via the same PeerManager
            // fingerprint cache that handle_brokers uses.
            match peer_handshake_auth(&state, req) {
                Some(resp) => resp,
                None => {
                    state.peer_manager.ensure_fingerprints_cached();

                    let mut peer_urls = state.peer_manager.peer_urls();
                    peer_urls.sort();

                    let peers: Vec<String> = peer_urls
                        .into_iter()
                        .filter_map(|url| state.peer_manager.peer_fingerprint(&url))
                        .collect();

                    json_response(
                        &serde_json::json!({
                            "node": state.node_key.node_uri(),
                            "p2p_enabled": state.peer_manager.is_enabled(),
                            "peers": peers,
                            "total": peers.len(),
                        }),
                        200,
                    )
                }
            }
        }

        // Brokers list — client-facing, IP-free primitive: "which brokers
        // does this node talk to". Unauthenticated (identity only, no
        // secrets, no IPs — same threat model as /peers' topology, but with
        // the peer_url/IP redacted down to a key-derived id).
        (Method::Get, "/brokers") => handle_brokers(&state),

        // Broker-advertised price `P` (credits/hour). GET is client-facing
        // (IP-free, no secrets). Note: `POST /price` is already taken by the
        // pre-existing cost-estimation endpoint below (takes
        // `ResourceRequirements`, unrelated to this broker's own price), so
        // the setter lives at `POST /price/set` to avoid colliding with it.
        // Gated loopback-only so a remote peer can never set this broker's
        // price for it.
        (Method::Get, "/price") => handle_get_price(&state),

        (Method::Post, "/price/set") => handle_set_price(&state, req),

        // --- Peer-to-peer broker endpoints (authenticated via X-Peer-Key) ---
        (Method::Get, "/peer/health") => handle_peer_health(&state, req),

        (Method::Get, "/peer/workers") => handle_peer_workers(&state, req),

        // Signed full-set peer gossip — roster-gated (see handle_peer_peers).
        (Method::Get, "/peer/peers") => handle_peer_peers(&state, req),

        // Signed price+resources advertisement — roster-gated (see handle_peer_advert).
        (Method::Get, "/peer/advert") => handle_peer_advert(&state, req),

        (Method::Post, "/peer/reserve") => handle_peer_reserve(state.clone(), req),

        (Method::Post, "/peer/commit") => handle_peer_commit(state.clone(), req),

        (Method::Post, "/peer/cancel") => handle_peer_cancel(state.clone(), req),

        (Method::Get, p) if p.starts_with("/peer/balance") => handle_peer_balance(&state, req),

        (Method::Post, "/peer/earn") => handle_peer_earn(state.clone(), req),

        // Peer identity — handshake endpoint
        (Method::Get, "/peer/identity") => handle_peer_identity(&state, req),

        // Peer task offer — publish-lock execution
        (Method::Post, "/peer/tasks/offer") => handle_peer_task_offer(state.clone(), req),
        (Method::Post, "/peer/tasks/commit") => handle_peer_task_commit(state.clone(), req),
        (Method::Post, "/peer/tasks/cancel") => handle_peer_task_cancel(state.clone(), req),

        // Model inference - forward a one-shot OpenAI chat completion to a resolved provider
        (Method::Post, "/infer") => handle_infer(&state, req),

        // Execute - main entry point
        (Method::Post, "/execute") => handle_execute(state, req, verbose),

        // List active instances (admin only)
        (Method::Get, "/instances") => match authenticate_bearer(req, &state) {
            Err(resp) => resp,
            Ok(caller) if caller != "admin" => {
                error_response("Forbidden: admin only", "FORBIDDEN", 403)
            }
            Ok(_) => {
                let instances: Vec<serde_json::Value> = state
                    .instance_registry
                    .list()
                    .into_iter()
                    .map(|(instance_id, worker_id)| {
                        serde_json::json!({
                            "instance_id": instance_id,
                            "worker_id": worker_id,
                        })
                    })
                    .collect();
                json_response(
                    &serde_json::json!({
                        "instances": instances,
                        "total": instances.len(),
                    }),
                    200,
                )
            }
        },

        // Delete an instance binding (admin only)
        (Method::Delete, path) if path.starts_with("/instances/") => {
            match authenticate_bearer(req, &state) {
                Err(resp) => resp,
                Ok(caller) if caller != "admin" => {
                    error_response("Forbidden: admin only", "FORBIDDEN", 403)
                }
                Ok(_) => {
                    let instance_id = path.trim_start_matches("/instances/");
                    match state.instance_registry.remove(instance_id) {
                        Some(_) => json_response(
                            &serde_json::json!({"status": "ok", "instance_id": instance_id}),
                            200,
                        ),
                        None => error_response("Instance not found", "NOT_FOUND", 404),
                    }
                }
            }
        }

        // Get credits (uses ledger) — requires Bearer, scoped to own user or admin
        (Method::Get, path) if path.starts_with("/credits/") && !path.contains("/add") => {
            match authenticate_bearer(req, &state) {
                Err(resp) => resp,
                Ok(caller) => {
                    let user_id = path.trim_start_matches("/credits/");
                    if caller != "admin" && caller != user_id {
                        error_response("Forbidden: can only view own balance", "FORBIDDEN", 403)
                    } else {
                        let info = state.ledger.get_user_info(user_id);
                        let credits = state.credits.get(info.user_id.as_str());
                        // Use live in-memory balance when available (reflects in-flight deductions)
                        let live_balance =
                            credits.as_ref().map(|c| c.balance).unwrap_or(info.balance);
                        json_response(
                            &serde_json::json!({
                                "user_id": info.user_id,
                                "balance": live_balance,
                                "balance_status": credits.as_ref().map(|c| c.balance_status.as_str()).unwrap_or("authoritative"),
                                "last_prefetched": credits.as_ref().and_then(|c| c.last_prefetched).map(|t| t.to_rfc3339()),
                            }),
                            200,
                        )
                    }
                }
            }
        }

        // Add credits (REQUIRES API KEY - uses ledger)
        (Method::Post, path) if path.starts_with("/credits/") && path.ends_with("/add") => {
            let user_id = path
                .trim_start_matches("/credits/")
                .trim_end_matches("/add");

            // Require API key for adding credits
            if let Some(api_key) = req.header("X-Api-Key") {
                match body_or_413(req) {
                    Err(resp) => resp,
                    Ok(body) => match serde_json::from_slice::<AddCreditsRequest>(body) {
                        Ok(req) => {
                            // In standalone mode (no dashboard API), allow seeding local credits
                            // with the ZAKURO_MASTER_KEY. This enables test environments and
                            // standalone deployments without a dashboard.
                            if state.ledger.is_api_mode() {
                                error_response("Adding credits directly via broker is not supported in API mode. Use the dashboard API.", "NOT_SUPPORTED", 501)
                            } else {
                                // In standalone mode: verify master key from env, or allow any
                                // key when no master key is configured (test/dev environments).
                                let master_key =
                                    std::env::var("ZAKURO_MASTER_KEY").unwrap_or_default();
                                let authorized = master_key.is_empty() || api_key == master_key;
                                if !authorized {
                                    error_response("Invalid master key", "UNAUTHORIZED", 401)
                                } else {
                                    let new_balance = {
                                        let mut entry = state
                                            .ledger
                                            .local_credits
                                            .entry(user_id.to_string())
                                            .or_insert(0.0);
                                        *entry += req.amount;
                                        *entry
                                    };
                                    // Keep authoritative_balances in sync so /me and P2P path
                                    // see the correct balance immediately after adding credits.
                                    state
                                        .ledger
                                        .authoritative_balances
                                        .entry(user_id.to_string())
                                        .and_modify(|b| *b += req.amount)
                                        .or_insert(new_balance);
                                    state.ledger.publish_transaction(
                                        &uuid::Uuid::new_v4().to_string(),
                                        user_id,
                                        "credit",
                                        req.amount,
                                        new_balance,
                                        WorkerName::none(),
                                        0.0,
                                        state.config.node_name.as_deref(),
                                    );
                                    json_response(
                                        &serde_json::json!({
                                            "status": "ok",
                                            "new_balance": new_balance,
                                            "ledger": "local"
                                        }),
                                        200,
                                    )
                                }
                            }
                        }
                        Err(e) => {
                            error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400)
                        }
                    },
                }
            } else {
                error_response(
                    "API key required. Set X-Api-Key header with ZAKURO_MASTER_KEY",
                    "UNAUTHORIZED",
                    401,
                )
            }
        }

        // Ledger status — requires master key (Bearer or X-Api-Key), redacts password
        (Method::Get, "/ledger/status") => match authenticate_bearer(req, &state) {
            Err(resp) => resp,
            Ok(caller) if caller != "admin" => {
                error_response("Forbidden: admin only", "FORBIDDEN", 403)
            }
            Ok(_) => json_response(
                &serde_json::json!({
                    "api_mode": state.ledger.is_api_mode(),
                }),
                200,
            ),
        },

        // Drain a worker (loopback-only): stop routing new work to it.
        (Method::Post, path) if path.starts_with("/workers/") && path.ends_with("/drain") => {
            let worker_id = path
                .trim_start_matches("/workers/")
                .trim_end_matches("/drain");
            handle_drain_worker(&state, req, worker_id)
        }

        // Delete worker (requires worker key when configured)
        (Method::Delete, path) if path.starts_with("/workers/") => {
            if !verify_worker_key(req, &state) {
                error_response(
                    "Worker key required. Set X-Worker-Key header",
                    "UNAUTHORIZED",
                    401,
                )
            } else {
                let worker_id = path.trim_start_matches("/workers/");
                match state.workers.remove(worker_id) {
                    Some(worker) => {
                        println!("  [BROKER] Worker unregistered: {}", worker_id);
                        json_response(
                            &serde_json::json!({"status": "ok", "worker_id": worker.id}),
                            200,
                        )
                    }
                    None => error_response("Worker not found", "NOT_FOUND", 404),
                }
            }
        }

        // Quota usage (authenticated) — returns current rate limit counters
        (Method::Get, "/quotas") => {
            match authenticate_bearer(req, &state) {
                Err(resp) => resp,
                Ok(caller) => {
                    let user_credits = state.credits.get(&caller);
                    let now = chrono::Utc::now();
                    match user_credits {
                        Some(uc) => {
                            // Calculate seconds until each window resets
                            let sec_reset = 1.0_f64
                                - now
                                    .signed_duration_since(uc.second_window_start)
                                    .num_milliseconds() as f64
                                    / 1000.0;
                            let day_reset = 86400.0
                                - now.signed_duration_since(uc.day_window_start).num_seconds()
                                    as f64;
                            let month_reset = 2_592_000.0
                                - now
                                    .signed_duration_since(uc.month_window_start)
                                    .num_seconds() as f64;

                            json_response(
                                &serde_json::json!({
                                    "user_id": caller,
                                    "rate_limit_per_second": uc.rate_limit_per_second,
                                    "rate_limit_per_day": uc.rate_limit_per_day,
                                    "rate_limit_per_month": uc.rate_limit_per_month,
                                    "requests_this_second": uc.requests_this_second,
                                    "requests_this_day": uc.requests_this_day,
                                    "requests_this_month": uc.requests_this_month,
                                    "seconds_until_second_reset": sec_reset.max(0.0),
                                    "seconds_until_day_reset": day_reset.max(0.0),
                                    "seconds_until_month_reset": month_reset.max(0.0),
                                }),
                                200,
                            )
                        }
                        None => json_response(
                            &serde_json::json!({
                                "user_id": caller,
                                "rate_limit_per_second": serde_json::Value::Null,
                                "rate_limit_per_day": serde_json::Value::Null,
                                "rate_limit_per_month": serde_json::Value::Null,
                                "requests_this_second": 0,
                                "requests_this_day": 0,
                                "requests_this_month": 0,
                                "seconds_until_second_reset": 0,
                                "seconds_until_day_reset": 0,
                                "seconds_until_month_reset": 0,
                            }),
                            200,
                        ),
                    }
                }
            }
        }

        // User info (authenticated)
        (Method::Get, "/me") => {
            if let Some(auth) = req.header("Authorization") {
                match auth.strip_prefix("Bearer ") {
                    Some(token) => match state.ledger.resolve_user_from_api_key(token) {
                        Ok(uid) => {
                            let balance = state.ledger.load_balance_if_needed(&uid);
                            json_response(
                                &serde_json::json!({
                                    "user_id": uid,
                                    "balance": balance,
                                    "local_mode": state.is_local_mode(),
                                }),
                                200,
                            )
                        }
                        Err(e) => error_response(&e.to_string(), e.auth_code(), e.auth_status()),
                    },
                    None => error_response("Invalid Authorization header", "UNAUTHORIZED", 401),
                }
            } else {
                error_response(
                    "API key required. Set Authorization: Bearer <key>",
                    "UNAUTHORIZED",
                    401,
                )
            }
        }

        // Not found
        _ => error_response("Not found", "NOT_FOUND", 404),
    };

    response
}

// --- Peer endpoint handlers ---

/// Fail-closed auth for the P2P **credit surface** (reserve/commit/cancel/
/// earn/balance/workers/tasks-offer). A valid X-Peer-Key is ALWAYS required;
/// `verify_peer_key` denies when no key is configured, so a keyless broker
/// refuses to serve these endpoints entirely. Returns `Some(401)` to reject,
/// `None` when authorized.
fn peer_credit_auth(state: &Arc<BrokerState>, request: &BrokerRequest) -> Option<BrokerResponse> {
    // Zero-trust per-node signature gate. Permissive by default (logs and allows)
    // so a mixed/upgrading mesh keeps working; enforced when ZAKURO_ENFORCE_NODE_SIG
    // is set. Retires ZAKURO_PEER_KEY as the identity gate once enforced.
    if let Some(reject) = node_sig_gate(state, request) {
        return Some(reject);
    }
    if peer::verify_peer_key(
        request.header("X-Peer-Key").as_deref(),
        state.peer_manager.peer_key(),
    ) {
        None
    } else {
        Some(error_response(
            "Peer authentication required (set ZAKURO_PEER_KEY and send X-Peer-Key)",
            "UNAUTHORIZED",
            401,
        ))
    }
}

/// Testable core of the node-signature gate. Returns `Ok(signer_pubkey)` when the
/// request carries a valid signature from a rostered node; `Err(reason)` otherwise.
/// Pure — no env, no I/O — so it can be unit-tested with a hand-built request.
fn check_node_sig(
    roster: &dashmap::DashMap<String, bool>,
    guard: &node_identity::ReplayGuard,
    request: &BrokerRequest,
    now: u64,
) -> Result<String, String> {
    // `revoked == false` → authorized; absent → not rostered.
    let is_rostered = |id: &str| roster.get(id).map(|r| !*r.value()).unwrap_or(false);
    let header = |name: &str| request.header(name);
    let method = format!("{:?}", request.method).to_uppercase(); // "GET"/"POST"
    node_identity::verify_request(
        &is_rostered,
        guard,
        &method,
        &request.path,
        &request.body,
        &header,
        now,
    )
}

/// Whether dashboard-signed job vouchers are required (issued on dispatch and
/// verified on receipt). Off by default — zero added latency and no behavior change.
/// Are dashboard vouchers required for remote/foreign jobs on this broker?
/// `ZAKURO_REQUIRE_VOUCHER=1|true`. The fleet sets it explicitly; brokers
/// started from the CLI get it defaulted on whenever billing credentials are
/// present (`broker::apply_user_broker_defaults`), so a user broker mints
/// when it dispatches to the fleet, which rejects unvouched offers with 402.
fn voucher_required() -> bool {
    std::env::var("ZAKURO_REQUIRE_VOUCHER")
        .map(|v| v == "1" || v == "true")
        .unwrap_or(false)
}

/// The `task_nonce` inside the offer's voucher `signed_json`, or `None` when
/// the offer carries no (parseable) voucher. Sent to the hub as
/// `voucher_nonce` (zc#400).
fn offer_voucher_nonce(offer: &task_board::TaskOffer) -> Option<String> {
    serde_json::from_str::<serde_json::Value>(&offer.voucher_signed_json)
        .ok()?
        .get("task_nonce")
        .and_then(|n| n.as_str())
        .filter(|n| !n.is_empty())
        .map(|s| s.to_string())
}

/// After a successful execution, redeem the offer's voucher nonce at the
/// dashboard (double-spend guard). No-op unless vouchers are `required` and a
/// voucher is present; best-effort (logs and continues on failure).
fn redeem_offer_voucher(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
    actual_cost: f64,
    required: bool,
) {
    if !required || offer.voucher_signed_json.is_empty() {
        return;
    }
    let nonce = offer_voucher_nonce(offer);
    if let (Some(nonce), Some(api_url), Some(api_key)) =
        (nonce, &state.config.api_url, &state.config.api_key)
    {
        match super::node_sync::redeem_voucher(api_url, api_key, &nonce, actual_cost) {
            Ok(true) => {}
            Ok(false) => {
                eprintln!("  [VOUCHER] nonce already spent (double-spend attempt?): {nonce}")
            }
            Err(e) => eprintln!("  [VOUCHER] redeem failed: {e}"),
        }
    }
}

/// Verify the voucher carried on an incoming `TaskOffer` against the cached
/// dashboard pubkey and the offer's estimated price. Returns `Err(reason)` on a
/// verification failure; `Ok(())` when valid or when vouchers are not required.
fn verify_offer_voucher(
    state: &Arc<BrokerState>,
    offer: &task_board::TaskOffer,
) -> Result<(), String> {
    verify_offer_voucher_with(state, offer, voucher_required())
}

/// [`verify_offer_voucher`] with the `ZAKURO_REQUIRE_VOUCHER` decision passed
/// in, so the QUIC offer gate and tests reuse it without touching env.
fn verify_offer_voucher_with(
    state: &Arc<BrokerState>,
    offer: &task_board::TaskOffer,
    required: bool,
) -> Result<(), String> {
    if !required {
        return Ok(());
    }
    let mut pubkeys = cached_voucher_pubkeys(state);
    if pubkeys.is_empty() {
        return Err("no dashboard voucher pubkey cached yet".into());
    }
    if offer.voucher_signed_json.is_empty() {
        return Err("voucher required but none supplied".into());
    }
    // Estimated spend for this offer: price/hr × duration(hrs), bounded by the offer.
    let price_estimate =
        offer.max_price_per_hour * (offer.estimated_duration_secs / 3600.0).max(0.0);
    let mut res = super::voucher::verify_voucher_now(
        &pubkeys,
        &offer.voucher_signed_json,
        &offer.voucher_sig,
        price_estimate,
    );
    if matches!(&res, Err(e) if super::voucher::is_signature_error(e))
        && refresh_voucher_pubkeys_on_failure(state)
    {
        pubkeys = cached_voucher_pubkeys(state);
        res = super::voucher::verify_voucher_now(
            &pubkeys,
            &offer.voucher_signed_json,
            &offer.voucher_sig,
            price_estimate,
        );
    }
    res.map(|_| ())
}

/// Snapshot of the cached dashboard voucher pubkey set (empty = none yet).
fn cached_voucher_pubkeys(state: &Arc<BrokerState>) -> Vec<String> {
    state
        .dash_voucher_pubkey
        .read()
        .map(|g| g.clone())
        .unwrap_or_default()
}

/// Minimum spacing between on-failure pubkey-set refreshes (#396).
const VOUCHER_PUBKEY_REFRESH_MIN_SECS: u64 = 60;

/// After a signature failure, re-fetch the hub's pubkey set (a rotation may have
/// happened since the last periodic sync). Rate-limited so a stream of bad
/// vouchers cannot hammer the hub. Returns true when the cache changed.
fn refresh_voucher_pubkeys_on_failure(state: &Arc<BrokerState>) -> bool {
    use std::sync::atomic::Ordering;
    let Some(api_url) = state.config.api_url.as_deref() else {
        return false;
    };
    let now = super::node_identity::now_secs();
    let last = state.voucher_pubkey_refreshed_at.load(Ordering::Relaxed);
    if now.saturating_sub(last) < VOUCHER_PUBKEY_REFRESH_MIN_SECS
        || state
            .voucher_pubkey_refreshed_at
            .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
            .is_err()
    {
        return false;
    }
    match super::node_sync::fetch_voucher_pubkey(api_url) {
        Ok(keys) => match state.dash_voucher_pubkey.write() {
            Ok(mut w) if *w != keys => {
                *w = keys;
                true
            }
            _ => false,
        },
        Err(e) => {
            eprintln!("  [VOUCHER] pubkey refresh after verify failure failed: {e}");
            false
        }
    }
}

/// Env-driven wrapper: enforce when `ZAKURO_ENFORCE_NODE_SIG` is set, else log and
/// allow (permissive rollout). Returns `Some(401)` only when enforcing a failure.
/// A test may pin the decision per broker with `enforce_node_sig_override`.
fn node_sig_gate(state: &Arc<BrokerState>, request: &BrokerRequest) -> Option<BrokerResponse> {
    let enforce = state
        .enforce_node_sig_override
        .get()
        .copied()
        .unwrap_or_else(enforce_node_sig);
    node_sig_verdict(state, request, enforce)
        .err()
        .map(|e| error_response(&e, "UNAUTHORIZED", 401))
}

/// `ZAKURO_ENFORCE_NODE_SIG=1|true`, read per call.
fn enforce_node_sig() -> bool {
    std::env::var("ZAKURO_ENFORCE_NODE_SIG")
        .map(|v| v == "1" || v == "true")
        .unwrap_or(false)
}

/// Core of [`node_sig_gate`] with the enforce decision passed in. `Err(reason)`
/// only when enforcing a failed check; permissive mode logs and returns `Ok`.
fn node_sig_verdict(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
    enforce: bool,
) -> Result<(), String> {
    match check_node_sig(
        &state.node_roster,
        &state.node_sig_guard,
        request,
        node_identity::now_secs(),
    ) {
        Ok(_) => Ok(()),
        Err(e) => {
            if enforce {
                Err(format!("node signature check failed: {e}"))
            } else {
                // Permissive rollout: stay silent for entirely-unsigned peers (expected
                // while the mesh upgrades); only flag a *present but invalid* signature.
                if request.header("X-Node-Id").is_some() {
                    eprintln!(
                        "  [NODE_SIG] permissive: {} {} — {}",
                        format!("{:?}", request.method).to_uppercase(),
                        request.path,
                        e
                    );
                }
                Ok(())
            }
        }
    }
}

/// The two zero-trust gate flags, as the HTTP `/peer/*` routes read them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PeerGateFlags {
    /// `ZAKURO_ENFORCE_NODE_SIG`
    pub enforce_node_sig: bool,
    /// `ZAKURO_REQUIRE_VOUCHER`
    pub require_voucher: bool,
}

impl PeerGateFlags {
    /// Read both flags from env, per call, exactly as `node_sig_gate` and
    /// `voucher_required` do.
    pub(crate) fn from_env() -> Self {
        Self {
            enforce_node_sig: enforce_node_sig(),
            require_voucher: voucher_required(),
        }
    }
}

/// Zero-trust gate for a task offer that arrived over QUIC (zc#421), after its
/// shared peer key has been checked. Applies the same node-signature check
/// (`node_sig_verdict`) and voucher requirement (`verify_offer_voucher_with`)
/// as `POST /peer/tasks/offer`, so the two transports cannot drift. `raw` is
/// the offer's JSON as received; the signature (carried in `offer.node_sig`)
/// covers [`task_board::quic_offer_sign_bytes`] of it under
/// [`task_board::QUIC_OFFER_SIGN_PATH`]. Permissive when both flags are off.
pub(crate) fn quic_offer_gate(
    state: &Arc<BrokerState>,
    raw: &[u8],
    offer: &task_board::TaskOffer,
    flags: PeerGateFlags,
) -> Result<(), String> {
    let request = BrokerRequest {
        method: Method::Post,
        path: task_board::QUIC_OFFER_SIGN_PATH.to_string(),
        query: String::new(),
        headers: offer.quic_sig_headers(),
        body: task_board::quic_offer_sign_bytes(raw).unwrap_or_default(),
        peer_addr: None,
    };
    node_sig_verdict(state, &request, flags.enforce_node_sig)?;
    verify_offer_voucher_with(state, offer, flags.require_voucher)
        .map_err(|reason| format!("voucher check failed: {reason}"))
}

/// Auth for the P2P **handshake surface** (health/identity). When a peer key
/// is configured it is required (same as the credit surface). When no key is
/// configured these stay reachable from loopback only, so localhost broker
/// auto-discovery (`discover_broker_peers_on_localhost`) keeps working without
/// exposing handshake info to the network. Returns `Some(401)` to reject,
/// `None` when authorized.
fn peer_handshake_auth(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
) -> Option<BrokerResponse> {
    let key = state.peer_manager.peer_key();
    if key.is_empty() {
        if request.is_loopback() {
            None
        } else {
            Some(error_response(
                "Peer authentication required (set ZAKURO_PEER_KEY)",
                "UNAUTHORIZED",
                401,
            ))
        }
    } else if peer::verify_peer_key(request.header("X-Peer-Key").as_deref(), key) {
        None
    } else {
        Some(error_response("Invalid peer key", "UNAUTHORIZED", 401))
    }
}

/// A single entry in the `/brokers` listing: a key-derived, IP-free peer id.
#[derive(serde::Serialize)]
struct BrokerEntry {
    id: String,
    reachable: bool,
    /// The zc binary that peer is running, from its last cached signed advert
    /// (zc#305). `null` for a peer that has not been adverted since this
    /// broker started, or one built before build disclosure.
    build: Option<crate::build_id::BuildId>,
}

/// The `/brokers` body: this broker's own identity and build, plus one entry
/// per peer. `self_build` is what a caller reconciles the peers against.
#[derive(serde::Serialize)]
struct BrokersResponse {
    #[serde(rename = "self")]
    self_id: String,
    self_build: &'static crate::build_id::BuildId,
    brokers: Vec<BrokerEntry>,
}

/// `GET /brokers` — the IP-free "list the brokers to communicate with"
/// primitive. Design model: a broker owns and manages only its own local
/// workers; the mesh is a set of BROKERS talking P2P. This is the client
/// surface for that mesh topology, scrubbed of every IP/peer_url — only
/// key-derived `zc://node-<fp>` ids are returned.
///
/// Peer ids come from `PeerManager`'s cached fingerprints, learned from each
/// peer's own `/peer/health` response (`broker_id`, now key-derived — see
/// `handle_peer_health`) during QUIC/health discovery and cached on the
/// `PeerClient`. A peer whose fingerprint hasn't been learned yet is
/// probed on demand (`ensure_fingerprints_cached`) so a cold-started broker
/// still answers usefully; if it's still unknown after that (peer
/// unreachable / predates key-derived identity), it is OMITTED from the
/// list rather than leaking its `peer_url` as a stand-in id.
fn handle_brokers(state: &Arc<BrokerState>) -> BrokerResponse {
    state.peer_manager.ensure_fingerprints_cached();

    let mut peer_urls = state.peer_manager.peer_urls();
    peer_urls.sort();

    // One broker, one row — keyed on identity, because one broker can be
    // registered under two spellings (its `ZAKURO_PEERS` DNS name and its
    // roster mesh address). The tick loop reconciles those away, but it runs
    // only every ~60s and cannot dedup a peer whose fingerprint was still
    // unresolved when it last ran; listing the same `zc://node-<fp>` twice
    // would falsify this feature's acceptance criterion in that window. A
    // peer is reachable if ANY of its spellings is.
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let brokers: Vec<BrokerEntry> = peer_urls
        .into_iter()
        .filter_map(|url| {
            let fp_id = state.peer_manager.peer_fingerprint(&url)?;
            let reachable = state
                .peer_manager
                .get_client(&url)
                .map(|c| c.is_reachable())
                .unwrap_or(false);
            let build = state
                .peer_manager
                .peer_advert(&url)
                .and_then(|a| a.build)
                .filter(|b| b.is_known());
            Some((fp_id, reachable, build))
        })
        .fold(
            Vec::<BrokerEntry>::new(),
            |mut acc, (fp_id, reachable, build)| {
                if seen.insert(fp_id.clone()) {
                    acc.push(BrokerEntry {
                        id: fp_id,
                        reachable,
                        build,
                    });
                } else if let Some(e) = acc.iter_mut().find(|e| e.id == fp_id) {
                    // Same broker under a second spelling: merge, never
                    // duplicate. Reachability is an OR, and a known build
                    // beats an unknown one — only one of the two spellings
                    // may have been adverted since startup.
                    e.reachable |= reachable;
                    if e.build.is_none() {
                        e.build = build;
                    }
                }
                acc
            },
        );

    json_response(
        &BrokersResponse {
            self_id: state.node_key.node_uri(),
            self_build: crate::build_id::current(),
            brokers,
        },
        200,
    )
}

/// Body for `POST /price`.
#[derive(Debug, Deserialize)]
struct SetPriceRequest {
    price_per_hour: f64,
}

/// `GET /price` — this broker's currently advertised price (credits/hour).
/// Client-facing, IP-free: only the numeric price is ever returned.
fn handle_get_price(state: &Arc<BrokerState>) -> BrokerResponse {
    json_response(
        &serde_json::json!({ "price_per_hour": state.price.get() }),
        200,
    )
}

/// `POST /price` — set this broker's advertised price. Loopback-only: a
/// broker's price is its own operator's decision, never settable by a
/// remote peer or client over the network.
fn handle_set_price(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if !request.is_loopback() {
        return error_response("Setting price is local-only (loopback)", "FORBIDDEN", 403);
    }
    match body_or_413(request) {
        Err(resp) => resp,
        Ok(body) => match serde_json::from_slice::<SetPriceRequest>(body) {
            Ok(req) => {
                state.price.set(req.price_per_hour);
                json_response(
                    &serde_json::json!({ "price_per_hour": state.price.get() }),
                    200,
                )
            }
            Err(e) => error_response(&format!("Invalid request body: {e}"), "BAD_REQUEST", 400),
        },
    }
}

/// `POST /workers/{id}/drain` — stop routing new work to one of this broker's
/// workers so the local `zc agent` can stop it without killing a job
/// (spec 2026-09-13-macos-widget §6.6). Loopback-only, like `/price/set`:
/// only the agent supervising the worker on this machine may drain it.
fn handle_drain_worker(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
    worker_id: &str,
) -> BrokerResponse {
    if !request.is_loopback() {
        return error_response("Draining is local-only (loopback)", "FORBIDDEN", 403);
    }
    match state.workers.drain(worker_id) {
        Some(w) => json_response(
            &serde_json::json!({
                "status": "draining",
                "worker_id": w.id,
                "active_requests": w.active_requests,
            }),
            200,
        ),
        None => error_response("Worker not found", "NOT_FOUND", 404),
    }
}

// --- Model inference (/infer) ---

/// Inbound `POST /infer` body: an OpenAI-shaped chat request addressed to a
/// `zc://` model uuid (or bare uuid) instead of a model name.
#[derive(Debug, Deserialize)]
struct InferRequest {
    model: String,
    /// Passed through to the provider as-is (messages + any extra OpenAI fields).
    #[serde(flatten)]
    rest: serde_json::Value,
}

/// The subset of an OpenAI chat-completions response this route cares about.
#[derive(Debug, Deserialize)]
struct OpenAiChatResponse {
    choices: Vec<OpenAiChoice>,
    #[serde(default)]
    usage: OpenAiUsage,
}

#[derive(Debug, Deserialize)]
struct OpenAiChoice {
    message: OpenAiMessage,
}

#[derive(Debug, Deserialize)]
struct OpenAiMessage {
    #[serde(default)]
    content: String,
}

#[derive(Debug, Default, Deserialize)]
struct OpenAiUsage {
    #[serde(default)]
    prompt_tokens: u64,
    #[serde(default)]
    completion_tokens: u64,
    #[serde(default)]
    total_tokens: u64,
}

/// Errors from [`forward_chat`], sanitized so the handler never has to worry
/// about leaking transport internals (connection strings, TLS details, etc.)
/// into a client-facing response.
#[derive(Debug)]
enum ForwardError {
    /// Transport-level failure (connection refused, timeout, DNS, ...).
    Transport(String),
    /// Provider responded but not with a parseable OpenAI chat completion.
    BadResponse(String),
}

impl std::fmt::Display for ForwardError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Transport(_) => write!(f, "provider unreachable"),
            Self::BadResponse(_) => write!(f, "provider returned an invalid response"),
        }
    }
}

/// Real HTTP forward of an OpenAI chat body to `{worker_uri}/v1/chat/completions`,
/// using the same outbound client (`ureq`) as `ledger::sync_workers_via_api`.
///
/// Factored out from [`handle_infer`] so tests can substitute a stub closure
/// in place of a live network call.
fn forward_chat_live(
    worker_uri: &str,
    body: &serde_json::Value,
) -> Result<OpenAiChatResponse, ForwardError> {
    let endpoint = format!("{}/v1/chat/completions", worker_uri.trim_end_matches('/'));
    let payload = serde_json::to_string(body)
        .map_err(|e| ForwardError::BadResponse(format!("failed to serialize request: {e}")))?;

    // A hung/unresponsive provider must not hang the broker's own /infer
    // handler indefinitely — ureq's defaults have no timeout. 120s read covers
    // slow generations without leaving the request open forever; connect gets
    // a much tighter bound since a live provider should accept fast.
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(std::time::Duration::from_secs(10)))
            .timeout_recv_response(Some(std::time::Duration::from_secs(120)))
            .build(),
    );

    let response = agent
        .post(&endpoint)
        .config()
        .http_status_as_error(false)
        .build()
        .header("Content-Type", "application/json")
        .send(payload.as_str())
        .map_err(|e| ForwardError::Transport(e.to_string()))?;

    let status = response.status().as_u16();
    let text = response
        .into_body()
        .read_to_string()
        .map_err(|e| ForwardError::Transport(e.to_string()))?;

    if status != 200 {
        return Err(ForwardError::BadResponse(format!(
            "provider returned status {status}"
        )));
    }

    serde_json::from_str::<OpenAiChatResponse>(&text)
        .map_err(|e| ForwardError::BadResponse(format!("failed to parse provider response: {e}")))
}

/// Auth gate for `/infer`, mirroring `execute_prepare`'s bearer resolution
/// exactly: a non-empty Bearer token must resolve to a user via the same
/// `resolve_user_from_api_key` path `/execute` uses; in local mode a missing
/// token is allowed (single-node, free demo path); in remote mode a missing
/// or invalid token is rejected with the same 401 shape `/execute` returns.
/// Returns the resolved user id (`None` on the keyless local-mode path) so
/// the billing step downstream charges the same identity auth admitted.
///
/// `execute` and `infer` apply the same three branches, and used to each carry
/// their own copy of them. One rule, so the two cannot drift — the failure
/// #252 records, where four hand-written selectors had quietly stopped
/// agreeing, started the same way.
fn authenticated_user(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
) -> Result<Option<String>, BrokerResponse> {
    let bearer = bearer_token(request.header("Authorization").as_deref());
    #[cfg(test)]
    auth_count_hook::record(bearer.as_deref());

    if let Some(token) = bearer {
        state
            .ledger
            .resolve_user_from_api_key(&token)
            .map(Some)
            .map_err(|e| error_response(&e.to_string(), e.auth_code(), e.auth_status()))
    } else if state.is_local_mode() {
        // No Bearer token: allowed only in local mode, where execution is
        // single-node and free — same rule `execute_prepare` applies.
        Ok(None)
    } else {
        // Remote mode: require an API key whether or not billing is enabled.
        Err(error_response(
            "API key required. Set Authorization: Bearer <key>",
            "UNAUTHORIZED",
            401,
        ))
    }
}

/// Test-only tally of [`authenticated_user`] calls per bearer token, so a test
/// can assert how many times one request authenticated (keyed by token because
/// tests run in parallel and the handlers hop threads).
#[cfg(test)]
mod auth_count_hook {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock};

    fn map() -> &'static Mutex<HashMap<String, usize>> {
        static M: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
        M.get_or_init(Default::default)
    }

    pub(super) fn record(token: Option<&str>) {
        if let Some(t) = token {
            *map().lock().unwrap().entry(t.to_string()).or_default() += 1;
        }
    }

    pub(super) fn count(token: &str) -> usize {
        map().lock().unwrap().get(token).copied().unwrap_or(0)
    }
}

/// Fallback generation budget when the caller sends no `max_tokens`: the
/// reservation must cover the worst the provider might generate, and
/// llama-server's own no-limit default is effectively "until context runs
/// out", so this is deliberately generous rather than typical.
const INFER_DEFAULT_MAX_TOKENS: u64 = 4096;

/// Upper bound on what a request could cost, reserved before forwarding.
///
/// Prompt tokens are unknown until the provider reports usage, so they are
/// over-estimated at one token per 3 bytes of request body (English text
/// runs ~4 bytes/token; 3 keeps the ceiling above the actual for tokenizers
/// that split tighter). Generation is bounded by the caller's `max_tokens`
/// (or `INFER_DEFAULT_MAX_TOKENS`). The commit is capped by this ceiling
/// (`capped_charge`), so over-estimating can only over-RESERVE, never
/// over-CHARGE — the difference is refunded at commit.
fn infer_cost_ceiling(price_per_mtok: f64, body_bytes: usize, max_tokens: Option<u64>) -> f64 {
    let prompt_est = (body_bytes as f64 / 3.0).ceil();
    let gen_budget = max_tokens.unwrap_or(INFER_DEFAULT_MAX_TOKENS) as f64;
    (prompt_est + gen_budget) * price_per_mtok / 1_000_000.0
}

/// Settle a billed inference whose provider is registered on THIS broker:
/// credit the broker's configured owner the payout (WAL-backed, exactly as
/// `handle_peer_earn` does for a mesh-delivered earn), mirror the platform
/// commission into the local cache, and redeem the voucher so the dashboard
/// credits the platform-house authoritatively. With no owner configured the
/// payout leg has no payee — the payout is REFUNDED to the requester (who
/// then nets only the commission), exactly the rule `settle_executor_payout`
/// applies when the earn RPC fails: money is never destroyed to nobody.
#[allow(clippy::too_many_arguments)]
fn settle_own_provider_payout(
    state: &Arc<BrokerState>,
    requester_uid: &str,
    worker: &Worker,
    actual_cost: f64,
    commission_c: f64,
    voucher_nonce: &str,
    request_id: &str,
    duration_ms: f64,
) {
    let (payout, commission) = split_commission(actual_cost, commission_c);
    if commission > 0.0 && state.is_billing_enabled() {
        let platform_uid =
            std::env::var("ZAKURO_PLATFORM_UID").unwrap_or_else(|_| "platform-house".into());
        state
            .ledger
            .local_credits
            .entry(platform_uid.clone())
            .and_modify(|b| *b += commission)
            .or_insert(commission);
        state
            .ledger
            .authoritative_balances
            .entry(platform_uid)
            .and_modify(|b| *b += commission)
            .or_insert(commission);
    }
    match state.config.owner_user_id.as_deref() {
        Some(owner) if payout > 0.0 => {
            let earn_request_id = format!("earn-{request_id}");
            let dashboard_configured =
                state.config.api_url.is_some() && state.config.api_key.is_some();
            if dashboard_configured {
                let _ = state.wal.append(&WalEntry {
                    request_id: earn_request_id.clone(),
                    user_id: owner.to_string(),
                    reservation_id: String::new(),
                    estimated_cost: payout,
                    actual_cost: Some(payout),
                    worker_id: worker.id.clone(),
                    worker_name: Some(worker.name.clone()),
                    duration_ms: Some(duration_ms),
                    timestamp: chrono::Utc::now(),
                    status: WalStatus::Earned,
                    voucher_nonce: None,
                });
            }
            let balance_after = state.ledger.local_add_credits(owner, payout);
            state.tx_buffer.push_transaction(BufferedTransaction {
                request_id: earn_request_id,
                user_id: owner.to_string(),
                tx_type: "credit".to_string(),
                amount: payout,
                balance_after,
                worker_id: worker.id.clone(),
                duration_ms,
                source_node: state.config.node_name.clone(),
                worker_name: Some(worker.name.clone()),
                worker_uri: Some(worker.uri.clone()),
                price_per_hour: worker.pricing.price_per_hour,
                voucher_nonce: None,
            });
        }
        Some(_) => {}
        None => {
            // No payee: refund the payout to the requester (nets −commission)
            // — the settle_executor_payout earn-failure rule; money is never
            // destroyed to nobody.
            eprintln!(
                "  [INFER] no owner configured on this broker: refunding provider payout \
                 {payout:.6} for request {request_id} to the requester"
            );
            if payout > 0.0 && state.is_billing_enabled() {
                state
                    .ledger
                    .local_credits
                    .entry(requester_uid.to_string())
                    .and_modify(|b| *b += payout)
                    .or_insert(payout);
                state
                    .ledger
                    .authoritative_balances
                    .entry(requester_uid.to_string())
                    .and_modify(|b| *b += payout)
                    .or_insert(payout);
                state.tx_buffer.push_transaction(BufferedTransaction {
                    request_id: format!("{request_id}-earn-refund"),
                    user_id: requester_uid.to_string(),
                    tx_type: "refund".to_string(),
                    amount: payout,
                    balance_after: 0.0,
                    worker_id: worker.id.clone(),
                    duration_ms,
                    source_node: state.config.node_name.clone(),
                    worker_name: Some(worker.name.clone()),
                    worker_uri: Some(worker.uri.clone()),
                    price_per_hour: worker.pricing.price_per_hour,
                    voucher_nonce: None,
                });
            }
        }
    }
    if !voucher_nonce.is_empty() {
        if let (Some(api_url), Some(api_key)) = (&state.config.api_url, &state.config.api_key) {
            match super::node_sync::redeem_voucher(api_url, api_key, voucher_nonce, actual_cost) {
                Ok(true) => {}
                Ok(false) => {
                    eprintln!("  [VOUCHER] infer nonce already spent: {voucher_nonce}")
                }
                Err(e) => eprintln!("  [VOUCHER] infer redeem failed: {e}"),
            }
        }
    }
}

/// Billing context carried from the pre-forward reserve to settlement.
struct InferBilling {
    res_id: String,
    ceiling: f64,
    request_id: String,
    uid: String,
    /// The ONE dashboard-verified commission rate for this request, captured
    /// at mint (0.0 when vouchers are not required) — settlement never
    /// re-derives it, mirroring `dispatch_to_peers`.
    commission_c: f64,
    /// Dashboard voucher nonce to redeem at settlement ("" when vouchers off).
    voucher_nonce: String,
}

/// What the request actually cost: total tokens at the provider's price.
fn infer_actual_cost(price_per_mtok: f64, total_tokens: u64) -> f64 {
    total_tokens as f64 * price_per_mtok / 1_000_000.0
}

/// `POST /infer` — resolve `model` (a `zc://` model uuid) to a serving worker
/// and forward a one-shot OpenAI chat completion to it. Charges the caller
/// `total_tokens × price_per_mtok / 1e6` (reserve-ceiling → forward →
/// capped commit; full refund when the provider call fails). Free when the
/// provider is unpriced, billing is disabled, or the caller is the keyless
/// local-mode path. Provider payout is NOT settled here — it rides on the
/// published transaction (`worker_id` + tokens) for the voucher/receipt
/// settlement to pay out, mirroring where /execute's payout lives.
fn handle_infer(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    handle_infer_with(state, request, forward_chat_live)
}

/// Testable core of `/infer`: auth -> parse -> resolve -> forward -> map, with
/// the actual provider call injected as `forward`. Production wires
/// [`forward_chat_live`]; tests substitute a canned stub.
fn handle_infer_with(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
    forward: impl FnOnce(&str, &serde_json::Value) -> Result<OpenAiChatResponse, ForwardError>,
) -> BrokerResponse {
    let user_id = match authenticated_user(state, request) {
        Ok(uid) => uid,
        Err(resp) => return resp,
    };
    // Paid work, taken after authentication so an anonymous request cannot
    // cancel a benchmark.
    let _inflight = super::InflightGuard::new(state);

    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let body_len = body.len();

    let parsed: InferRequest = match serde_json::from_slice(body) {
        Ok(v) => v,
        Err(_) => return error_response("invalid model uri", "BAD_REQUEST", 400),
    };

    let model_uuid = match parse_model_uri(&parsed.model) {
        Some(uuid) => uuid,
        None => return error_response("invalid model uri", "BAD_REQUEST", 400),
    };

    let worker = match state.workers.resolve_model(&model_uuid) {
        Ok(w) => w,
        Err(ModelResolveError::NoProvider { model_uuid }) => {
            return error_response(
                &format!("no provider serving zc://{model_uuid}"),
                "NOT_FOUND",
                404,
            );
        }
    };

    // Forward the caller's body as-is (messages, max_tokens, etc.). The
    // `model` field is what the provider keys on, and the two provider kinds
    // need different things: a SPECIALIZED provider is one llama-server that
    // ignores the name (any value works; the worker name reads best in its
    // logs), but a GENERAL provider serves many models and must be told
    // WHICH one — its on-demand loader (`serve_general`) parses this field
    // as the model uuid. Sending it the worker name would 400 every request.
    let mut forward_body = parsed.rest;
    if let serde_json::Value::Object(ref mut map) = forward_body {
        let model_field = match worker.provider_type {
            crate::broker::worker::ProviderType::General => model_uuid.clone(),
            crate::broker::worker::ProviderType::Specialized => worker.name.clone(),
        };
        map.insert("model".to_string(), serde_json::Value::String(model_field));
    }

    // ── Billing: reserve the ceiling before spending provider compute ──
    // Billable only when all three hold: billing is on, the provider set a
    // price, and auth resolved a user (the keyless local-mode path stays
    // free). An unpriced provider (price_per_mtok == 0, today's default)
    // bills nothing, so rolling this out changes nothing until providers
    // opt in with `zc serve --price`.
    let max_tokens = forward_body.get("max_tokens").and_then(|v| v.as_u64());
    let billable = state.is_billing_enabled() && worker.price_per_mtok > 0.0;
    let reservation = match (&user_id, billable) {
        (Some(uid), true) => {
            let ceiling = infer_cost_ceiling(worker.price_per_mtok, body_len, max_tokens);
            // Commission rides on a dashboard-signed voucher exactly as it
            // does for direct-forward /execute: minted fail-closed BEFORE
            // any credits are reserved or provider compute is spent, so a
            // billed inference can never run uncommissioned when vouchers
            // are required. Vouchers off (the default) → commission 0 and
            // no dashboard round-trip.
            let (commission_c, voucher_nonce) = if voucher_required() {
                match mint_and_verify_remote_voucher(state, ceiling, None) {
                    Ok(v) => v,
                    Err(resp) => return resp,
                }
            } else {
                (0.0, String::new())
            };
            let request_id = uuid::Uuid::new_v4().to_string();
            match state.ledger.local_reserve(uid, ceiling, &request_id) {
                Ok((res_id, _balance)) => Some(InferBilling {
                    res_id,
                    ceiling,
                    request_id,
                    uid: uid.clone(),
                    commission_c,
                    voucher_nonce,
                }),
                Err(ledger::LedgerError::InsufficientCredits {
                    required,
                    available,
                }) => {
                    return error_response(
                        &format!("Insufficient credits: need {required:.6}, have {available:.6}"),
                        "INSUFFICIENT_CREDITS",
                        402,
                    );
                }
                Err(e) => return error_response(&e.to_string(), "LEDGER_ERROR", 503),
            }
        }
        _ => None,
    };

    let started = Instant::now();
    match forward(&worker.uri, &forward_body) {
        Ok(resp) => {
            let content = resp
                .choices
                .first()
                .map(|c| c.message.content.clone())
                .unwrap_or_default();
            // Commit the actual cost, capped by the reservation so an
            // over-reporting provider can never charge past the ceiling the
            // caller's balance was checked against. The uncharged remainder
            // is released by the commit.
            //
            // The balance after the charge travels back as a header, the same
            // receipt `/execute` gives: a caller who has to fetch their
            // balance separately to learn what a call left them sees a number
            // from a different moment.
            let mut credits_remaining: Option<f64> = None;
            let charged = match &reservation {
                Some(bill) => {
                    let InferBilling {
                        res_id,
                        ceiling,
                        request_id,
                        uid,
                        commission_c,
                        voucher_nonce,
                    } = bill;
                    let actual = capped_charge(
                        infer_actual_cost(worker.price_per_mtok, resp.usage.total_tokens),
                        *ceiling,
                    );
                    let balance_after = match state.ledger.local_commit(res_id, actual) {
                        Ok(b) => b,
                        Err(e) => {
                            // The forward already succeeded and the tokens are
                            // spent; a commit failure must not un-serve the
                            // response. Log and report the charge we attempted.
                            eprintln!("  [INFER] commit error for {request_id}: {e}");
                            state.ledger.load_balance_if_needed(uid)
                        }
                    };
                    credits_remaining = Some(balance_after);
                    // Audit trail: same buffered-transaction stream the
                    // dashboard ingests for /execute. duration_ms carries the
                    // forward latency; tokens are recoverable from amount /
                    // price_per_mtok. Provider payout settles downstream off
                    // this record — never minted here.
                    state.tx_buffer.push_transaction(BufferedTransaction {
                        request_id: request_id.clone(),
                        user_id: uid.clone(),
                        tx_type: "infer".to_string(),
                        amount: actual,
                        balance_after,
                        worker_id: worker.id.clone(),
                        duration_ms: started.elapsed().as_millis() as f64,
                        source_node: state.config.node_name.clone(),
                        worker_name: Some(worker.name.clone()),
                        worker_uri: Some(worker.uri.clone()),
                        price_per_hour: worker.pricing.price_per_hour,
                        voucher_nonce: None,
                    });
                    // ── Provider payout + commission, /execute's direct-path
                    // semantics verbatim: settle to the provider's broker by
                    // its key-derived node identity, redeem the voucher for
                    // the authoritative platform-house credit, and if the
                    // provider's broker cannot be resolved, refund the FULL
                    // charge — pay nobody, redeem nothing, requester nets 0.
                    let own_fp = state.node_key.fingerprint();
                    let exec_fp = executor_fp(&worker);
                    if exec_fp == Some(own_fp.as_str()) {
                        // Provider registered directly on THIS broker (zc
                        // serve --advertise against the fleet): its payout
                        // goes to this broker's configured owner — the same
                        // payee handle_peer_earn would credit if the earn
                        // arrived over the mesh. No RPC to fail, so no
                        // refund leg; conservation is payout+commission ==
                        // actual by construction.
                        settle_own_provider_payout(
                            state,
                            uid,
                            &worker,
                            actual,
                            *commission_c,
                            voucher_nonce,
                            request_id,
                            started.elapsed().as_millis() as f64,
                        );
                        actual
                    } else {
                        match exec_fp.and_then(|fp| state.peer_manager.get_url_for_fingerprint(fp))
                        {
                            Some(peer_url) => {
                                settle_executor_payout(
                                    state,
                                    uid,
                                    actual,
                                    *commission_c,
                                    &peer_url,
                                    WorkerName::of(&worker),
                                    request_id,
                                    started.elapsed().as_millis() as f64,
                                );
                                if !voucher_nonce.is_empty() {
                                    if let (Some(api_url), Some(api_key)) =
                                        (&state.config.api_url, &state.config.api_key)
                                    {
                                        match super::node_sync::redeem_voucher(
                                            api_url,
                                            api_key,
                                            voucher_nonce,
                                            actual,
                                        ) {
                                            Ok(true) => {}
                                            Ok(false) => eprintln!(
                                            "  [VOUCHER] infer nonce already spent: {voucher_nonce}"
                                        ),
                                            Err(e) => {
                                                eprintln!("  [VOUCHER] infer redeem failed: {e}")
                                            }
                                        }
                                    }
                                }
                                actual
                            }
                            None => {
                                eprintln!(
                                "  [INFER] provider's broker unresolved for worker {}                                  (request {request_id}): refunding {actual:.6} in full",
                                worker.name
                            );
                                state
                                    .ledger
                                    .local_credits
                                    .entry(uid.to_string())
                                    .and_modify(|b| *b += actual)
                                    .or_insert(actual);
                                state
                                    .ledger
                                    .authoritative_balances
                                    .entry(uid.to_string())
                                    .and_modify(|b| *b += actual)
                                    .or_insert(actual);
                                credits_remaining = credits_remaining.map(|b| b + actual);
                                state.tx_buffer.push_transaction(BufferedTransaction {
                                    request_id: format!("{request_id}-unresolved-refund"),
                                    user_id: uid.to_string(),
                                    tx_type: "refund".to_string(),
                                    amount: actual,
                                    balance_after: 0.0,
                                    worker_id: worker.id.clone(),
                                    duration_ms: started.elapsed().as_millis() as f64,
                                    source_node: state.config.node_name.clone(),
                                    worker_name: Some(worker.name.clone()),
                                    worker_uri: Some(worker.uri.clone()),
                                    price_per_hour: worker.pricing.price_per_hour,
                                    voucher_nonce: None,
                                });
                                0.0
                            }
                        }
                    }
                }
                None => 0.0,
            };
            let mut out = json_response(
                &serde_json::json!({
                    "content": content,
                    "usage": {
                        "prompt_tokens": resp.usage.prompt_tokens,
                        "completion_tokens": resp.usage.completion_tokens,
                        "total_tokens": resp.usage.total_tokens,
                    },
                    "provider": worker.name,
                    "charged_zkcr": charged,
                }),
                200,
            );
            if let Some(bill) = &reservation {
                out.headers
                    .push(header_or("X-Zakuro-Request-Id", &bill.request_id));
            }
            out.headers
                .push(header_or("X-Zakuro-Worker", worker.name.as_str()));
            out.headers
                .push(header_or("X-Zakuro-Cost", &format!("{charged:.6}")));
            if let Some(b) = credits_remaining {
                out.headers
                    .push(header_or("X-Zakuro-Credits-Remaining", &format!("{b:.6}")));
            }
            out.headers.push(header_or(
                "X-Zakuro-Duration-Ms",
                &format!("{:.2}", started.elapsed().as_secs_f64() * 1000.0),
            ));
            out
        }
        Err(e) => {
            // Failed forward: the caller pays nothing — release the full
            // reservation before surfacing the error.
            if let Some(bill) = &reservation {
                if let Err(cancel_err) = state.ledger.local_cancel(&bill.res_id) {
                    eprintln!(
                        "  [INFER] cancel error for {}: {cancel_err}",
                        bill.request_id
                    );
                }
            }
            error_response(&format!("provider request failed: {e}"), "BAD_GATEWAY", 502)
        }
    }
}

#[cfg(test)]
mod infer_tests {
    use super::*;
    use crate::broker::worker::{
        HardwareInfo, ProviderType, WorkerPricing, WorkerRegistration, WorkerResources,
    };
    use crate::broker::BrokerState;
    use std::sync::Arc;
    use tiny_http::Method;

    const UUID: &str = "ae5f3db4-437a-40d1-93ec-c8258315d69a";

    fn state_with_provider(uuid: &str, name: &str) -> Arc<BrokerState> {
        let state = BrokerState::new();
        state.workers.register(WorkerRegistration {
            name: name.to_string(),
            uri: "http://10.0.0.5:9000".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::Specialized,
            served_models: vec![uuid.to_string()],
            price_per_mtok: 1.0,
        });
        // These tests exercise parse/resolve/forward, not auth — run them in
        // local mode (keyless, single-node) so a missing Bearer token doesn't
        // trip the auth gate added for the /infer 401 fix.
        state.set_local_mode(true);
        Arc::new(state)
    }

    fn infer_req(body: &str) -> BrokerRequest {
        infer_req_with_headers(body, vec![])
    }

    fn infer_req_with_headers(body: &str, headers: Vec<(String, String)>) -> BrokerRequest {
        BrokerRequest {
            method: Method::Post,
            path: "/infer".to_string(),
            query: String::new(),
            headers,
            body: body.as_bytes().to_vec(),
            peer_addr: None,
        }
    }

    fn canned_ok(
        _worker_uri: &str,
        _body: &serde_json::Value,
    ) -> Result<OpenAiChatResponse, ForwardError> {
        Ok(OpenAiChatResponse {
            choices: vec![OpenAiChoice {
                message: OpenAiMessage {
                    content: "hello there".to_string(),
                },
            }],
            usage: OpenAiUsage {
                prompt_tokens: 10,
                completion_tokens: 5,
                total_tokens: 15,
            },
        })
    }

    fn canned_err(
        _worker_uri: &str,
        _body: &serde_json::Value,
    ) -> Result<OpenAiChatResponse, ForwardError> {
        Err(ForwardError::Transport(
            "connection refused to 10.0.0.5:9000 secret-token".to_string(),
        ))
    }

    #[test]
    fn served_uuid_forwards_and_maps_response() {
        let state = state_with_provider(UUID, "gpu-worker-1");
        let req = infer_req(&format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}]}}"#
        ));

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["content"], "hello there");
        assert_eq!(v["usage"]["prompt_tokens"], 10);
        assert_eq!(v["usage"]["completion_tokens"], 5);
        assert_eq!(v["usage"]["total_tokens"], 15);
        assert_eq!(v["provider"], "gpu-worker-1");
        assert_eq!(v["charged_zkcr"], 0.0);
    }

    #[test]
    fn general_provider_receives_the_model_uuid_not_the_worker_name() {
        let state = BrokerState::new();
        state.set_local_mode(true);
        state.workers.register(WorkerRegistration {
            name: "general-1".to_string(),
            uri: "http://10.0.0.6:8600".to_string(),
            worker_type: "llm".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::General,
            served_models: vec![crate::broker::worker::MODEL_WILDCARD.to_string()],
            price_per_mtok: 0.0,
        });
        let state = Arc::new(state);
        let req = infer_req(&format!(r#"{{"model":"zc://{UUID}","messages":[]}}"#));

        let seen = std::sync::Mutex::new(String::new());
        let resp = handle_infer_with(&state, &req, |_, body| {
            *seen.lock().unwrap() = body["model"].as_str().unwrap_or("").to_string();
            canned_ok("", body)
        });
        assert_eq!(resp.status, 200);
        assert_eq!(
            *seen.lock().unwrap(),
            UUID,
            "a general provider must be told WHICH model to load"
        );
    }

    #[test]
    fn unserved_uuid_returns_404() {
        let state = BrokerState::new();
        state.set_local_mode(true);
        let state = Arc::new(state);
        let req = infer_req(&format!(r#"{{"model":"zc://{UUID}","messages":[]}}"#));

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 404);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["error"], format!("no provider serving zc://{UUID}"));
    }

    #[test]
    fn invalid_model_uri_returns_400() {
        let state = BrokerState::new();
        state.set_local_mode(true);
        let state = Arc::new(state);
        let req = infer_req(r#"{"model":"zc://node-abc","messages":[]}"#);

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 400);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["error"], "invalid model uri");
    }

    #[test]
    fn provider_forward_error_returns_502_without_leaking_internals() {
        let state = state_with_provider(UUID, "gpu-worker-1");
        let req = infer_req(&format!(
            r#"{{"model":"{UUID}","messages":[{{"role":"user","content":"hi"}}]}}"#
        ));

        let resp = handle_infer_with(&state, &req, canned_err);
        assert_eq!(resp.status, 502);
        let body = String::from_utf8(resp.body.clone()).unwrap();
        assert!(
            !body.contains("10.0.0.5") && !body.contains("secret-token"),
            "502 body must not leak transport internals: {body}"
        );
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert!(v["error"]
            .as_str()
            .unwrap()
            .starts_with("provider request failed"));
    }

    /// A state where billing is genuinely on (dashboard api configured) and
    /// the caller identity `uid` holds `balance` in the local ledger.
    fn billing_state_with_priced_provider(
        uuid: &str,
        price_per_mtok: f64,
        uid: &str,
        balance: f64,
    ) -> Arc<BrokerState> {
        let mut state = BrokerState::new();
        state.config.api_url = Some("http://dashboard.test".to_string());
        state.config.api_key = Some("svc-key".to_string());
        state.config.owner_user_id = Some("provider-owner".to_string());
        let w = state.workers.register(WorkerRegistration {
            name: "priced-worker".to_string(),
            uri: "http://10.0.0.5:9000".to_string(),
            worker_type: "llm".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::Specialized,
            served_models: vec![uuid.to_string()],
            price_per_mtok,
        });
        // Directly-registered provider: stamped with this broker's own node
        // fp, exactly as the POST /workers route does — settlement takes the
        // own-provider (owner payout) branch.
        let fp = state.node_key.fingerprint();
        state.workers.set_node_fp(&w.id, &fp);
        state.set_local_mode(true); // keyless allowed; billing still applies to Bearer callers
        state
            .ledger
            .authoritative_balances
            .insert(uid.to_string(), balance);
        Arc::new(state)
    }

    fn bearer(uid: &str) -> Vec<(String, String)> {
        vec![(
            "Authorization".to_string(),
            format!("Bearer zk_{uid}_deadbeef"),
        )]
    }

    #[test]
    fn cost_ceiling_and_actual_cost_math() {
        // 300-byte body -> 100 prompt-token estimate; +200 max_tokens = 300
        // tokens at 1000 zkcr/mtok = 0.3.
        assert!((infer_cost_ceiling(1000.0, 300, Some(200)) - 0.3).abs() < 1e-9);
        // No max_tokens: the generous default budget applies.
        let c = infer_cost_ceiling(1000.0, 300, None);
        assert!((c - (100.0 + INFER_DEFAULT_MAX_TOKENS as f64) * 1000.0 / 1e6).abs() < 1e-9);
        assert!((infer_actual_cost(1000.0, 15) - 0.015).abs() < 1e-12);
        // Unpriced provider: everything is zero.
        assert_eq!(infer_cost_ceiling(0.0, 300, Some(200)), 0.0);
        assert_eq!(infer_actual_cost(0.0, 15), 0.0);
    }

    /// `/infer` carries the same receipt `/execute` does, so `zc infer` can
    /// print who served the call, what it cost and what it left.
    #[test]
    fn billed_infer_returns_the_receipt_headers() {
        let state = billing_state_with_priced_provider(UUID, 1000.0, "u9", 10.0);
        let body = format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":100}}"#
        );
        let req = infer_req_with_headers(&body, bearer("u9"));

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let h = |name: &str| {
            resp.headers
                .iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.clone())
        };
        assert!(h("X-Zakuro-Worker").is_some_and(|w| !w.is_empty()));
        assert_eq!(h("X-Zakuro-Cost").as_deref(), Some("0.015000"));
        let left: f64 = h("X-Zakuro-Credits-Remaining").unwrap().parse().unwrap();
        assert!((left - (10.0 - 0.015)).abs() < 1e-6, "remaining {left}");
        assert!(h("X-Zakuro-Request-Id").is_some());
    }

    #[test]
    fn billed_infer_charges_actual_tokens_and_reports_it() {
        let state = billing_state_with_priced_provider(UUID, 1000.0, "u1", 10.0);
        let body = format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":100}}"#
        );
        let req = infer_req_with_headers(&body, bearer("u1"));

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        // canned_ok reports 15 total tokens at 1000 zkcr/mtok = 0.015.
        assert!((v["charged_zkcr"].as_f64().unwrap() - 0.015).abs() < 1e-9);
        // The balance dropped by exactly the charge — the reservation
        // remainder was released, not kept.
        let bal = *state.ledger.authoritative_balances.get("u1").unwrap();
        assert!((bal - (10.0 - 0.015)).abs() < 1e-9, "balance {bal}");
        // Vouchers off → commission 0 → the provider's owner earns the full
        // charge; the three legs conserve: requester −0.015, owner +0.015.
        let owner = *state
            .ledger
            .authoritative_balances
            .get("provider-owner")
            .expect("owner credited");
        assert!((owner - 0.015).abs() < 1e-9, "owner payout {owner}");
    }

    #[test]
    fn no_owner_refunds_payout_to_requester() {
        // Own-provider settlement with no owner configured must refund the
        // payout leg — the requester nets only the commission (0 with
        // vouchers off), never a charge that pays nobody.
        let state = billing_state_with_priced_provider(UUID, 1000.0, "u7", 10.0);
        // billing helper sets an owner; strip it via a fresh state clone is
        // not possible (Arc) — rebuild without owner instead.
        let mut raw = BrokerState::new();
        raw.config.api_url = Some("http://dashboard.test".to_string());
        raw.config.api_key = Some("svc-key".to_string());
        raw.config.owner_user_id = None;
        let w = raw.workers.register(WorkerRegistration {
            name: "priced-worker".to_string(),
            uri: "http://10.0.0.5:9000".to_string(),
            worker_type: "llm".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::Specialized,
            served_models: vec![UUID.to_string()],
            price_per_mtok: 1000.0,
        });
        let fp = raw.node_key.fingerprint();
        raw.workers.set_node_fp(&w.id, &fp);
        raw.set_local_mode(true);
        raw.ledger
            .authoritative_balances
            .insert("u7".to_string(), 10.0);
        let state2 = Arc::new(raw);
        drop(state);

        let body = format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":100}}"#
        );
        let req = infer_req_with_headers(&body, bearer("u7"));
        let resp = handle_infer_with(&state2, &req, canned_ok);
        assert_eq!(resp.status, 200);
        // Vouchers off => commission 0 => full payout refunded => net 0.
        let bal = *state2.ledger.authoritative_balances.get("u7").unwrap();
        assert!(
            (bal - 10.0).abs() < 1e-9,
            "requester must net 0, balance {bal}"
        );
    }

    #[test]
    fn unstamped_provider_settlement_refunds_in_full() {
        // A provider with no node identity has no payee; the requester must
        // be made whole (pay nobody, charge nobody — conserving), exactly
        // like /execute's unresolved-peer arm.
        let state = billing_state_with_priced_provider(UUID, 1000.0, "u6", 10.0);
        // Strip the fp the helper stamped.
        let wid = state.workers.list()[0].id.clone();
        state.workers.set_node_fp(&wid, "");
        let body = format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":100}}"#
        );
        let req = infer_req_with_headers(&body, bearer("u6"));

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(
            v["charged_zkcr"], 0.0,
            "refunded charge must be reported as 0"
        );
        let bal = *state.ledger.authoritative_balances.get("u6").unwrap();
        assert!(
            (bal - 10.0).abs() < 1e-9,
            "requester made whole, balance {bal}"
        );
        assert!(
            state
                .ledger
                .authoritative_balances
                .get("provider-owner")
                .map(|b| *b == 0.0)
                .unwrap_or(true),
            "nobody may be paid when the charge was refunded"
        );
    }

    #[test]
    fn insufficient_credits_rejects_before_forwarding() {
        // Ceiling for this request is ~0.13 zkcr; the caller has less.
        let state = billing_state_with_priced_provider(UUID, 1000.0, "u2", 0.0001);
        let body = format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":100}}"#
        );
        let req = infer_req_with_headers(&body, bearer("u2"));

        let forwarded = std::sync::atomic::AtomicBool::new(false);
        let resp = handle_infer_with(&state, &req, |_, _| {
            forwarded.store(true, std::sync::atomic::Ordering::SeqCst);
            canned_ok("", &serde_json::Value::Null)
        });
        assert_eq!(resp.status, 402);
        assert!(
            !forwarded.load(std::sync::atomic::Ordering::SeqCst),
            "provider compute must not be spent for a caller who cannot pay"
        );
        // Balance untouched.
        let bal = *state.ledger.authoritative_balances.get("u2").unwrap();
        assert!((bal - 0.0001).abs() < 1e-12);
    }

    #[test]
    fn failed_forward_refunds_the_full_reservation() {
        let state = billing_state_with_priced_provider(UUID, 1000.0, "u3", 5.0);
        let body = format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":100}}"#
        );
        let req = infer_req_with_headers(&body, bearer("u3"));

        let resp = handle_infer_with(&state, &req, canned_err);
        assert_eq!(resp.status, 502);
        let bal = *state.ledger.authoritative_balances.get("u3").unwrap();
        assert!(
            (bal - 5.0).abs() < 1e-9,
            "failed call must cost nothing, balance {bal}"
        );
    }

    #[test]
    fn unpriced_provider_stays_free_for_authed_caller() {
        let state = billing_state_with_priced_provider(UUID, 0.0, "u4", 5.0);
        let body = format!(r#"{{"model":"zc://{UUID}","messages":[]}}"#);
        let req = infer_req_with_headers(&body, bearer("u4"));

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["charged_zkcr"], 0.0);
        let bal = *state.ledger.authoritative_balances.get("u4").unwrap();
        assert!((bal - 5.0).abs() < 1e-12);
    }

    #[test]
    fn keyless_local_caller_stays_free_even_on_priced_provider() {
        let state = billing_state_with_priced_provider(UUID, 1000.0, "unused", 5.0);
        let body = format!(r#"{{"model":"zc://{UUID}","messages":[]}}"#);
        let req = infer_req(&body);

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["charged_zkcr"], 0.0);
    }

    #[test]
    fn over_reporting_provider_cannot_charge_past_the_ceiling() {
        let state = billing_state_with_priced_provider(UUID, 1000.0, "u5", 10.0);
        let body = format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}],"max_tokens":10}}"#
        );
        let req = infer_req_with_headers(&body, bearer("u5"));

        let resp = handle_infer_with(&state, &req, |_, _| {
            Ok(OpenAiChatResponse {
                choices: vec![OpenAiChoice {
                    message: OpenAiMessage {
                        content: "x".to_string(),
                    },
                }],
                usage: OpenAiUsage {
                    prompt_tokens: 1_000_000,
                    completion_tokens: 1_000_000,
                    total_tokens: 2_000_000,
                },
            })
        });
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        let charged = v["charged_zkcr"].as_f64().unwrap();
        let ceiling = infer_cost_ceiling(1000.0, req.body.len(), Some(10));
        assert!(
            charged <= ceiling + 1e-12,
            "charged {charged} must not exceed reserved ceiling {ceiling}"
        );
    }

    fn canned_panics(
        _worker_uri: &str,
        _body: &serde_json::Value,
    ) -> Result<OpenAiChatResponse, ForwardError> {
        panic!("forward must not run when the auth gate rejects the request");
    }

    #[test]
    fn remote_mode_without_bearer_returns_401_before_forward() {
        let state = state_with_provider(UUID, "gpu-worker-1");
        state.set_local_mode(false); // remote mode: auth required, like /execute
        let req = infer_req(&format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}]}}"#
        ));

        let resp = handle_infer_with(&state, &req, canned_panics);
        assert_eq!(resp.status, 401);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(
            v["error"],
            "API key required. Set Authorization: Bearer <key>"
        );
    }

    #[test]
    fn remote_mode_with_valid_bearer_proceeds() {
        let state = state_with_provider(UUID, "gpu-worker-1");
        state.set_local_mode(false); // remote mode: auth required, like /execute
        let req = infer_req_with_headers(
            &format!(r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}]}}"#),
            vec![(
                "Authorization".to_string(),
                "Bearer zk_user123_abcdef".to_string(),
            )],
        );

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["content"], "hello there");
        assert_eq!(v["charged_zkcr"], 0.0);
    }

    #[test]
    fn local_mode_without_bearer_is_allowed() {
        // Demo/single-host path: local mode stays keyless, mirroring /execute.
        let state = state_with_provider(UUID, "gpu-worker-1"); // already local_mode(true)
        let req = infer_req(&format!(
            r#"{{"model":"zc://{UUID}","messages":[{{"role":"user","content":"hi"}}]}}"#
        ));

        let resp = handle_infer_with(&state, &req, canned_ok);
        assert_eq!(resp.status, 200);
        let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(v["content"], "hello there");
    }
}

fn handle_peer_health(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_handshake_auth(state, request) {
        return resp;
    }
    // broker_id is this node's key-derived identity (`zc://node-<fp>`), never
    // an IP — peers cache this from a successful probe (PeerClient::
    // check_health) to answer the IP-free `/brokers` listing without ever
    // touching the peer's base_url/IP.
    //
    // The response body is signed too (`X-Node-Id`/`X-Node-Sig`, same
    // convention as `/peer/peers`) so `discovery::accept_peer` can bind a
    // gossiped/scanned `(fp, url)` hint to the key that actually answers at
    // `url`, rejecting an address-spoofed peer whose health is signed by a
    // different key than the fp it claims.
    let body = serde_json::to_vec(&peer::PeerHealthResponse {
        status: "healthy".to_string(),
        broker_id: state.node_key.node_uri(),
    })
    .unwrap_or_default();
    let sig = state.node_key.sign(&body);
    BrokerResponse::json_bytes(body, 200)
        .with_header("X-Node-Id", &state.node_key.public_b64())
        .with_header("X-Node-Sig", &sig)
}

fn handle_peer_workers(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(state, request) {
        return resp;
    }
    // Return only this broker's OWN workers — never re-forward peer-discovered
    // ones (they carry Some(source_node), stamped at peer-sync ingest). The old
    // predicate was "uri is loopback", which silently excluded any own worker
    // registered with a reachable address — exactly what `zc serve --advertise`
    // now produces — so an advertised provider was never visible to the rest
    // of the fleet (zc#172).
    let worker_infos: Vec<WorkerInfo> = state
        .workers
        .list()
        .iter()
        .filter(|w| w.source_node.is_none())
        // Peer sync never carries the estimate: it is this broker's own
        // belief about its own workers, of no use to a peer building its
        // routing view, and it would otherwise ride along on every sync tick.
        .map(|w| worker_to_info(w, &state.workers, &state.node_key, false, false))
        .collect();

    json_response(
        &WorkerListResponse {
            total: worker_infos.len(),
            workers: worker_infos,
        },
        200,
    )
}

/// `GET /peer/peers` — signed full-set peer gossip (roster-gated), the
/// forward-compat primitive that feeds spec #2's delta merge. Unlike the
/// permissive `node_sig_gate` used elsewhere during a mixed-version mesh
/// rollout, gossip must ALWAYS pass a strict node-signature check to be
/// served at all — the request itself is peer-authenticated (`verify_request`
/// via `check_node_sig`).
///
/// The response body is signed too: `X-Node-Id` (this node's pubkey) and
/// `X-Node-Sig` (raw Ed25519 signature over the exact JSON body bytes, per
/// `node_identity::verify_sig`), so `discovery::fetch_gossip` can verify the
/// signer and gate on roster membership before trusting any entry.
fn handle_peer_peers(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Err(e) = check_node_sig(
        &state.node_roster,
        &state.node_sig_guard,
        request,
        node_identity::now_secs(),
    ) {
        return error_response(
            &format!("node signature check failed: {e}"),
            "UNAUTHORIZED",
            401,
        );
    }

    let entries: Vec<serde_json::Value> = state
        .peer_manager
        .gossip_entries()
        .into_iter()
        .map(|p| serde_json::json!({"fp": p.fp, "url": p.url, "epoch": p.last_seen}))
        .collect();

    let body = serde_json::to_vec(&serde_json::json!({ "peers": entries })).unwrap_or_default();
    let sig = state.node_key.sign(&body);

    BrokerResponse::json_bytes(body, 200)
        .with_header("X-Node-Id", &state.node_key.public_b64())
        .with_header("X-Node-Sig", &sig)
}

/// `GET /peer/advert` — signed advertisement of this broker's price and
/// aggregated available resources, feeding spec #2's executor selection
/// (task 5). Mirrors `handle_peer_peers` exactly: strict node-signature gate
/// on the inbound request (peer-authenticated, never permissive), and the
/// response body is signed (`X-Node-Id`/`X-Node-Sig`, raw Ed25519 over the
/// exact JSON body bytes) so `discovery::fetch_advert` can verify the signer
/// and roster-gate before trusting it.
///
/// SECURITY: the body carries only fp + price + aggregated resources +
/// epoch — never per-worker IPs/addresses.
fn handle_peer_advert(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Err(e) = check_node_sig(
        &state.node_roster,
        &state.node_sig_guard,
        request,
        node_identity::now_secs(),
    ) {
        return error_response(
            &format!("node signature check failed: {e}"),
            "UNAUTHORIZED",
            401,
        );
    }

    let advert = crate::broker::discovery::Advert {
        fp: state.node_key.fingerprint(),
        price_per_hour: state.price.get(),
        resources: state.workers.aggregate_available(),
        epoch: node_identity::now_secs(),
        build: Some(crate::build_id::current().clone()),
    };

    let body = serde_json::to_vec(&advert).unwrap_or_default();
    let sig = state.node_key.sign(&body);

    BrokerResponse::json_bytes(body, 200)
        .with_header("X-Node-Id", &state.node_key.public_b64())
        .with_header("X-Node-Sig", &sig)
}

fn handle_peer_reserve(state: Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(&state, request) {
        return resp;
    }

    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let req: peer::PeerReserveRequest = match serde_json::from_slice(body) {
        Ok(r) => r,
        Err(e) => return error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400),
    };

    match state
        .ledger
        .local_reserve(&req.user_id, req.amount, &req.request_id)
    {
        Ok((reservation_id, balance_before)) => json_response(
            &peer::PeerReserveResponse {
                reservation_id,
                balance_before,
            },
            200,
        ),
        Err(ledger::LedgerError::InsufficientCredits {
            required,
            available,
        }) => json_response(
            &peer::PeerErrorResponse {
                error: format!(
                    "Insufficient credits: need {:.4}, have {:.4}",
                    required, available
                ),
                code: "INSUFFICIENT_CREDITS".to_string(),
            },
            402,
        ),
        // 503, not 402: we could not determine the balance, so this is our
        // failure to authorize rather than the caller being out of credits.
        // Clients switch on `code`, so it gets its own rather than being
        // flattened into LEDGER_ERROR.
        Err(e @ ledger::LedgerError::BalanceUnavailable { .. }) => json_response(
            &peer::PeerErrorResponse {
                error: e.to_string(),
                code: "BALANCE_UNAVAILABLE".to_string(),
            },
            503,
        ),
        Err(e) => error_response(&e.to_string(), "LEDGER_ERROR", 500),
    }
}

fn handle_peer_commit(state: Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(&state, request) {
        return resp;
    }

    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let req: peer::PeerCommitRequest = match serde_json::from_slice(body) {
        Ok(r) => r,
        Err(e) => return error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400),
    };

    match state
        .ledger
        .local_commit(&req.reservation_id, req.actual_cost)
    {
        Ok(balance_after) => json_response(&peer::PeerCommitResponse { balance_after }, 200),
        Err(e) => error_response(&e.to_string(), "LEDGER_ERROR", 500),
    }
}

fn handle_peer_cancel(state: Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(&state, request) {
        return resp;
    }

    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let req: peer::PeerCancelRequest = match serde_json::from_slice(body) {
        Ok(r) => r,
        Err(e) => return error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400),
    };

    if let Err(e) = state.ledger.local_cancel(&req.reservation_id) {
        eprintln!(
            "  [BILLING] local_cancel failed for {}: {}",
            req.reservation_id, e
        );
    }
    json_response(&serde_json::json!({"status": "ok"}), 200)
}

fn handle_peer_balance(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(state, request) {
        return resp;
    }

    let user_id = request
        .query
        .split('&')
        .find(|p| p.starts_with("user_id="))
        .map(|p| p[8..].to_string())
        .unwrap_or_default();

    if user_id.is_empty() {
        return error_response("Missing user_id parameter", "BAD_REQUEST", 400);
    }

    let balance = state.ledger.load_balance_if_needed(&user_id);
    json_response(&peer::PeerBalanceResponse { user_id, balance }, 200)
}

fn handle_peer_earn(state: Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(&state, request) {
        return resp;
    }

    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let req: peer::PeerEarnRequest = match serde_json::from_slice(body) {
        Ok(r) => r,
        Err(e) => return error_response(&format!("Invalid request: {}", e), "BAD_REQUEST", 400),
    };

    let owner_user_id = match state.config.owner_user_id.as_deref() {
        Some(uid) => uid.to_string(),
        None => {
            return error_response("No owner configured on this broker", "NOT_CONFIGURED", 503);
        }
    };

    let earn_request_id = format!("earn-{}", req.request_id);

    // No dashboard configured (standalone/local-only P2P) — there's nothing to
    // deliver, so mirror `Ledger::publish_transaction`'s existing no-op-when-
    // no-api-configured behavior: skip the WAL entirely rather than append an
    // `Earned` row that could NEVER be marked `Committed` (flush_to_api is
    // only reachable when api_url/api_key are set). Without this guard, a
    // standalone broker would re-replay and re-mint the same earn on every
    // restart forever.
    let dashboard_configured = state.config.api_url.is_some() && state.config.api_key.is_some();

    if dashboard_configured {
        // WAL the earn BEFORE crediting in-memory: if we crash between here and
        // the dashboard flush, replay re-applies it. Left as `Earned` (non-terminal)
        // — it's only marked `Committed` once the periodic tx_buffer flush has
        // actually delivered it to the dashboard (see flush::flush_to_api), so a
        // crash before delivery always leaves it replay-eligible.
        let _ = state.wal.append(&WalEntry {
            request_id: earn_request_id.clone(),
            user_id: owner_user_id.clone(),
            reservation_id: String::new(),
            estimated_cost: req.amount,
            actual_cost: Some(req.amount),
            worker_id: req.worker_id.clone(),
            worker_name: Some(req.worker_id.clone()),
            duration_ms: Some(req.duration_ms),
            timestamp: chrono::Utc::now(),
            status: WalStatus::Earned,
            voucher_nonce: None,
        });
    }

    // Credit in-memory balance
    let balance_after = state.ledger.local_add_credits(&owner_user_id, req.amount);

    // Queue earn transaction for dashboard sync (type "credit" maps to "credit_purchase")
    state.tx_buffer.push_transaction(BufferedTransaction {
        request_id: earn_request_id,
        user_id: owner_user_id.clone(),
        tx_type: "credit".to_string(),
        amount: req.amount,
        balance_after,
        worker_id: req.worker_id.clone(),
        duration_ms: req.duration_ms,
        source_node: state.config.node_name.clone(),
        worker_name: Some(req.worker_id.clone()),
        worker_uri: None,
        price_per_hour: 0.0,
        voucher_nonce: None,
    });
    state
        .tx_buffer
        .snapshot_balance(&owner_user_id, balance_after);

    eprintln!(
        "  [EARN] Worker {} earned {:.6} credits from user {} → owner {} (balance now {:.6})",
        req.worker_id, req.amount, req.requesting_user, owner_user_id, balance_after
    );

    json_response(
        &serde_json::json!({"status": "ok", "balance_after": balance_after}),
        200,
    )
}

fn handle_peer_identity(state: &Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_handshake_auth(state, request) {
        return resp;
    }

    let workers: Vec<task_board::WorkerSummary> = state
        .workers
        .list()
        .iter()
        .filter(|w| state.is_local_worker(&w.uri))
        .map(|w| task_board::WorkerSummary {
            name: w.name.clone(),
            price_per_hour: w.pricing.price_per_hour,
            status: format!("{:?}", w.status),
            cpus: w.resources.cpus_total,
            memory_bytes: w.resources.memory_total,
            gpus: w.resources.gpus_total,
        })
        .collect();

    let identity = task_board::PeerIdentity {
        owner_user_id: state.config.owner_user_id.clone().unwrap_or_default(),
        node_name: state.config.node_name.clone().unwrap_or_default(),
        verified: state.is_billing_enabled(),
        workers,
        quic_port: state.quic_port.load(Ordering::Relaxed),
        // This build supports the two-phase reserve→commit/cancel offer protocol.
        supports_two_phase: true,
        build: Some(crate::build_id::current().clone()),
    };

    json_response(&identity, 200)
}

/// Whether the adaptive policy routes, or only watches.
///
/// Off by default: the shadow ledger is what argues for turning it on, and
/// until a mesh has produced that evidence the safe thing is to keep the
/// routing everyone already understands.
pub fn adaptive_routing_enabled() -> bool {
    matches!(
        std::env::var("ZAKURO_ADAPTIVE_ROUTING")
            .unwrap_or_default()
            .trim()
            .to_ascii_lowercase()
            .as_str(),
        "1" | "true" | "yes" | "on"
    )
}

/// Make a routing decision with the adaptive policy when it is switched on,
/// and otherwise show the policy what was decided, so its ledger keeps
/// accumulating the case for switching.
///
/// `pick` names which selection this path wants; this decides who chooses.
/// Every `/execute` and every peer offer goes through here, so the policy
/// applies to all of this broker's traffic or to none of it — never to one
/// branch because that is where it happened to be wired in.
fn choose_worker(
    state: &BrokerState,
    verbose: bool,
    pick: impl FnOnce(
        Option<crate::broker::router::Adaptive<'_>>,
    ) -> Result<
        crate::broker::router::RoutingDecision,
        crate::broker::router::RoutingError,
    >,
) -> Result<crate::broker::router::RoutingDecision, crate::broker::router::RoutingError> {
    let routing = adaptive_routing_enabled();
    let mut rng = state.shadow.rng_for_routing();
    let weights = crate::broker::policy::Weights::default();
    let decision = pick(routing.then_some(crate::broker::router::Adaptive {
        rng: &mut rng,
        weights: &weights,
    }))?;
    if !routing {
        record_shadow(state, verbose, &decision);
    }
    Ok(decision)
}

/// Show the adaptive policy the decision that was just made, so its ledger can
/// say whether it would have done better. It routes nothing: this is the
/// evidence the switch is argued from.
fn record_shadow(
    state: &BrokerState,
    verbose: bool,
    decision: &crate::broker::router::RoutingDecision,
) {
    let workers = state.workers.healthy();
    let Some(chosen) = workers.iter().position(|w| w.id == decision.worker.id) else {
        return;
    };
    let candidates: Vec<crate::broker::policy::Candidate> = workers
        .iter()
        .map(|w| crate::broker::policy::Candidate {
            stats: w.stats,
            in_flight: w.active_requests,
            price_per_hour: w.pricing.price_per_hour,
            local: w.source_node.is_none(),
        })
        .collect();
    state.shadow.observe(&candidates, chosen);

    // A line every 200 decisions: often enough to watch a run, rare enough
    // not to drown the transaction log it sits in.
    let v = state.shadow.verdict();
    if verbose && v.decisions > 0 && v.decisions.is_multiple_of(200) {
        if let Some(line) = state.shadow.summary() {
            eprintln!("  {line}");
        }
    }
}

/// An offer, as a requirement this broker's router understands.
///
/// An offer carries the same shape of requirement a local request does —
/// resources, a worker type, tags, a timeout, a price ceiling. The offer path
/// used to read three of them, in filters written out by hand next to the
/// router rather than through it.
///
/// `offer.target_worker` is deliberately dropped: worker selection is this
/// broker's private authority, and a client — or a peer relaying one — never
/// names a worker. See
/// docs/superpowers/specs/2026-07-11-zc-key-derived-identity-amendment.md
/// "Routing addendum".
fn offer_requirements(
    offer: &task_board::TaskOffer,
) -> crate::broker::router::ResourceRequirements {
    crate::broker::router::ResourceRequirements {
        cpus: offer.cpus,
        memory_bytes: offer.memory_bytes,
        gpus: offer.gpus,
        worker_type: offer.worker_type.clone(),
        tags: offer.tags.clone(),
        estimated_duration_secs: offer.estimated_duration_secs,
        timeout_secs: offer.timeout_secs,
        ..Default::default()
    }
}

/// Pick — and quota-reserve — a local worker for a peer's offer.
///
/// The same router the broker's own requests go through, so the strategy, the
/// queue term and the adaptive policy reach a peer's work as well. The
/// reservation is the caller's to release: `cancel_offer` for a two-phase
/// reserve, and `execute_offer_locally` when the run fails.
fn reserve_worker_for_offer(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
) -> Result<Worker, task_board::TaskReject> {
    use crate::broker::router::{Scope, Selection};

    let requirements = offer_requirements(offer);
    // In local mode this broker owns everything it can see; otherwise only
    // what it registered itself, resolved the same way direct execution does.
    let own_ip = super::discovery::get_mesh_ip().or_else(|| state.own_wireguard_ip.clone());
    let scope = match state.is_local_mode() {
        true => Scope::Any,
        false => Scope::Local {
            own_ip: own_ip.as_deref(),
        },
    };
    choose_worker(state, false, |adaptive| {
        state.router.select(
            &state.workers,
            Selection {
                requirements: &requirements,
                scope,
                // An offer has always been accepted whatever the worker
                // reported free, in step with the other executing paths.
                check_capacity: false,
                check_labels: true,
                max_price_per_hour: offer.max_price_per_hour,
                // The requester's broker holds the money for a peer's job.
                billed_to: None,
            },
            adaptive,
        )
    })
    .map(|d| d.worker)
    .map_err(|e| task_board::TaskReject {
        task_id: offer.task_id.clone(),
        reason: match e.code.as_str() {
            "QUOTA_EXCEEDED" => "Worker quota exhausted".to_string(),
            _ => "No matching local worker".to_string(),
        },
    })
}

/// Two-phase RESERVE: pick + quota-reserve a local worker and stash the offer
/// (NOT executed), awaiting a commit/cancel. Returns TaskAccept or TaskReject.
pub fn reserve_offer(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
) -> Result<task_board::TaskAccept, task_board::TaskReject> {
    let worker = reserve_worker_for_offer(state, offer)?;
    let estimated_cost = worker.pricing.estimate_cost(offer.estimated_duration_secs);
    state.pending_offers.insert(
        offer.task_id.clone(),
        super::PendingOffer {
            offer: offer.clone(),
            worker_id: worker.id.clone(),
            created: Instant::now(),
        },
    );
    Ok(task_board::TaskAccept {
        task_id: offer.task_id.clone(),
        estimated_cost,
        worker_name: worker.name.clone(),
        executor_owner: state.config.owner_user_id.clone().unwrap_or_default(),
        price_per_hour: worker.pricing.price_per_hour,
    })
}

/// How many reserved-but-uncommitted offers each worker holds (worker id →
/// count). `GET /workers` adds these to `active_requests`: a reservation pins
/// its worker until the commit runs on it, so a drain must not read that
/// worker as idle in the meantime.
pub fn pending_reservations(state: &BrokerState) -> std::collections::HashMap<String, u32> {
    let mut counts = std::collections::HashMap::new();
    for entry in state.pending_offers.iter() {
        *counts.entry(entry.value().worker_id.clone()).or_insert(0) += 1;
    }
    counts
}

/// Two-phase CANCEL: release a reserved offer's quota slot. Idempotent.
pub fn cancel_offer(state: &BrokerState, task_id: &str) {
    if let Some((_, pending)) = state.pending_offers.remove(task_id) {
        state.workers.cancel_quota_reservation(&pending.worker_id);
        release_offer_voucher_claim(state, &pending.offer);
    }
}

/// Two-phase COMMIT: remove and return the reserved offer for execution.
/// None when the task is unknown or already committed/cancelled/expired.
pub fn take_committed(state: &BrokerState, task_id: &str) -> Option<super::PendingOffer> {
    state.pending_offers.remove(task_id).map(|(_, p)| p)
}

/// Release reserved offers older than `ttl` (a lost commit/cancel) so worker
/// slots don't leak. Called periodically by the broker background loop.
pub fn sweep_expired_offers(state: &BrokerState, ttl: std::time::Duration) {
    let stale: Vec<String> = state
        .pending_offers
        .iter()
        .filter(|e| e.value().created.elapsed() > ttl)
        .map(|e| e.key().clone())
        .collect();
    for task_id in stale {
        cancel_offer(state, &task_id);
    }
}

/// Execute a task offer on a local worker, redeeming its voucher when
/// `ZAKURO_REQUIRE_VOUCHER` is set. Peer offers arriving on any transport go
/// through [`run_peer_offer`], which calls this after its own checks.
pub fn execute_offer_locally(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
) -> Result<task_board::TaskResult, task_board::TaskReject> {
    execute_offer_locally_with(state, offer, voucher_required())
}

/// [`execute_offer_locally`] with the voucher requirement passed in.
fn execute_offer_locally_with(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
    require_voucher: bool,
) -> Result<task_board::TaskResult, task_board::TaskReject> {
    // Selecting takes the worker's quota slot, as dispatching does everywhere
    // else. A one-phase offer used to select without reserving, so a peer's
    // work was the one kind this broker ran without counting.
    let worker = reserve_worker_for_offer(state, offer)?;
    let result = run_offer_on(state, offer, &worker, require_voucher);
    if result.is_err() {
        state.workers.cancel_quota_reservation(&worker.id);
    }
    result
}

/// What a peer offer that passed the gates became.
#[derive(Debug)]
pub(crate) enum PeerOfferOutcome {
    /// Two-phase: a worker is reserved, awaiting a commit or a cancel.
    Reserved(task_board::TaskAccept),
    /// One-phase: executed, and its voucher redeemed.
    Executed(task_board::TaskResult),
}

/// The one executor for a peer task offer that has passed its transport's
/// node-signature and voucher gates, shared by `POST /peer/tasks/offer` and
/// QUIC (one-shot and task feed), so the transports cannot drift (zc#423):
///
/// 1. the `target_node` pin: an offer pinned to another node is refused;
/// 2. the voucher claim: when vouchers are required, an offer whose voucher
///    nonce this node already took is refused as a replay;
/// 3. two-phase offers reserve a worker, one-phase offers execute and redeem
///    the voucher.
///
/// A refused, failed or (later) cancelled offer releases its voucher claim, so
/// the requester can still place the job elsewhere or retry it here.
pub(crate) fn run_peer_offer(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
    require_voucher: bool,
) -> Result<PeerOfferOutcome, task_board::TaskReject> {
    let reject = |reason: String| task_board::TaskReject {
        task_id: offer.task_id.clone(),
        reason,
    };
    // NOTE: `offer.target_worker` is intentionally NOT consulted here — a
    // client-supplied worker target is not a valid reason to accept/reject a
    // task offer. Worker selection remains the accepting broker's private
    // authority (see reserve_worker_for_offer).
    //
    // `offer.target_node` IS consulted: which broker runs the work is the
    // requester's choice, and this is the only place that can enforce it
    // whatever route the offer took to get here. Refusing is safe — the
    // dispatcher fails a pinned offer rather than re-offering it elsewhere.
    if let Some(pinned) = offer_pin(offer) {
        if !node_identity::node_filter_matches(&state.node_key, pinned) {
            return Err(reject(format!(
                "Offer is pinned to node {}; this is {}",
                pinned,
                state.node_key.node_uri()
            )));
        }
    }
    let claim = claim_offer_voucher(state, offer, require_voucher)?;
    let outcome = if offer.two_phase {
        reserve_offer(state, offer).map(PeerOfferOutcome::Reserved)
    } else {
        execute_offer_locally_with(state, offer, require_voucher).map(PeerOfferOutcome::Executed)
    };
    if outcome.is_err() {
        release_voucher_claim(state, claim.as_deref());
    }
    outcome
}

/// How long a claimed voucher nonce is kept when its voucher carries no
/// readable expiry (a verified voucher always does).
const VOUCHER_CLAIM_FALLBACK_SECS: u64 = 24 * 3600;

/// Take this offer's voucher nonce for this node. `Ok(None)` when vouchers are
/// not required or the offer carries no nonce; `Ok(Some(nonce))` once taken;
/// `Err` when the nonce is already taken here (a replay). Claims are dropped
/// once their voucher has expired, because an expired voucher no longer passes
/// the voucher gate anyway.
fn claim_offer_voucher(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
    require_voucher: bool,
) -> Result<Option<String>, task_board::TaskReject> {
    if !require_voucher || offer.voucher_signed_json.is_empty() {
        return Ok(None);
    }
    let Some(nonce) = offer_voucher_nonce(offer) else {
        return Ok(None);
    };
    let now = node_identity::now_secs();
    let exp = serde_json::from_str::<serde_json::Value>(&offer.voucher_signed_json)
        .ok()
        .and_then(|v| v.get("exp").and_then(|e| e.as_u64()))
        .unwrap_or(now + VOUCHER_CLAIM_FALLBACK_SECS);
    state.claimed_voucher_nonces.retain(|_, e| *e > now);
    match state.claimed_voucher_nonces.entry(nonce.clone()) {
        dashmap::mapref::entry::Entry::Occupied(_) => {
            eprintln!("  [VOUCHER] refused a replayed voucher nonce: {nonce}");
            Err(task_board::TaskReject {
                task_id: offer.task_id.clone(),
                reason: "voucher check failed: voucher already used on this node".to_string(),
            })
        }
        dashmap::mapref::entry::Entry::Vacant(v) => {
            v.insert(exp);
            Ok(Some(nonce))
        }
    }
}

/// Give a voucher claim back: the offer it covered was refused, failed or was
/// cancelled, so nothing was redeemed under it.
fn release_voucher_claim(state: &BrokerState, nonce: Option<&str>) {
    if let Some(nonce) = nonce {
        state.claimed_voucher_nonces.remove(nonce);
    }
}

/// [`release_voucher_claim`] for an offer's own nonce, whatever the flags.
fn release_offer_voucher_claim(state: &BrokerState, offer: &task_board::TaskOffer) {
    release_voucher_claim(state, offer_voucher_nonce(offer).as_deref());
}

/// The task feed's executor (`run_subscription_client`): [`run_peer_offer`]
/// for one-phase offers. The feed has no commit or cancel message, so a
/// two-phase offer is refused before anything is reserved.
pub fn execute_feed_offer(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
    require_voucher: bool,
) -> Result<task_board::TaskResult, task_board::TaskReject> {
    if offer.two_phase {
        return Err(task_board::TaskReject {
            task_id: offer.task_id.clone(),
            reason: "two-phase offers are not taken over the task feed".to_string(),
        });
    }
    match run_peer_offer(state, offer, require_voucher)? {
        PeerOfferOutcome::Executed(result) => Ok(result),
        PeerOfferOutcome::Reserved(accept) => {
            cancel_offer(state, &accept.task_id);
            Err(task_board::TaskReject {
                task_id: accept.task_id,
                reason: "two-phase offers are not taken over the task feed".to_string(),
            })
        }
    }
}

/// Run an offer on a specific (already-selected, possibly pre-reserved) worker:
/// decode the payload, forward to the worker, build the TaskResult. Used by the
/// one-phase path (execute_offer_locally) and by the two-phase commit (which
/// runs on the worker it reserved).
fn run_offer_on(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
    worker: &Worker,
    require_voucher: bool,
) -> Result<task_board::TaskResult, task_board::TaskReject> {
    // A P2P offer must count toward active_requests for the whole forward
    // (through the response read), exactly like /execute — otherwise a
    // draining worker mid-P2P-job reports 0 active requests and the agent
    // sends SIGTERM before the job completes (spec §6.5). Held for the entire
    // function body; dropped (decrementing) on every return path, including
    // the early payload-decode error below.
    let _active_guard = state.workers.active_guard(&worker.id);
    // Paid work like /execute: it cancels a running benchmark and holds the
    // next one off. Peer and QUIC offers have already been authenticated.
    let _inflight = super::InflightGuard::new(state);

    let payload = base64::Engine::decode(
        &base64::engine::general_purpose::STANDARD,
        &offer.payload_b64,
    )
    .map_err(|e| task_board::TaskReject {
        task_id: offer.task_id.clone(),
        reason: format!("Invalid payload encoding: {}", e),
    })?;

    let worker_uri = format!("{}/execute", worker.uri.trim_end_matches('/'));
    let start = Instant::now();
    let timeout = if offer.timeout_secs > 0.0 {
        offer.timeout_secs
    } else {
        300.0
    };
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(std::time::Duration::from_secs_f64(timeout + 5.0)))
            .build(),
    );

    let forward_result = agent
        .post(&worker_uri)
        .header("Content-Type", "application/octet-stream")
        .header("X-Zakuro-Request-Id", &offer.task_id)
        .header("X-Zakuro-Timeout-Secs", &format!("{:.1}", timeout))
        .send(&payload);

    let duration_ms = start.elapsed().as_secs_f64() * 1000.0;

    match forward_result {
        Ok(response) => {
            let actual_cost = worker.pricing.estimate_cost(duration_ms / 1000.0);
            let worker_pid = response
                .headers()
                .get("X-Zakuro-Pid")
                .and_then(|v| v.to_str().ok())
                .map(|s| s.to_string());
            let mut response_body = Vec::new();
            let _ = response
                .into_body()
                .into_reader()
                .read_to_end(&mut response_body);
            let result_b64 =
                base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &response_body);
            let executor_owner = state.config.owner_user_id.clone().unwrap_or_default();
            // Redeem the voucher nonce (double-spend guard). Best-effort and only
            // when vouchers are in use; settlement still rides the existing path.
            redeem_offer_voucher(state, offer, actual_cost, require_voucher);
            let mut result = task_board::TaskResult {
                task_id: offer.task_id.clone(),
                payload_b64: result_b64,
                duration_ms,
                actual_cost,
                worker_name: worker.name.clone(),
                worker_uri: worker.zc_uri(),
                price_per_hour: worker.pricing.price_per_hour,
                executor_owner,
                worker_pid,
                executor_node_uri: state.node_key.node_uri(),
                executor_node_id: None,
                executor_sig: None,
            };
            result.executor_node_id = Some(state.node_key.public_b64());
            result.executor_sig = Some(state.node_key.sign(&task_board::receipt_bytes(&result)));
            Ok(result)
        }
        Err(e) => Err(task_board::TaskReject {
            task_id: offer.task_id.clone(),
            reason: format!("Worker execution failed: {}", e),
        }),
    }
}

fn handle_peer_task_offer(state: Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(&state, request) {
        return resp;
    }

    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let offer: task_board::TaskOffer = match serde_json::from_slice(body) {
        Ok(o) => o,
        Err(e) => return error_response(&format!("Invalid task offer: {}", e), "BAD_REQUEST", 400),
    };

    // Zero-trust authorization: the dashboard-signed voucher must cover this spend
    // (no-op unless ZAKURO_REQUIRE_VOUCHER is set). Reject before reserving/executing.
    let require_voucher = voucher_required();
    if let Err(reason) = verify_offer_voucher_with(&state, &offer, require_voucher) {
        return error_response(
            &format!("voucher check failed: {reason}"),
            "VOUCHER_INVALID",
            402,
        );
    }

    // The pin, the voucher claim, and two-phase (RESERVE, execute on commit)
    // or one-phase (execute now) — the same core QUIC offers go through.
    match run_peer_offer(&state, &offer, require_voucher) {
        Ok(PeerOfferOutcome::Reserved(accept)) => json_response(&accept, 200),
        Ok(PeerOfferOutcome::Executed(result)) => json_response(&result, 200),
        Err(reject) => json_response(&reject, 404),
    }
}

/// Two-phase COMMIT: execute the previously-reserved offer on its reserved
/// worker and return the result. Unknown/expired task → reject.
fn handle_peer_task_commit(state: Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(&state, request) {
        return resp;
    }
    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let commit: task_board::TaskCommit = match serde_json::from_slice(body) {
        Ok(c) => c,
        Err(e) => return error_response(&format!("Invalid commit: {}", e), "BAD_REQUEST", 400),
    };
    match take_committed(&state, &commit.task_id) {
        Some(pending) => match state.workers.get(&pending.worker_id) {
            Some(worker) => match run_offer_on(&state, &pending.offer, &worker, voucher_required())
            {
                Ok(result) => json_response(&result, 200),
                Err(reject) => {
                    release_offer_voucher_claim(&state, &pending.offer);
                    json_response(&reject, 404)
                }
            },
            None => {
                release_offer_voucher_claim(&state, &pending.offer);
                json_response(
                    &task_board::TaskReject {
                        task_id: commit.task_id.clone(),
                        reason: "Reserved worker no longer available".to_string(),
                    },
                    404,
                )
            }
        },
        None => json_response(
            &task_board::TaskReject {
                task_id: commit.task_id.clone(),
                reason: "Unknown or expired reservation".to_string(),
            },
            404,
        ),
    }
}

/// Two-phase CANCEL: release a previously-reserved offer (no execution).
fn handle_peer_task_cancel(state: Arc<BrokerState>, request: &BrokerRequest) -> BrokerResponse {
    if let Some(resp) = peer_credit_auth(&state, request) {
        return resp;
    }
    let body = match body_or_413(request) {
        Ok(b) => b,
        Err(resp) => return resp,
    };
    let cancel: task_board::TaskCancel = match serde_json::from_slice(body) {
        Ok(c) => c,
        Err(e) => return error_response(&format!("Invalid cancel: {}", e), "BAD_REQUEST", 400),
    };
    cancel_offer(&state, &cancel.task_id);
    json_response(
        &serde_json::json!({ "status": "cancelled", "task_id": cancel.task_id }),
        200,
    )
}

// ── execute helpers ──────────────────────────────────────────────────────────

/// Forward a request body to a worker, with an optional hard timeout, reusing
/// the broker's shared connection-pooled agent (no fresh TCP+TLS per call).
/// The per-request timeout is set on the request builder so a single agent
/// serves every worker call (async-phase-2: connection pooling).
fn forward_to_worker(
    agent: &ureq::Agent,
    worker_uri: &str,
    body: &[u8],
    request_id: &str,
    effective_timeout: f64,
) -> Result<ureq::http::Response<ureq::Body>, ureq::Error> {
    forward_to_worker_with(
        agent,
        worker_uri,
        body,
        request_id,
        effective_timeout,
        DEFAULT_FORWARD_TIMEOUT_SECS,
    )
}

fn forward_to_worker_with(
    agent: &ureq::Agent,
    worker_uri: &str,
    body: &[u8],
    request_id: &str,
    effective_timeout: f64,
    default_timeout_secs: f64,
) -> Result<ureq::http::Response<ureq::Body>, ureq::Error> {
    let mut req = agent
        .post(worker_uri)
        .config()
        .timeout_global(Some(std::time::Duration::from_secs_f64(
            forward_timeout_secs(effective_timeout, default_timeout_secs),
        )))
        .build()
        .header("Content-Type", "application/octet-stream")
        .header("X-Zakuro-Request-Id", request_id);
    if effective_timeout > 0.0 {
        req = req.header(
            "X-Zakuro-Timeout-Secs",
            &format!("{:.1}", effective_timeout),
        );
    }
    req.send(body)
}

/// The agent for a synchronous forward: the direct pooled client for a worker
/// on this machine, and the sidecar-proxied pooled client for any other
/// worker, which on a proxy-route host is the only route onto the mesh (#242).
///
/// Both are long-lived, which is the point. This used to build a fresh agent
/// per forward via `mesh_agent_for`, and a fresh `ureq::Agent` carries a fresh
/// connection pool -- so every request to a peer opened a new TCP connection
/// across the mesh and threw it away, exactly the cost `http_client` was
/// introduced to stop paying. The async path already did it this way
/// (`pick_forward_client` over `async_http`/`async_http_mesh`); this is the
/// same shape for the sync one.
///
/// A host with no sidecar has no proxied agent and dials every worker direct.
pub(crate) fn pick_forward_agent<'a>(
    direct: &'a ureq::Agent,
    mesh: Option<&'a ureq::Agent>,
    worker_uri: &str,
) -> &'a ureq::Agent {
    match mesh {
        Some(agent) if !crate::vpn::is_loopback_url(worker_uri) => agent,
        _ => direct,
    }
}

struct WorkerReply {
    status: u16,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
}

/// Timeout for a worker forward when the caller names none. Without it, a
/// worker that never answers holds `/execute` open for as long as the client
/// waits: #242 measured 120 s against a mesh worker the host could not reach.
const DEFAULT_FORWARD_TIMEOUT_SECS: f64 = 60.0;

/// How long a forward may take. An explicit caller timeout keeps its five
/// seconds of slack over the worker's own budget; no timeout means the default.
fn forward_timeout_secs(effective_timeout: f64, default_secs: f64) -> f64 {
    if effective_timeout > 0.0 {
        effective_timeout + 5.0
    } else {
        default_secs
    }
}

/// The client a forward to `worker_uri` should use: a worker on this machine is
/// dialed directly, any other worker goes through the sidecar's CONNECT proxy,
/// which on a proxy-route host is the only route onto the mesh (#242). A host
/// with no sidecar has no proxied client and dials every worker directly.
fn pick_forward_client<'a>(
    direct: &'a reqwest::Client,
    mesh: Option<&'a reqwest::Client>,
    worker_uri: &str,
) -> &'a reqwest::Client {
    match mesh {
        Some(client) if !crate::vpn::is_loopback_url(worker_uri) => client,
        _ => direct,
    }
}

async fn forward_to_worker_async(
    client: &reqwest::Client,
    worker_uri: &str,
    body: Vec<u8>,
    request_id: &str,
    effective_timeout: f64,
) -> Result<WorkerReply, String> {
    forward_to_worker_async_with(
        client,
        worker_uri,
        body,
        request_id,
        effective_timeout,
        DEFAULT_FORWARD_TIMEOUT_SECS,
    )
    .await
}

async fn forward_to_worker_async_with(
    client: &reqwest::Client,
    worker_uri: &str,
    body: Vec<u8>,
    request_id: &str,
    effective_timeout: f64,
    default_timeout_secs: f64,
) -> Result<WorkerReply, String> {
    let mut req = client
        .post(worker_uri)
        .header("Content-Type", "application/octet-stream")
        .header("X-Zakuro-Request-Id", request_id)
        .timeout(std::time::Duration::from_secs_f64(forward_timeout_secs(
            effective_timeout,
            default_timeout_secs,
        )))
        .body(body);
    if effective_timeout > 0.0 {
        req = req.header("X-Zakuro-Timeout-Secs", format!("{:.1}", effective_timeout));
    }
    let resp = req.send().await.map_err(|e| e.to_string())?;
    let status = resp.status().as_u16();
    let headers = resp
        .headers()
        .iter()
        .map(|(k, v)| {
            (
                k.as_str().to_lowercase(),
                v.to_str().unwrap_or("").to_string(),
            )
        })
        .collect();
    let body = resp.bytes().await.map_err(|e| e.to_string())?.to_vec();
    Ok(WorkerReply {
        status,
        headers,
        body,
    })
}

/// Convert a ureq HTTP response into a `WorkerReply`.
///
/// Header names are lowercased so that downstream code can do
/// case-insensitive lookups by comparing against lowercase literals.
fn into_worker_reply(resp: ureq::http::Response<ureq::Body>) -> WorkerReply {
    let status = resp.status().as_u16();
    let headers = resp
        .headers()
        .iter()
        .map(|(k, v)| {
            (
                k.as_str().to_lowercase(),
                v.to_str().unwrap_or("").to_string(),
            )
        })
        .collect();
    let mut body = Vec::new();
    let _ = resp.into_body().into_reader().read_to_end(&mut body);
    WorkerReply {
        status,
        headers,
        body,
    }
}

/// True when a worker reply says the instance no longer exists
/// (ZAK-0016: "Instance not found: <id> (expired or evicted)").
fn instance_gone(body: &[u8], instance_id: &str) -> bool {
    let needle = format!("Instance not found: {}", instance_id);
    let n = needle.as_bytes();
    !n.is_empty() && body.windows(n.len()).any(|w| w == n)
}

/// Look up a header value from a `WorkerReply` by name, case-insensitively.
///
/// Because `into_worker_reply` lowercases all names, passing a lowercase
/// literal is sufficient.  Mixed-case callers work too since we normalise
/// the needle as well.
fn reply_header<'a>(reply: &'a WorkerReply, name: &str) -> Option<&'a str> {
    let needle = name.to_lowercase();
    reply
        .headers
        .iter()
        .find(|(k, _)| *k == needle)
        .map(|(_, v)| v.as_str())
}

/// Post-forward half of execute: WAL EXECUTED, commit/refund, WAL COMMITTED,
/// ledger/buffer updates, response building, and the synchronous retry path.
///
/// `forward` is the outcome of calling `forward_to_worker` (converted to a
/// `WorkerReply` via `into_worker_reply`) or an error string.
///
/// NOTE: Callers must call `state.workers.increment_active(&p.worker.id)` before
/// forwarding. `execute_finish` is responsible for decrementing `p.worker.id`
/// exactly once on every exit path (success via `record_request`, and
/// timeout/no-worker/retry-exhausted via `decrement_active`).
///
/// NOTE: The one-shot retry inside this function is still synchronous
/// (`forward_to_worker` + `into_worker_reply`). The primary /execute forward
/// runs async via `forward_to_worker_async`; this sync path serves the retry
/// and non-axum callers (bench).
fn execute_finish(
    state: &Arc<BrokerState>,
    verbose: bool,
    mut p: PreparedForward,
    forward: Result<WorkerReply, String>,
) -> BrokerResponse {
    // The gap since the `forward` mark is the wait for a blocking-pool slot,
    // not work — see the `queue` mark in `execute_prepare`.
    p.phases.mark("finish_queue");
    let worker_name = p.worker.name.clone();
    let duration_ms = p.start.elapsed().as_secs_f64() * 1000.0;

    match forward {
        Ok(reply) => {
            // Calculate actual cost (free for local worker)
            let actual_cost = if p.is_local {
                0.0
            } else {
                let actual_duration_secs = duration_ms / 1000.0;
                p.worker.pricing.estimate_cost(actual_duration_secs)
            };

            // WAL: mark as executed (critical — if we crash here, recovery will commit)
            if !p.is_local {
                let _ = state.wal.update_status(
                    &p.request_id,
                    WalStatus::Executed,
                    Some(actual_cost),
                    Some(duration_ms),
                );
            }

            // Commit reservation + publish transaction — authority-aware
            let credits_remaining = commit_credits(
                state,
                &p.authority,
                p.is_local,
                &p.reservation_id,
                actual_cost,
                p.balance_before,
                &p.request_id,
                &p.user_id,
                &p.worker,
                duration_ms,
                p.commission_c,
                &p.voucher_task_nonce,
            );

            // WAL: the entry stays `Executed`. The debit `commit_credits` just
            // queued is owed to the hub until a flush delivers it, and that
            // flush retires the entry (`flush::retire_delivered`). Marking it
            // Committed here, after the in-memory commit only, is what let a
            // broker killed with the row still queued lose the requester's
            // debit while replay re-delivered the owner's earn for the same
            // job (zc-worker-i9-2, 2026-10-02). A row delivered some other way
            // stays replayable until restart, and the hub dedupes it by
            // request_id.

            // Update worker stats — record_request also decrements the in-flight
            // counter (via WorkerRegistry::decrement_active internally).
            state
                .workers
                .record_request(&p.worker.id, duration_ms, true);
            state.active_requests.remove(&p.request_id);

            // Header lookups use lowercase names (into_worker_reply lowercases).
            let worker_pid = reply_header(&reply, "x-zakuro-pid").map(|s| s.to_string());
            let worker_ip = reply_header(&reply, "x-zakuro-ip")
                .map(|s| s.to_string())
                .or_else(|| {
                    let u = p
                        .worker
                        .uri
                        .strip_prefix("http://")
                        .unwrap_or(&p.worker.uri);
                    u.split(':').next().map(|s| s.to_string())
                });

            let response_body = reply.body;

            // Register instance affinity: pin instance_id → worker_id
            if p.instance_action.as_deref() == Some("create_instance") {
                if let Some(ref iid) = p.instance_id {
                    state
                        .instance_registry
                        .insert(iid.clone(), p.worker.id.clone());
                }
            }

            // Drop the affinity entry when the instance is gone on the worker:
            // an explicit release, or a "not found" answer (idle TTL / evicted).
            // Surfaced to the caller as-is, never re-placed (see `affinity`).
            if let Some(iid) = p.instance_id.as_deref() {
                match p.instance_action.as_deref() {
                    Some("release_instance") => {
                        state.instance_registry.remove(iid);
                    }
                    Some("call_method") if instance_gone(&response_body, iid) => {
                        state.instance_registry.remove(iid);
                    }
                    _ => {}
                }
            }

            // Log transaction with agreed price and worker identity (owner_id, pid, ip)
            let action_label = match p.instance_action.as_deref() {
                Some("create_instance") => "CREATE_INST",
                Some("call_method") => "CALL_METHOD",
                _ => "EXECUTE",
            };
            log_transaction_with_worker_info(
                state,
                verbose,
                p.tx_num,
                &p.user_id,
                action_label,
                actual_cost,
                credits_remaining,
                Some(&worker_name),
                duration_ms,
                "OK",
                Some(p.worker.pricing.price_per_hour),
                state.config.owner_user_id.as_deref(),
                worker_pid.as_deref(),
                worker_ip.as_deref(),
                Some(&p.request_id),
            );

            let headers = [
                header_or("Content-Type", "application/octet-stream"),
                header_or("X-Zakuro-Request-Id", &p.request_id),
                header_or("X-Zakuro-Worker", worker_name.as_str()),
                header_or("X-Zakuro-Cost", &format!("{:.6}", actual_cost)),
                header_or(
                    "X-Zakuro-Credits-Remaining",
                    &format!("{:.6}", credits_remaining),
                ),
                header_or("X-Zakuro-Duration-Ms", &format!("{:.2}", duration_ms)),
                header_or("X-Zakuro-Transport", "local"),
                header_or("X-Zakuro-Reason", &sanitize_reason_header(&p.reason)),
            ];
            let mut resp = BrokerResponse {
                status: 200,
                headers: Vec::new(),
                body: response_body,
            };
            resp.headers.extend(headers);
            // Settlement runs after `duration_ms` is taken, so it is invisible
            // to every other number on this response. Mark it last and report
            // the whole walk when the caller asked for it.
            p.phases.mark("settle");
            if p.trace {
                resp.headers
                    .push(header_or("X-Zakuro-Phases", &p.phases.header()));
            }
            resp
        }
        Err(e) => {
            // When a timeout fires, the worker may still be running. Charge for
            // the wall-clock time the request was in flight so a malicious user
            // can't abuse a long-running function for free.
            let is_timeout = e.contains("timed out") || e.contains("Timeout");

            let timeout_cost = if is_timeout && !p.is_local {
                let elapsed_secs = duration_ms / 1000.0;
                // Never charge more than was reserved (the reservation is itself
                // capped at the user's balance): elapsed-time billing on a slow
                // worker could otherwise exceed the hold (audit M2).
                capped_charge(
                    p.worker.pricing.estimate_cost(elapsed_secs),
                    p.reservation_amount,
                )
            } else {
                0.0
            };

            if is_timeout {
                // ── Timeout: partial charge, no retry ────────────────────────
                if !p.is_local && timeout_cost > 0.0 {
                    match &p.authority {
                        Authority::Local => {
                            if let Err(e) =
                                state.ledger.local_commit(&p.reservation_id, timeout_cost)
                            {
                                eprintln!(
                                    "  [BILLING] local_commit failed for {}: {}",
                                    p.request_id, e
                                );
                            }
                            state.tx_buffer.push_transaction(BufferedTransaction {
                                request_id: p.request_id.clone(),
                                user_id: p.user_id.clone(),
                                tx_type: "commit".to_string(),
                                amount: timeout_cost,
                                balance_after: p.balance_before - timeout_cost,
                                worker_id: p.worker.id.clone(),
                                duration_ms,
                                source_node: state.config.node_name.clone(),
                                worker_name: Some(p.worker.name.clone()),
                                worker_uri: Some(p.worker.uri.clone()),
                                price_per_hour: p.worker.pricing.price_per_hour,
                                voucher_nonce: nonce_opt(&p.voucher_task_nonce),
                            });
                        }
                        Authority::Peer(url) => {
                            if let Some(client) = state.peer_manager.get_client(url) {
                                let _ = client.commit(&p.reservation_id, timeout_cost);
                            } else {
                                let _ = state.ledger.commit(&p.reservation_id, timeout_cost);
                            }
                            state.ledger.publish_transaction_for_voucher(
                                &p.request_id,
                                &p.user_id,
                                "commit",
                                timeout_cost,
                                p.balance_before - timeout_cost,
                                WorkerName::of(&p.worker),
                                duration_ms,
                                state.config.node_name.as_deref(),
                                Some(p.voucher_task_nonce.as_str()).filter(|n| !n.is_empty()),
                            );
                        }
                        Authority::Standalone => {
                            let _ = state.ledger.commit(&p.reservation_id, timeout_cost);
                            state.ledger.publish_transaction_for_voucher(
                                &p.request_id,
                                &p.user_id,
                                "commit",
                                timeout_cost,
                                p.balance_before - timeout_cost,
                                WorkerName::of(&p.worker),
                                duration_ms,
                                state.config.node_name.as_deref(),
                                Some(p.voucher_task_nonce.as_str()).filter(|n| !n.is_empty()),
                            );
                        }
                    }
                    let _ = state.wal.update_status(
                        &p.request_id,
                        WalStatus::Committed,
                        Some(timeout_cost),
                        Some(duration_ms),
                    );
                }
                state.active_requests.remove(&p.request_id);
                log_transaction(
                    state,
                    verbose,
                    p.tx_num,
                    &p.user_id,
                    "EXECUTE",
                    timeout_cost,
                    p.balance_before - timeout_cost,
                    Some(&worker_name),
                    duration_ms,
                    "FAIL",
                );
                // Don't mark as unhealthy — the worker is fine, just slow
                // Decrement the outer worker's in-flight counter (no RAII guard in this path).
                state.workers.decrement_active(&p.worker.id);
                return error_response(
                    &format!(
                        "Request timed out after {:.1}s (charged {:.6} credits)",
                        duration_ms / 1000.0,
                        timeout_cost
                    ),
                    "TIMEOUT",
                    504,
                );
            }

            // ── Non-timeout failure: cancel reservation + retry on another worker ─
            // Mark the failed worker unhealthy so it won't be selected again.
            state.workers.mark_unhealthy(&p.worker.id);
            // Return the pre-committed quota slot so it doesn't count against the worker.
            state.workers.cancel_quota_reservation(&p.worker.id);

            // Cancel reservation (full refund) for the failed attempt.
            if !p.is_local {
                cancel_credits(
                    state,
                    &p.authority,
                    &p.reservation_id,
                    &p.request_id,
                    &p.user_id,
                    &p.worker.id,
                    p.balance_before,
                    duration_ms,
                );
            }
            state.active_requests.remove(&p.request_id);
            // Decrement the outer worker's in-flight counter (no RAII guard in this path).
            state.workers.decrement_active(&p.worker.id);

            // Try remaining healthy workers (up to MAX_RETRIES attempts).
            const MAX_RETRIES: usize = 2;
            let mut tried_ids: Vec<String> = vec![p.worker.id.clone()];

            for attempt in 1..=MAX_RETRIES {
                // Find next healthy worker not yet attempted
                let next_worker = {
                    let healthy = state.workers.healthy();
                    healthy.into_iter().find(|w| !tried_ids.contains(&w.id))
                };

                let next = match next_worker {
                    Some(w) => w,
                    None => {
                        log_transaction(
                            state,
                            verbose,
                            p.tx_num,
                            &p.user_id,
                            "EXECUTE",
                            0.0,
                            p.balance_before,
                            Some(&worker_name),
                            duration_ms,
                            "FAIL",
                        );
                        return error_response(
                            &format!(
                                "Worker unreachable and no fallback available (tried {} worker(s))",
                                tried_ids.len()
                            ),
                            "NO_WORKERS",
                            503,
                        );
                    }
                };

                let retry_uri = format!("{}/execute", next.uri.trim_end_matches('/'));
                let retry_name = next.name.clone();
                tried_ids.push(next.id.clone());

                // Atomically reserve a quota slot on the retry worker.
                // Skip it if its quota is already full.
                if !state.workers.try_reserve_quota(&next.id) {
                    continue;
                }

                eprintln!(
                    "  [RETRY] attempt {}/{} → {} ({})",
                    attempt, MAX_RETRIES, retry_name, retry_uri
                );

                // Per-attempt in-flight guard: decrements on a failed attempt
                // (loop continues → drop) or is disarmed on success below.
                let mut retry_guard = state.workers.active_guard(&next.id);
                state
                    .active_requests
                    .insert(p.request_id.clone(), next.id.clone());

                let retry_start = Instant::now();
                // Retry is still synchronous in this phase; the async path covers only
                // the first forward (see task-6).
                let retry_result = forward_to_worker(
                    pick_forward_agent(
                        &state.http_client,
                        state.http_client_mesh.as_ref(),
                        &retry_uri,
                    ),
                    &retry_uri,
                    &p.body,
                    &p.request_id,
                    p.effective_timeout,
                )
                .map(into_worker_reply)
                .map_err(|e| e.to_string());

                let retry_duration_ms = retry_start.elapsed().as_secs_f64() * 1000.0;

                match retry_result {
                    Ok(retry_reply) => {
                        let actual_cost = if p.is_local {
                            0.0
                        } else {
                            next.pricing.estimate_cost(retry_duration_ms / 1000.0)
                        };

                        // Billing for the retry: reserve then immediately commit (execution already done).
                        let retry_reservation_id = if !p.is_local {
                            let res_id = format!("{}-retry{}", p.request_id, attempt);
                            match &p.authority {
                                Authority::Local => {
                                    let _ = state.ledger.local_reserve(
                                        &p.user_id,
                                        actual_cost,
                                        &res_id,
                                    );
                                    let _ = state.ledger.local_commit(&res_id, actual_cost);
                                }
                                Authority::Peer(url) => {
                                    // Forward reserve + immediate commit to authoritative peer.
                                    if let Some(client) = state.peer_manager.get_client(url) {
                                        if client.reserve(&p.user_id, actual_cost, &res_id).is_ok()
                                        {
                                            let _ = client.commit(&res_id, actual_cost);
                                        }
                                    }
                                }
                                Authority::Standalone => {
                                    // Standalone: reserve from local_credits (already loaded) + commit.
                                    if state
                                        .ledger
                                        .reserve(&p.user_id, actual_cost, &res_id)
                                        .is_ok()
                                    {
                                        let _ = state.ledger.commit(&res_id, actual_cost);
                                    }
                                }
                            }
                            res_id
                        } else {
                            String::new()
                        };

                        // Executed, not Committed: owed until the flush delivers
                        // the debit (see the main path in `execute_finish`).
                        if !p.is_local {
                            let _ = state.wal.update_status(
                                &p.request_id,
                                WalStatus::Executed,
                                Some(actual_cost),
                                Some(retry_duration_ms),
                            );
                        }

                        state
                            .workers
                            .record_request(&next.id, retry_duration_ms, true);
                        retry_guard.disarm();
                        state.active_requests.remove(&p.request_id);

                        let credits_remaining = if p.is_local {
                            p.balance_before
                        } else {
                            p.balance_before - actual_cost
                        };

                        // Queue retry transaction to tx_buffer (flushed periodically to dashboard)
                        state.tx_buffer.push_transaction(BufferedTransaction {
                            request_id: format!("{}-retry{}", p.request_id, attempt),
                            user_id: p.user_id.clone(),
                            tx_type: "commit".to_string(),
                            amount: actual_cost,
                            balance_after: credits_remaining,
                            worker_id: next.id.clone(),
                            duration_ms: retry_duration_ms,
                            source_node: state.config.node_name.clone(),
                            worker_name: Some(next.name.clone()),
                            worker_uri: Some(next.uri.clone()),
                            price_per_hour: next.pricing.price_per_hour,
                            voucher_nonce: None,
                        });

                        let action_label = match p.instance_action.as_deref() {
                            Some("create_instance") => "CREATE_INST",
                            Some("call_method") => "CALL_METHOD",
                            _ => "EXECUTE",
                        };
                        log_transaction(
                            state,
                            verbose,
                            p.tx_num,
                            &p.user_id,
                            action_label,
                            actual_cost,
                            credits_remaining,
                            Some(&retry_name),
                            retry_duration_ms,
                            "OK",
                        );

                        let response_body = retry_reply.body;

                        let _ = retry_reservation_id; // suppress unused warning
                        let headers = [
                            header_or("Content-Type", "application/octet-stream"),
                            header_or("X-Zakuro-Request-Id", &p.request_id),
                            header_or("X-Zakuro-Cost", &format!("{:.6}", actual_cost)),
                            header_or(
                                "X-Zakuro-Credits-Remaining",
                                &format!("{:.6}", credits_remaining),
                            ),
                            header_or("X-Zakuro-Duration-Ms", &format!("{:.2}", retry_duration_ms)),
                            header_or("X-Zakuro-Retries", &format!("{}", attempt)),
                            header_or("X-Zakuro-Reason", &sanitize_reason_header(&p.reason)),
                        ];
                        let mut resp = BrokerResponse {
                            status: 200,
                            headers: Vec::new(),
                            body: response_body,
                        };
                        resp.headers.extend(headers);
                        return resp;
                    }
                    Err(_retry_err) => {
                        // This retry also failed — mark unhealthy, cancel quota slot, continue
                        state.workers.mark_unhealthy(&next.id);
                        state.workers.cancel_quota_reservation(&next.id);
                        state.active_requests.remove(&p.request_id);
                    }
                }
            }

            // All retries exhausted
            log_transaction(
                state,
                verbose,
                p.tx_num,
                &p.user_id,
                "EXECUTE",
                0.0,
                p.balance_before,
                Some(&worker_name),
                duration_ms,
                "FAIL",
            );
            error_response(
                &format!(
                    "All workers unreachable after {} retries (tried: {})",
                    MAX_RETRIES,
                    tried_ids.join(", ")
                ),
                "NO_WORKERS",
                503,
            )
        }
    }
}

/// Reserve credits — authority-aware.
/// Returns `Ok(reservation_id)` or `Err(error_response)` for early exit.
#[allow(clippy::too_many_arguments)]
fn reserve_credits(
    state: &Arc<BrokerState>,
    authority: &peer::Authority,
    user_id: &str,
    amount: f64,
    request_id: &str,
    verbose: bool,
    tx_num: u64,
    balance_before: f64,
) -> Result<String, BrokerResponse> {
    let fail = |msg: &str, code: &str, status: u16| -> Result<String, _> {
        log_transaction(
            state,
            verbose,
            tx_num,
            user_id,
            "EXECUTE",
            0.0,
            balance_before,
            None,
            0.0,
            "FAIL",
        );
        Err(error_response(msg, code, status))
    };

    match authority {
        peer::Authority::Local => match state.ledger.local_reserve(user_id, amount, request_id) {
            Ok((id, _)) => Ok(id),
            Err(ledger::LedgerError::InsufficientCredits {
                required,
                available,
            }) => fail(
                &format!(
                    "Insufficient credits: need {:.4}, have {:.4}",
                    required, available
                ),
                "INSUFFICIENT_CREDITS",
                402,
            ),
            Err(e @ ledger::LedgerError::BalanceUnavailable { .. }) => {
                fail(&e.to_string(), "BALANCE_UNAVAILABLE", 503)
            }
            Err(e) => fail(&e.to_string(), "LEDGER_ERROR", 503),
        },
        peer::Authority::Peer(url) => {
            let peer_result = state
                .peer_manager
                .get_client(url)
                .and_then(|c| c.reserve(user_id, amount, request_id).ok())
                .map(|r| r.reservation_id);
            if let Some(id) = peer_result {
                return Ok(id);
            }
            eprintln!(
                "  [P2P] Peer reserve failed ({}), falling back to local",
                url
            );
            reserve_via_ledger(
                state,
                user_id,
                amount,
                request_id,
                verbose,
                tx_num,
                balance_before,
            )
        }
        peer::Authority::Standalone => reserve_via_ledger(
            state,
            user_id,
            amount,
            request_id,
            verbose,
            tx_num,
            balance_before,
        ),
    }
}

fn reserve_via_ledger(
    state: &Arc<BrokerState>,
    user_id: &str,
    amount: f64,
    request_id: &str,
    verbose: bool,
    tx_num: u64,
    balance_before: f64,
) -> Result<String, BrokerResponse> {
    let fail = |msg: &str, code: &str, status: u16| -> Result<String, _> {
        log_transaction(
            state,
            verbose,
            tx_num,
            user_id,
            "EXECUTE",
            0.0,
            balance_before,
            None,
            0.0,
            "FAIL",
        );
        Err(error_response(msg, code, status))
    };
    match state.ledger.reserve(user_id, amount, request_id) {
        Ok(id) => Ok(id),
        Err(ledger::LedgerError::InsufficientCredits {
            required,
            available,
        }) => fail(
            &format!(
                "Insufficient credits: need {:.4}, have {:.4}",
                required, available
            ),
            "INSUFFICIENT_CREDITS",
            402,
        ),
        Err(e @ ledger::LedgerError::BalanceUnavailable { .. }) => {
            fail(&e.to_string(), "BALANCE_UNAVAILABLE", 503)
        }
        Err(e) => fail(&e.to_string(), "LEDGER_ERROR", 503),
    }
}

/// Cancel a credit reservation — authority-aware.
/// Also publishes a "cancel" transaction and updates the WAL.
/// Only call when `!is_local`.
#[allow(clippy::too_many_arguments)]
fn cancel_credits(
    state: &Arc<BrokerState>,
    authority: &peer::Authority,
    reservation_id: &str,
    request_id: &str,
    user_id: &str,
    worker_id: &str,
    balance_before: f64,
    duration_ms: f64,
) {
    match authority {
        peer::Authority::Local => {
            if let Err(e) = state.ledger.local_cancel(reservation_id) {
                eprintln!("  [BILLING] local_cancel failed for {}: {}", request_id, e);
            }
        }
        peer::Authority::Peer(url) => {
            if let Some(client) = state.peer_manager.get_client(url) {
                if let Err(e) = client.cancel(reservation_id) {
                    eprintln!("  [BILLING] peer cancel failed for {}: {}", request_id, e);
                }
            } else if let Err(e) = state.ledger.cancel(reservation_id) {
                eprintln!("  [BILLING] cancel failed for {}: {}", request_id, e);
            }
        }
        peer::Authority::Standalone => {
            if let Err(e) = state.ledger.cancel(reservation_id) {
                eprintln!("  [BILLING] cancel failed for {}: {}", request_id, e);
            }
        }
    }
    // Queue cancel to tx_buffer — flushed periodically to dashboard.
    // For Peer authority the peer itself records the cancel; we still log it here for auditing.
    state.tx_buffer.push_transaction(BufferedTransaction {
        request_id: request_id.to_string(),
        user_id: user_id.to_string(),
        tx_type: "cancel".to_string(),
        amount: 0.0,
        balance_after: balance_before,
        worker_id: worker_id.to_string(),
        duration_ms,
        source_node: state.config.node_name.clone(),
        worker_name: None,
        worker_uri: None,
        price_per_hour: 0.0,
        voucher_nonce: None,
    });
    let _ = state.wal.update_status(
        request_id,
        super::wal::WalStatus::Failed,
        None,
        Some(duration_ms),
    );
}

/// Commit a credit reservation and return the new balance.
/// Handles all authority paths, queues tx_buffer entries, and (for `Local`)
/// triggers the earn notification to the worker's broker.
/// Pay the executor's broker `cost*(1-commission_c)` and — when
/// `commission_c > 0` and billing is enabled — credit the platform-house
/// account (both ledger caches) with `cost*commission_c`. `payout+commission
/// == cost` always (see `split_commission`), so this single call is the ONE
/// place executor earn is computed for a remote settlement — every remote
/// money path (the offer path and the direct-forward path) must route
/// through here so commission is universal and the conservation invariant
/// (requester −cost == executor +payout + platform +commission) can't drift
/// between call sites. `commission_c == 0.0` degrades to the legacy
/// uncommissioned payout (`payout == cost`) — callers on a `voucher_required`
/// path must never reach here with `commission_c == 0.0` for a remote job
/// (see the fail-closed minting in `execute_prepare` / `dispatch_to_peers`).
#[allow(clippy::too_many_arguments)]
fn settle_executor_payout(
    state: &Arc<BrokerState>,
    user_id: &str,
    cost: f64,
    commission_c: f64,
    executor_peer_url: &str,
    executor_worker: crate::broker::worker::WorkerName<'_>,
    request_id: &str,
    duration_ms: f64,
) {
    let (payout, commission) = split_commission(cost, commission_c);
    if commission > 0.0 && state.is_billing_enabled() {
        let platform_uid =
            std::env::var("ZAKURO_PLATFORM_UID").unwrap_or_else(|_| "platform-house".into());
        state
            .ledger
            .local_credits
            .entry(platform_uid.clone())
            .and_modify(|b| *b += commission)
            .or_insert(commission);
        state
            .ledger
            .authoritative_balances
            .entry(platform_uid)
            .and_modify(|b| *b += commission)
            .or_insert(commission);
    }
    // Resolve the executor to a REGISTERED peer before paying it. The executor
    // identifies itself by the address it believes it has
    // (`http://<own_ip>:<port>`, see `our_url` in `start_server`), but it is
    // registered under whatever `ZAKURO_PEERS` spelled -- possibly a DNS name.
    // Same host, different spelling: the exact-string lookup missed and every
    // remote job fell into the refund arm below, so the executor was never paid
    // for work it really did. IP-configured deployments are unaffected either
    // way (the spellings coincide, and the exact match is tried first).
    let settle_url = state
        .peer_manager
        .get_url_for_endpoint(executor_peer_url)
        .unwrap_or_else(|| executor_peer_url.to_string());
    let earn_ok = match state.peer_manager.get_client(&settle_url) {
        Some(client) => match client.earn(
            payout,
            duration_ms,
            executor_worker.as_str(),
            user_id,
            request_id,
        ) {
            Ok(_) => true,
            Err(e) => {
                eprintln!(
                    "  [EARN] Failed to notify peer {}: {}",
                    executor_peer_url, e
                );
                false
            }
        },
        None => {
            // Print what was looked up AND what it resolved to: when these
            // differ, the peer is registered under another spelling and the
            // real fault is a registry mismatch, not an unreachable executor.
            eprintln!(
                "  [EARN] No client for peer {} (resolved to {}, request {}): executor unreachable, refunding payout to requester",
                executor_peer_url, settle_url, request_id
            );
            false
        }
    };

    // The executor's broker could not be paid (unreachable, or the earn RPC
    // failed — e.g. it restarted between returning the job result and
    // receiving this earn call). The requester was already debited `cost`
    // by the caller; refund `payout` back so the requester nets only
    // `-commission` (platform keeps its cut, executor got nothing, and the
    // three legs sum to zero: requester -commission, executor +0, platform
    // +commission). Only valid on the path where the requester was actually
    // debited `cost` for this job — see the callers of
    // `settle_executor_payout`.
    let refund = earn_refund_amount(payout, earn_ok);
    if refund > 0.0 && state.is_billing_enabled() {
        state
            .ledger
            .local_credits
            .entry(user_id.to_string())
            .and_modify(|b| *b += refund)
            .or_insert(refund);
        state
            .ledger
            .authoritative_balances
            .entry(user_id.to_string())
            .and_modify(|b| *b += refund)
            .or_insert(refund);
        state.tx_buffer.push_transaction(BufferedTransaction {
            request_id: format!("{request_id}-earn-refund"),
            user_id: user_id.to_string(),
            tx_type: "refund".to_string(),
            amount: refund,
            balance_after: 0.0,
            worker_id: executor_worker.as_str().to_string(),
            duration_ms,
            source_node: state.config.node_name.clone(),
            worker_name: Some(executor_worker.as_str().to_string()),
            worker_uri: None,
            price_per_hour: 0.0,
            voucher_nonce: None,
        });
    }
}

/// The executing node's fingerprint for settlement routing. `Worker::node_fp`
/// is stamped for peer-synced workers by `discovery::peer_node_fp` and for
/// local workers from this node's own key. Deliberately has NO address
/// fallback: an unstamped worker routes to the full-refund arm rather than to
/// a lucky exact host match (which never fired behind a proxy/NAT anyway).
fn executor_fp(worker: &Worker) -> Option<&str> {
    if worker.node_fp.is_empty() {
        None
    } else {
        Some(worker.node_fp.as_str())
    }
}

/// The executing worker is one of THIS broker's own: stamped with our node
/// fingerprint when it registered (`discovery` / `POST /workers`). Keyed on
/// identity, never on address — the same rule as every other settlement
/// site: an address match would call a NAT'd or proxied peer "ours" and pay
/// nobody. An unstamped worker is NOT ours here; it takes the existing
/// unresolved-executor refund arm.
fn executor_is_self(state: &BrokerState, worker: &Worker) -> bool {
    executor_fp(worker).is_some_and(|fp| fp == state.node_key.fingerprint())
}

/// Whether this broker's own hardware ran the job.
///
/// Identity first, and identity alone wherever there is any. A worker stamped
/// with a node fingerprint is ours if and only if that fingerprint is ours —
/// `is_local_worker` is not consulted, because it answers a different
/// question and answers it by address. In local mode it returns true for
/// every worker there is, which is right for the single-node broker it was
/// written for and wrong the moment a mesh node registers with one.
///
/// Only an unstamped worker falls back to the address heuristic, which is the
/// best that can be said about one.
fn ran_on_our_hardware(state: &BrokerState, worker: &Worker) -> bool {
    match executor_fp(worker) {
        Some(fp) => fp == state.node_key.fingerprint(),
        None => state.is_local_worker(&worker.uri),
    }
}

/// Whether a voucher minted here for this authority will also be redeemed
/// here — the only question that makes minting safe.
///
/// It used to be "does this broker settle the requester's credits", and the
/// answer for `Peer` was no, so `Peer` refused to mint. That was the right
/// instinct guarding the wrong thing. Redeeming a nonce needs the nonce and
/// this broker's own api key, not the requester's shard; what `Peer` actually
/// lacked was the executor payout, because `commit_credits`'s `Peer` arm
/// forwarded the charge and then simply stopped — no earn, no redeem (#333).
/// With that arm settling the executor side like the others, all three
/// authorities redeem what they mint.
///
/// Exhaustive on purpose. The compiler makes whoever adds an `Authority`
/// variant answer this question rather than inherit a `true` they never
/// considered.
fn redeems_here(authority: &Authority) -> bool {
    match authority {
        Authority::Local | Authority::Standalone | Authority::Peer(_) => true,
    }
}

/// Whether an execution costs nothing.
///
/// Both halves are required, and they answer different questions.
/// `is_self_owned` is about the requester: whose credits would be spent.
/// `self_executed` is about the worker: whose compute was spent. A job is
/// free only when the answer to both is "the owner's".
///
/// Dropping either half has been a real bug in both directions. Without
/// `is_self_owned`, every direct request a fleet broker's own worker could
/// serve ran at cost 0 while the same job forwarded to a peer was billed.
/// Without `self_executed` (#297), the owner's job ran free on somebody
/// else's hardware — a broker dispatches to every worker registered with it
/// down one path, wherever that worker's machine is, so the peer whose
/// machine did the work was never paid for it.
fn execution_is_free(billing_enabled: bool, is_self_owned: bool, self_executed: bool) -> bool {
    !billing_enabled || (is_self_owned && self_executed)
}

/// Who gets paid for the work, resolved from the executing worker's
/// key-derived identity.
///
/// Resolution is a purely local lookup — a stamped fingerprint and the peer
/// registry, no network — which is what lets the caller ask *before* charging
/// anyone. That ordering matters on `Authority::Peer`, where the requester's
/// ledger is somebody else's: there the only honest response to an
/// unresolvable executor is to never charge at all, because this broker has no
/// way to refund a ledger it does not own.
enum ExecutorSide {
    /// This broker's own hardware: the owner is credited on this ledger.
    Owner,
    /// Another node, reachable at this base URL.
    Peer(String),
    /// No stamped `node_fp`, or no peer's cached fingerprint matches it.
    /// Happens under chaos when a peer is briefly evicted mid-restart.
    Unresolved,
}

fn resolve_executor(state: &BrokerState, worker: &worker::Worker) -> ExecutorSide {
    if executor_is_self(state, worker) {
        return ExecutorSide::Owner;
    }
    match executor_fp(worker).and_then(|fp| state.peer_manager.get_url_for_fingerprint(fp)) {
        Some(url) => ExecutorSide::Peer(url),
        None => ExecutorSide::Unresolved,
    }
}

/// Settle the executor side of a billed job and report the balance to return.
///
/// Called on every authority. `Local` and `Standalone` both settle on this
/// broker's own ledger — one because it owns the user's shard, the other
/// because there is no shard to own. `Peer` debited the requester on somebody
/// else's ledger, but neither leg here touches that shard: the earn is
/// addressed to the executor's node fingerprint, and the redeem is a dashboard
/// call keyed by nonce under this broker's api key. It used to be skipped
/// there anyway, which is what made remote work on a peer-sharded requester
/// unpayable (#333).
///
/// Three legs move together or not at all: the executor's earn, the platform
/// house credit, and the dashboard voucher redeem. Where the executor cannot
/// be resolved none of them fire and the requester is refunded in full, so the
/// job conserves rather than charging for work nobody was paid for. That
/// refund credits THIS ledger, so it is only correct when the requester was
/// debited here — under `Authority::Peer` the caller resolves the executor
/// first and cancels the reservation instead of ever reaching this branch.
#[allow(clippy::too_many_arguments)]
fn settle_executor_side(
    state: &Arc<BrokerState>,
    user_id: &str,
    actual_cost: f64,
    balance: f64,
    request_id: &str,
    worker: &worker::Worker,
    duration_ms: f64,
    commission_c: f64,
    voucher_task_nonce: &str,
) -> f64 {
    let exec_fp = executor_fp(worker);
    match resolve_executor(state, worker) {
        // Self-executed for a foreign requester: the executor is this very
        // broker, so pay the owner here and redeem — no peer hop to resolve.
        ExecutorSide::Owner => {
            settle_self_payout(
                state,
                user_id,
                actual_cost,
                commission_c,
                worker,
                request_id,
                duration_ms,
            );
            redeem_task_nonce(state, voucher_task_nonce, actual_cost);
            balance
        }
        ExecutorSide::Peer(peer_url) => {
            settle_executor_payout(
                state,
                user_id,
                actual_cost,
                commission_c,
                &peer_url,
                WorkerName::of(worker),
                request_id,
                duration_ms,
            );
            // Redeem the voucher this broker minted for this remote job
            // (fail-closed minting happens in `execute_prepare` — this is
            // the authoritative dashboard credit for the platform-house
            // commission, mirroring `redeem_offer_voucher` on the offer
            // path). Best-effort: logs and continues on failure — the
            // executor earn + platform cache credit already happened just
            // above via `settle_executor_payout`.
            if !voucher_task_nonce.is_empty() {
                if let (Some(api_url), Some(api_key)) =
                    (&state.config.api_url, &state.config.api_key)
                {
                    match super::node_sync::redeem_voucher(
                        api_url,
                        api_key,
                        voucher_task_nonce,
                        actual_cost,
                    ) {
                        Ok(true) => {}
                        Ok(false) => eprintln!(
                            "  [VOUCHER] nonce already spent (double-spend attempt?): {voucher_task_nonce}"
                        ),
                        Err(e) => eprintln!("  [VOUCHER] redeem failed: {e}"),
                    }
                }
            }
            balance
        }
        ExecutorSide::Unresolved => {
            // Executor peer could not be resolved from the executing
            // node's identity — either the worker carries no stamped
            // `node_fp`, or no peer's cached fingerprint matches it
            // (happens under chaos when the peer is temporarily evicted
            // from the registry mid-restart): pay nobody and redeem
            // nothing (redeeming here would credit the platform
            // commission with no offsetting executor earn). The whole
            // settlement failed — no executor earn, no platform-house
            // credit, no voucher redeem — so the requester, already
            // debited `actual_cost` via `local_commit` above, must be
            // made whole for the FULL charge (not just `payout`).
            // Net: requester -actual_cost +actual_cost = 0, executor 0,
            // platform 0 → the job effectively didn't bill, conserving.
            eprintln!(
                "  [EARN] UNRESOLVED executor peer for node={} \
                 (request {request_id}): no executor payout/redeem — refunding \
                 requester {actual_cost:.6} in full to conserve",
                exec_fp
                    .map(|f| format!("zc://node-{f}"))
                    .unwrap_or_else(|| "<unstamped>".into())
            );
            if state.is_billing_enabled() {
                state
                    .ledger
                    .local_credits
                    .entry(user_id.to_string())
                    .and_modify(|b| *b += actual_cost)
                    .or_insert(actual_cost);
                state
                    .ledger
                    .authoritative_balances
                    .entry(user_id.to_string())
                    .and_modify(|b| *b += actual_cost)
                    .or_insert(actual_cost);
                state.tx_buffer.push_transaction(BufferedTransaction {
                    request_id: format!("{request_id}-unresolved-refund"),
                    user_id: user_id.to_string(),
                    tx_type: "refund".to_string(),
                    amount: actual_cost,
                    balance_after: balance + actual_cost,
                    worker_id: worker.id.clone(),
                    duration_ms,
                    source_node: state.config.node_name.clone(),
                    worker_name: Some(worker.name.clone()),
                    worker_uri: Some(worker.uri.clone()),
                    price_per_hour: worker.pricing.price_per_hour,
                    voucher_nonce: None,
                });
            }
            balance
        }
    }
}

/// The predicates that decide whether money moves, and whether this broker
/// may promise that it will.
#[cfg(test)]
mod settlement_predicate_tests {
    use super::{execution_is_free, redeems_here};
    use crate::broker::peer::Authority;

    #[test]
    fn free_needs_both_the_owner_and_the_owners_hardware() {
        // "Self-hosted jobs are free" — the case that must keep working.
        assert!(execution_is_free(true, true, true));
    }

    #[test]
    fn the_owners_job_on_someone_elses_worker_is_billed() {
        // #297. A broker dispatches to every worker registered with it down
        // one path, wherever that worker's machine is. Deciding the charge
        // from requester identity alone ran the owner's work free on other
        // people's hardware, and they were never paid.
        assert!(!execution_is_free(true, true, false));
    }

    #[test]
    fn a_foreign_requester_pays_even_on_this_brokers_own_worker() {
        assert!(!execution_is_free(true, false, true));
        assert!(!execution_is_free(true, false, false));
    }

    #[test]
    fn nothing_is_billed_when_there_is_no_billing_authority() {
        for owned in [true, false] {
            for here in [true, false] {
                assert!(execution_is_free(false, owned, here), "({owned}, {here})");
            }
        }
    }

    /// `ran_on_our_hardware` has had no test, and it is the half of the #297
    /// rule that says whose machine ran the job.
    ///
    /// A peer worker is stamped with the PEER's fingerprint by discovery, so
    /// identity alone answers this and the answer is "not ours". The bug this
    /// pins is the `local_mode` fallback: `is_local_worker` returns true for
    /// every worker there is once local mode is on, so a mesh broker in local
    /// mode calls every peer's hardware its own and runs the owner's work free
    /// on all of it.
    #[test]
    fn a_peer_worker_is_never_our_hardware_even_in_local_mode() {
        use super::ran_on_our_hardware;
        use crate::broker::worker::WorkerRegistration;
        use crate::broker::BrokerState;

        let state = BrokerState::new();
        let peer = state.workers.register(WorkerRegistration {
            name: "worker-zc-worker-x399-1".into(),
            uri: "http://10.13.13.20:3960".into(),
            worker_type: "zakuro".into(),
            resources: Default::default(),
            pricing: Default::default(),
            tags: vec![],
            max_timeout_secs: 0.0,
            hardware: Default::default(),
            wireguard_ip: Some("10.13.13.20".into()),
            is_docker: None,
            source_node: Some("node-6188100f5daf463e".into()),
            explicit_local: false,
            provider_type: Default::default(),
            served_models: vec![],
            price_per_mtok: 0.0,
        });
        let peer = state
            .workers
            .set_node_fp(&peer.id, "6188100f5daf463e")
            .expect("stamped");
        assert_ne!(
            peer.node_fp,
            state.node_key.fingerprint(),
            "fixture must describe a DIFFERENT node"
        );

        assert!(
            !ran_on_our_hardware(&state, &peer),
            "a peer's worker is not our hardware"
        );

        // The regression: local mode must not turn every peer into us.
        state.set_local_mode(true);
        assert!(
            !ran_on_our_hardware(&state, &peer),
            "local mode called a peer's hardware ours, so the owner's work on \
             it was free and the peer was never paid (#297/#329)"
        );
    }

    #[test]
    fn a_broker_on_its_own_ledger_may_mint_a_voucher() {
        // Local because it owns the user's shard, Standalone because there is
        // no shard to own. Both redeem what they mint.
        assert!(redeems_here(&Authority::Local));
        assert!(redeems_here(&Authority::Standalone));
    }

    /// A worker with no resolvable executor must not be charged for.
    ///
    /// On `Authority::Local` this is recoverable — charge, then refund on the
    /// same ledger. On `Authority::Peer` it is not: the debit lands on the
    /// peer's ledger and this broker has no verb to reverse it, because
    /// `/peer/earn` credits the receiving broker's OWNER rather than an
    /// arbitrary user. So the caller must ask BEFORE charging, which is why
    /// resolution is a local lookup and not a peer round trip.
    #[test]
    fn an_unstamped_worker_has_no_resolvable_executor() {
        use super::{resolve_executor, ExecutorSide};
        use crate::broker::worker::WorkerRegistration;
        use crate::broker::BrokerState;

        let state = BrokerState::new();
        let orphan = state.workers.register(WorkerRegistration {
            name: "worker-from-a-departed-node".into(),
            uri: "http://10.13.13.77:3960".into(),
            worker_type: "zakuro".into(),
            resources: Default::default(),
            pricing: Default::default(),
            tags: vec![],
            max_timeout_secs: 0.0,
            hardware: Default::default(),
            wireguard_ip: Some("10.13.13.77".into()),
            is_docker: None,
            // Stamped as a peer's, so it is not ours ...
            source_node: Some("node-ffffffffffffffff".into()),
            explicit_local: false,
            provider_type: Default::default(),
            served_models: vec![],
            price_per_mtok: 0.0,
        });
        let orphan = state
            .workers
            .set_node_fp(&orphan.id, "ffffffffffffffff")
            .expect("stamped");

        // ... and no peer in the registry carries that fingerprint.
        assert!(
            matches!(resolve_executor(&state, &orphan), ExecutorSide::Unresolved),
            "a worker whose node is not in the peer registry has nobody to pay"
        );
    }

    #[test]
    fn our_own_worker_resolves_to_the_owner() {
        use super::{resolve_executor, ExecutorSide};
        use crate::broker::worker::WorkerRegistration;
        use crate::broker::BrokerState;

        let state = BrokerState::new();
        let mine = state.workers.register(WorkerRegistration {
            name: "worker-local-1".into(),
            uri: "http://127.0.0.1:3960".into(),
            worker_type: "zakuro".into(),
            resources: Default::default(),
            pricing: Default::default(),
            tags: vec![],
            max_timeout_secs: 0.0,
            hardware: Default::default(),
            wireguard_ip: None,
            is_docker: None,
            source_node: None,
            explicit_local: true,
            provider_type: Default::default(),
            served_models: vec![],
            price_per_mtok: 0.0,
        });
        let fp = state.node_key.fingerprint();
        let mine = state
            .workers
            .set_node_fp(&mine.id, &fp)
            .expect("stamped with our own fingerprint");

        assert!(
            matches!(resolve_executor(&state, &mine), ExecutorSide::Owner),
            "our own hardware pays the owner on this ledger, with no peer hop"
        );
    }

    #[test]
    fn a_broker_settling_on_a_peers_ledger_may_mint_too() {
        // #333. This refused, and on an N-broker mesh a user is the shard
        // owner on exactly one broker — so on the other N−1 every remote job
        // was refused outright and the mesh could not use itself.
        //
        // Redeeming needs the nonce and this broker's own api key, not the
        // requester's shard. What `Peer` actually lacked was the executor
        // payout: `commit_credits` forwarded the charge and stopped. That arm
        // now settles the executor side like the others, so the nonce this
        // mint produces is redeemed.
        assert!(redeems_here(&Authority::Peer(
            "http://10.0.0.2:9000".into()
        )));
    }
}

#[allow(clippy::too_many_arguments)]
fn commit_credits(
    state: &Arc<BrokerState>,
    authority: &peer::Authority,
    is_local: bool,
    reservation_id: &str,
    actual_cost: f64,
    balance_before: f64,
    request_id: &str,
    user_id: &str,
    worker: &worker::Worker,
    duration_ms: f64,
    commission_c: f64,
    voucher_task_nonce: &str,
) -> f64 {
    if is_local {
        // No dashboard POST here. A local job is free (amount 0.0), and the
        // row it produces is delivered by the 30 s-batched `tx_buffer` below,
        // which exists precisely to keep the hub off the hot path. Posting it
        // synchronously as well bought nothing -- `/api/broker/batch-sync`
        // carries a superset of `/api/broker/transaction`'s fields and the hub
        // dedupes on `request_id` -- and cost a full TCP+TLS round trip to the
        // dashboard on every single request. Against stg that is ~800 ms, which
        // is what `zc bench -s best_latency` was measuring per `add(2, 3)`
        // while the broker logged 1-4 ms: `duration_ms` is taken at the top of
        // `execute_finish`, so this call sat outside it, invisible to both the
        // reported latency and the router's estimates.
        if state.is_billing_enabled() {
            state.tx_buffer.push_transaction(BufferedTransaction {
                request_id: request_id.to_string(),
                user_id: user_id.to_string(),
                tx_type: "commit".to_string(),
                amount: 0.0,
                balance_after: balance_before,
                worker_id: worker.id.clone(),
                duration_ms,
                source_node: state.config.node_name.clone(),
                worker_name: Some(worker.name.clone()),
                worker_uri: Some(worker.uri.clone()),
                price_per_hour: worker.pricing.price_per_hour,
                voucher_nonce: None,
            });
        }
        return balance_before;
    }

    match authority {
        peer::Authority::Local => {
            let balance = match state.ledger.local_commit(reservation_id, actual_cost) {
                Ok(b) => b,
                Err(e) => {
                    eprintln!("  [P2P] Local commit error for {}: {}", request_id, e);
                    balance_before - actual_cost
                }
            };
            state.tx_buffer.push_transaction(BufferedTransaction {
                request_id: request_id.to_string(),
                user_id: user_id.to_string(),
                tx_type: "commit".to_string(),
                amount: actual_cost,
                balance_after: balance,
                worker_id: worker.id.clone(),
                duration_ms,
                source_node: state.config.node_name.clone(),
                worker_name: Some(worker.name.clone()),
                worker_uri: Some(worker.uri.clone()),
                price_per_hour: worker.pricing.price_per_hour,
                voucher_nonce: nonce_opt(voucher_task_nonce),
            });
            state.tx_buffer.snapshot_balance(user_id, balance);
            // Notify provider's broker that their worker earned credits, net of
            // platform commission (`commission_c`, stamped in the dashboard
            // voucher minted in `execute_prepare` for this remote job — see
            // `settle_executor_payout`). Gross basis is `actual_cost` — the SAME
            // amount the requester was debited above — so payout+commission ==
            // actual_cost and the legs net to zero. Deriving earn from
            // wall-clock `duration_ms` diverges from the committed charge under
            // concurrency (queue latency inflates it), minting credits — the
            // conservation bug a stress test surfaced. `duration_ms` stays as
            // transaction metadata only.
            // ALL THREE money legs (executor earn, platform-house cache credit,
            // and the dashboard voucher redeem that authoritatively credits
            // platform commission) must happen together or not at all. Keeping
            // the redeem OUTSIDE this guard could credit the platform its
            // commission while the executor earn never fires (unresolvable
            // peer) — requester −cost, executor +0, platform +commission →
            // credits unaccounted, requester overcharged. Bind them atomically.
            // Settlement is keyed by the executor's key-derived node identity
            // (`zc://node-<fp>`), never by an address: a peer reached via the
            // sidecar CONNECT proxy or behind NAT has a base-URL host that is
            // not its worker's IP, so the old exact-host match silently paid
            // nobody for real work.
            settle_executor_side(
                state,
                user_id,
                actual_cost,
                balance,
                request_id,
                worker,
                duration_ms,
                commission_c,
                voucher_task_nonce,
            )
        }
        peer::Authority::Peer(url) => {
            // The requester's ledger lives on `url`, not here. This arm used to
            // commit the charge and stop: no executor payout, no voucher
            // redeem. On a mesh of N brokers a user is the shard owner on only
            // one of them, so on the other N−1 every remote job charged the
            // requester and paid the node that did the work nothing — which is
            // why minting was fail-closed upstream (#333). Closing the hole is
            // what makes minting safe, so the settlement is done here rather
            // than the refusal kept.
            //
            // Resolve the executor BEFORE charging. On `Authority::Local` an
            // unresolvable executor is recoverable — charge, then refund on the
            // same ledger. Here it is not: the debit would land on the peer's
            // ledger and this broker has no verb to reverse it (`/peer/earn`
            // credits the receiving broker's OWNER, not an arbitrary user). So
            // the reservation is cancelled instead of committed and nobody is
            // charged at all — the same net zero the local path reaches by
            // refunding, reached by not charging.
            let executor = resolve_executor(state, worker);
            if matches!(executor, ExecutorSide::Unresolved) {
                eprintln!(
                    "  [EARN] UNRESOLVED executor for node={} (request {request_id}): \
                     cancelling the reservation on authority {url} rather than charging \
                     for work nobody can be paid for",
                    executor_fp(worker)
                        .map(|f| format!("zc://node-{f}"))
                        .unwrap_or_else(|| "<unstamped>".into())
                );
                if let Some(client) = state.peer_manager.get_client(url) {
                    if let Err(e) = client.cancel(reservation_id) {
                        // The reservation is left to expire on the peer. Still
                        // strictly better than committing a charge with no
                        // offsetting payout.
                        eprintln!("  [P2P] Peer cancel failed ({url}) for {request_id}: {e}");
                    }
                }
                return balance_before;
            }

            let peer_balance = if let Some(client) = state.peer_manager.get_client(url) {
                match client.commit(reservation_id, actual_cost) {
                    Ok(resp) => {
                        state.tx_buffer.push_transaction(BufferedTransaction {
                            request_id: request_id.to_string(),
                            user_id: user_id.to_string(),
                            tx_type: "commit".to_string(),
                            amount: actual_cost,
                            balance_after: resp.balance_after,
                            worker_id: worker.id.clone(),
                            duration_ms,
                            source_node: state.config.node_name.clone(),
                            worker_name: Some(worker.name.clone()),
                            worker_uri: Some(worker.uri.clone()),
                            price_per_hour: worker.pricing.price_per_hour,
                            voucher_nonce: nonce_opt(voucher_task_nonce),
                        });
                        Some(resp.balance_after)
                    }
                    Err(e) => {
                        eprintln!(
                            "  [P2P] Peer commit failed ({}), falling back to local: {}",
                            url, e
                        );
                        None
                    }
                }
            } else {
                None
            };
            let balance = match peer_balance {
                Some(b) => b,
                None => {
                    state.ledger.publish_transaction_for_voucher(
                        request_id,
                        user_id,
                        "commit",
                        actual_cost,
                        balance_before - actual_cost,
                        WorkerName::of(worker),
                        duration_ms,
                        state.config.node_name.as_deref(),
                        Some(voucher_task_nonce).filter(|n| !n.is_empty()),
                    );
                    match state.ledger.commit(reservation_id, actual_cost) {
                        Ok(b) => b,
                        Err(e) => {
                            eprintln!("  [LEDGER] Commit error for {}: {}", request_id, e);
                            balance_before - actual_cost
                        }
                    }
                }
            };
            // The requester has been charged — now pay the executor and redeem
            // the nonce, exactly as `Authority::Local` does. Both legs are
            // reachable from a non-authority broker: the earn is addressed to
            // the executor's node fingerprint, and the redeem is a dashboard
            // call keyed by nonce under THIS broker's api key. Neither touches
            // the requester's shard, which is the only thing living on `url`.
            //
            // `executor` was resolved above and is not `Unresolved`, so
            // `settle_executor_side`'s refund branch — which credits the LOCAL
            // ledger and would be the wrong ledger here — is unreachable from
            // this path.
            settle_executor_side(
                state,
                user_id,
                actual_cost,
                balance,
                request_id,
                worker,
                duration_ms,
                commission_c,
                voucher_task_nonce,
            )
        }
        peer::Authority::Standalone => {
            let balance = match state.ledger.commit(reservation_id, actual_cost) {
                Ok(b) => b,
                Err(e) => {
                    eprintln!(
                        "  [LEDGER] Commit error for {}: {} (WAL has record)",
                        request_id, e
                    );
                    balance_before - actual_cost
                }
            };
            // Queue to tx_buffer (flushed periodically) instead of synchronous API call
            state.tx_buffer.push_transaction(BufferedTransaction {
                request_id: request_id.to_string(),
                user_id: user_id.to_string(),
                tx_type: "commit".to_string(),
                amount: actual_cost,
                balance_after: balance,
                worker_id: worker.id.clone(),
                duration_ms,
                source_node: state.config.node_name.clone(),
                worker_name: Some(worker.name.clone()),
                worker_uri: Some(worker.uri.clone()),
                price_per_hour: worker.pricing.price_per_hour,
                voucher_nonce: nonce_opt(voucher_task_nonce),
            });
            // P2P off (single broker, billing on). The requester's ledger is
            // this one, so the executor side settles exactly as it does under
            // `Authority::Local` — including for an executor on ANOTHER node.
            //
            // It used to settle only `executor_is_self`, so a job on a worker
            // belonging to somebody else paid nobody. `total_brokers <= 1` is
            // Standalone, and a broker with nine mesh nodes registered against
            // it still reports `index=0/1` — so this is the ordinary case for
            // a workstation on a mesh, not a corner (#297).
            settle_executor_side(
                state,
                user_id,
                actual_cost,
                balance,
                request_id,
                worker,
                duration_ms,
                commission_c,
                voucher_task_nonce,
            )
        }
    }
}

/// A voucher `task_nonce` as the optional wire field: `None` when the job has
/// no voucher (`""`), so nothing is sent for it (zc#400).
fn nonce_opt(nonce: &str) -> Option<String> {
    (!nonce.is_empty()).then(|| nonce.to_string())
}

/// Redeem a minted voucher's nonce at the dashboard (double-spend guard +
/// authoritative platform commission). No-op without a nonce or api creds;
/// best-effort, logs and continues — settlement on this ledger already stands.
fn redeem_task_nonce(state: &Arc<BrokerState>, voucher_task_nonce: &str, actual_cost: f64) {
    if voucher_task_nonce.is_empty() {
        return;
    }
    if let (Some(api_url), Some(api_key)) = (&state.config.api_url, &state.config.api_key) {
        match super::node_sync::redeem_voucher(api_url, api_key, voucher_task_nonce, actual_cost) {
            Ok(true) => {}
            Ok(false) => eprintln!(
                "  [VOUCHER] nonce already spent (double-spend attempt?): {voucher_task_nonce}"
            ),
            Err(e) => eprintln!("  [VOUCHER] redeem failed: {e}"),
        }
    }
}

/// Settlement for a job this broker ran on its OWN worker for a requester who
/// is not the owner. Same split as `settle_executor_payout` — `cost*(1-c)` to
/// the executor's owner, `cost*c` to platform-house — minus the network hop:
/// the executor IS this broker, so the owner is credited on this ledger
/// directly (exactly what `handle_peer_earn` does when we are the remote
/// side). Conservation: requester −cost == owner +payout + platform +commission.
/// Without an owner configured there is nobody to pay, so the payout is
/// refunded to the requester rather than vanishing.
fn settle_self_payout(
    state: &Arc<BrokerState>,
    user_id: &str,
    cost: f64,
    commission_c: f64,
    worker: &worker::Worker,
    request_id: &str,
    duration_ms: f64,
) {
    if !state.is_billing_enabled() || cost <= 0.0 {
        return;
    }
    let (payout, commission) = split_commission(cost, commission_c);
    if commission > 0.0 {
        let platform_uid =
            std::env::var("ZAKURO_PLATFORM_UID").unwrap_or_else(|_| "platform-house".into());
        state
            .ledger
            .local_credits
            .entry(platform_uid.clone())
            .and_modify(|b| *b += commission)
            .or_insert(commission);
        state
            .ledger
            .authoritative_balances
            .entry(platform_uid)
            .and_modify(|b| *b += commission)
            .or_insert(commission);
    }
    let Some(owner) = state.config.owner_user_id.clone() else {
        eprintln!(
            "  [EARN] self-executed job {request_id} but no owner configured on this broker; \
             refunding payout {payout:.6} to requester {user_id}"
        );
        state
            .ledger
            .local_credits
            .entry(user_id.to_string())
            .and_modify(|b| *b += payout)
            .or_insert(payout);
        state
            .ledger
            .authoritative_balances
            .entry(user_id.to_string())
            .and_modify(|b| *b += payout)
            .or_insert(payout);
        state.tx_buffer.push_transaction(BufferedTransaction {
            request_id: format!("{request_id}-earn-refund"),
            user_id: user_id.to_string(),
            tx_type: "refund".to_string(),
            amount: payout,
            balance_after: 0.0,
            worker_id: worker.id.clone(),
            duration_ms,
            source_node: state.config.node_name.clone(),
            worker_name: Some(worker.name.clone()),
            worker_uri: None,
            price_per_hour: worker.pricing.price_per_hour,
            voucher_nonce: None,
        });
        return;
    };
    let earn_request_id = format!("earn-{request_id}");
    let _ = state.wal.append(&WalEntry {
        request_id: earn_request_id.clone(),
        user_id: owner.clone(),
        reservation_id: String::new(),
        estimated_cost: payout,
        actual_cost: Some(payout),
        worker_id: worker.id.clone(),
        worker_name: Some(worker.name.clone()),
        duration_ms: Some(duration_ms),
        timestamp: chrono::Utc::now(),
        status: WalStatus::Earned,
        voucher_nonce: None,
    });
    let balance_after = state.ledger.local_add_credits(&owner, payout);
    state.tx_buffer.push_transaction(BufferedTransaction {
        request_id: earn_request_id,
        user_id: owner.clone(),
        tx_type: "credit".to_string(),
        amount: payout,
        balance_after,
        worker_id: worker.id.clone(),
        duration_ms,
        source_node: state.config.node_name.clone(),
        worker_name: Some(worker.name.clone()),
        worker_uri: None,
        price_per_hour: worker.pricing.price_per_hour,
        voucher_nonce: None,
    });
    state.tx_buffer.snapshot_balance(&owner, balance_after);
    println!(
        "  [EARN] Worker {} earned {:.6} credits from user {} → owner {} (self-executed; commission {:.6}; balance now {:.6})",
        worker.name, payout, user_id, owner, commission, balance_after
    );
}

/// Dispatch a task offer to peer brokers via QUIC subscribers then parallel HTTP/QUIC.
/// Returns the first successful response, or a 503 if no peer accepted.
/// Always returns a complete `Response` — the caller should `return` it immediately.
/// Overall deadline for waiting on peer offer responses in `dispatch_to_peers`.
///
/// `PeerClient::offer_task` falls back to a 310s global timeout when the offer
/// carries no `timeout_secs`, and the fan-out loop's `recv` had no deadline of
/// its own — so a single slow or unresponsive peer could hang the request for
/// over five minutes, far past any client timeout. This caps the wait: an
/// explicit task budget is honored (plus slack for transport/queueing), and an
/// unset budget falls back to 30s rather than 310s.
fn peer_dispatch_deadline(timeout_secs: f64) -> std::time::Duration {
    if timeout_secs > 0.0 {
        std::time::Duration::from_secs_f64(timeout_secs + 12.0)
    } else {
        std::time::Duration::from_secs(30)
    }
}

/// Which peers an offer may be sent to.
///
/// `None` means the offer is pinned to a node no peer answers for — the
/// caller must fail the request rather than dispatch it.
///
/// A pin is a restriction, not a preference. The unpinned path is a
/// first-accept-wins race across every peer, so letting a pinned offer into
/// it does not bias the result towards the named node, it simply runs the
/// work wherever the race lands — which is how a `target_node` used to be an
/// anti-pin: it forced the job off the named node and onto anybody.
fn dispatch_targets(
    peer_urls: &[String],
    target_node: Option<&str>,
    resolve_fp: impl Fn(&str) -> Option<String>,
) -> Option<Vec<String>> {
    match target_node {
        None => Some(peer_urls.to_vec()),
        Some(tn) => resolve_fp(tn).map(|url| vec![url]),
    }
}

/// The node an offer is pinned to, if any. Blank and whitespace are "no pin",
/// so an empty field from an older peer never reads as a pin to nowhere.
fn offer_pin(offer: &task_board::TaskOffer) -> Option<&str> {
    let tn = offer.target_node.trim();
    (!tn.is_empty()).then_some(tn)
}

/// Builds the set of peer URLs to broadcast a task offer to in step 2 of
/// `dispatch_to_peers`, excluding `abandoned_preferred_peer` when present.
///
/// `abandoned_preferred_peer` is `Some(url)` only when step 1.5's direct
/// pre-selected offer to that peer timed out or errored — since offers are
/// one-phase (`PeerClient::offer_task` returns only once the peer finishes
/// executing), that peer may still be executing the same `task_id`.
/// Re-offering the same task to it in the broadcast race could cause it to
/// execute the job a second time, so it is excluded from this dispatch's
/// broadcast set. This is narrow, per-dispatch scoping: it does not affect
/// which peers are considered for other requests, and it does not change
/// step 2's broadcast semantics for the remaining peers (parallel offer,
/// first-accept-wins).
fn broadcast_targets(peer_urls: &[String], abandoned_preferred_peer: Option<&str>) -> Vec<String> {
    match abandoned_preferred_peer {
        Some(abandoned) => peer_urls
            .iter()
            .filter(|url| url.as_str() != abandoned)
            .cloned()
            .collect(),
        None => peer_urls.to_vec(),
    }
}

/// Env escape hatch for marketplace policy pre-selection (task 5). Default
/// ON — any value other than exactly `"0"` (including unset) leaves
/// pre-selection active. Set `ZAKURO_MARKETPLACE_SELECT=0` to disable it and
/// fall back to the legacy broadcast-only race for safe rollout.
fn marketplace_select_enabled() -> bool {
    std::env::var("ZAKURO_MARKETPLACE_SELECT")
        .map(|v| v != "0")
        .unwrap_or(true)
}

/// Marketplace policy pre-selection (task 5): pick the single best-admitted
/// peer broker for `req` from cached adverts, ranked by lowest observed
/// latency (resource admission + freshness first) — see
/// `selection::select_executor_broker`. Returns the peer's base URL, or
/// `None` when no peer is admitted (caller falls back to the broadcast
/// race unchanged).
///
/// Latency source: `PeerManager::peer_latency_ms` (the most recent
/// `/peer/health` probe RTT). A peer that hasn't been probed yet has no
/// latency signal — it is still included (so a single freshly-registered
/// peer can be pre-selected) but ranked behind any peer with a measured
/// RTT, via an `f64::MAX` sentinel latency.
fn preselect_executor_peer(state: &Arc<BrokerState>, req: &ResourceRequirements) -> Option<String> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let peers: Vec<(String, Option<super::discovery::Advert>, f64)> = state
        .peer_manager
        .peer_urls()
        .into_iter()
        .map(|url| {
            let advert = state.peer_manager.peer_advert(&url);
            let latency_ms = state.peer_manager.peer_latency_ms(&url).unwrap_or(f64::MAX);
            (url, advert, latency_ms)
        })
        .collect();
    // Staleness window: generous relative to the discovery tick (default
    // 15s, see DiscoveryConfig::interval_secs) so a couple of missed ticks
    // don't spuriously disable pre-selection.
    const MAX_ADVERT_AGE_SECS: u64 = 120;
    super::selection::select_executor_broker(&peers, req, MAX_ADVERT_AGE_SECS, now).map(|b| b.url)
}

#[allow(clippy::too_many_arguments)]
/// Split a gross charge `gross` into `(payout, commission)` for commission rate
/// `c` in `[0.0, 1.0)`. The commission is computed first and the payout is the
/// exact remainder (`gross - commission`) — never an independently rounded
/// piece — so `payout + commission == gross` holds to the last bit. `c == 0.0`
/// yields `(gross, 0.0)`.
fn split_commission(gross: f64, c: f64) -> (f64, f64) {
    let commission = gross * c;
    let payout = gross - commission;
    (payout, commission)
}

/// Pure decision: given the executor's earn outcome, how much (if any) should
/// be refunded to the requester by `settle_executor_payout`?
///
/// The requester was already debited `cost` by the caller before settlement.
/// - `earn_ok == true`: the executor was paid `payout`; nothing to refund.
/// - `earn_ok == false`: the executor's broker could not be reached/paid (it
///   restarted between returning the job result and receiving the earn RPC,
///   or the peer was already unresolvable) — refund `payout` to the
///   requester so they net only `-commission`, matching the platform's cut.
///   Conservation holds either way: requester_net + executor_delta +
///   platform_delta == 0, where platform_delta == commission in both cases.
fn earn_refund_amount(payout: f64, earn_ok: bool) -> f64 {
    if earn_ok {
        0.0
    } else {
        payout
    }
}

/// Extract the stamped `commission_c` from an offer's dashboard-signed voucher.
///
/// This runs on the REQUESTER's settlement broker — a party with an obvious
/// incentive to strip or zero `commission_c` before it ever reaches this
/// point, since that broker's own operator controls the code path. We must
/// not trust the JSON contents until the dashboard's Ed25519 signature over
/// the *exact bytes* has been verified against `dash_pubkey` (mirroring
/// `verify_offer_voucher`'s signature-first discipline). `price_estimate` is
/// passed as `0.0` because this call only extracts `commission_c` — it does
/// not re-check budget (already enforced by the executor broker's earlier
/// `verify_offer_voucher` call) — so a generous/zero estimate never spuriously
/// rejects a valid voucher on budget grounds here.
///
/// Returns `0.0` (no local platform-mirror commission) whenever: there is no
/// voucher, no cached dashboard pubkey, or signature/verification fails. This
/// is safe and non-regressive — the dashboard remains the authoritative
/// commission enforcer via its own voucher-nonce lookup at settlement, so a
/// `0.0` here only skips the broker-local platform-house cache mirror, never
/// dashboard-side enforcement. A parse or verification failure must never
/// throw money, so we always fall back to no commission rather than guess.
fn offer_commission_c(offer: &task_board::TaskOffer, dash_pubkey: Option<&str>) -> f64 {
    if offer.voucher_signed_json.is_empty() || offer.voucher_sig.is_empty() {
        return 0.0;
    }
    let Some(pubkey) = dash_pubkey else {
        return 0.0;
    };
    match super::voucher::verify_voucher_now(
        &[pubkey],
        &offer.voucher_signed_json,
        &offer.voucher_sig,
        0.0,
    ) {
        Ok(v) if (0.0..1.0).contains(&v.commission_c) => v.commission_c,
        _ => 0.0,
    }
}

#[allow(clippy::too_many_arguments)]
fn dispatch_to_peers(
    state: &Arc<BrokerState>,
    offer: task_board::TaskOffer,
    start: Instant,
    user_id: &str,
    _is_self_owned: bool,
    request_id: &str,
    tx_num: u64,
    verbose: bool,
    balance_before: f64,
    preferred_peer: Option<String>,
    // The ONE dashboard-verified commission rate for this job, captured at mint
    // time in `execute_prepare` (0.0 when vouchers are not required). Used
    // directly for the executor payout — settlement never re-derives it
    // (re-derivation returned 0.0 on a rotated/missing pubkey and minted
    // credits, since the executor-side redeem still charged commission).
    verified_commission_c: f64,
) -> BrokerResponse {
    let peer_urls: Vec<String> = state.peer_manager.peer_urls();

    // ── Node pin ─────────────────────────────────────────────────────
    // A pinned offer goes to exactly one peer or nowhere. Resolved before the
    // credit gate so an unroutable pin fails as a routing error rather than
    // after reserving anything.
    let pin = offer_pin(&offer);
    let dispatch_set = match dispatch_targets(&peer_urls, pin, |fp| {
        state.peer_manager.get_url_for_fingerprint(fp)
    }) {
        Some(urls) => urls,
        None => {
            log_transaction(
                state,
                verbose,
                tx_num,
                user_id,
                "EXECUTE",
                0.0,
                balance_before,
                None,
                0.0,
                "FAIL",
            );
            return error_response(
                &format!(
                    "No peer on this mesh answers for pinned node {}",
                    pin.unwrap_or_default()
                ),
                "NODE_UNREACHABLE",
                503,
            );
        }
    };

    // ── Pre-dispatch credit gate (audit C2) ──────────────────────────
    // Mirror the local select_worker credit check: reject the request with
    // 402 INSUFFICIENT_CREDITS *before* offering the task to any peer when the
    // requester cannot cover the maximum cost the offer permits. Without this,
    // remote jobs were dispatched with no balance check and overspend was
    // silently clamped to zero after the fact.
    if state.is_billing_enabled() {
        // Maximum the requester can be charged: the offer's price ceiling
        // (max_price_per_hour) over its estimated duration. When no budget was
        // supplied, max_price_per_hour is f64::MAX — the cost cannot be bounded
        // ahead of the offer (the executing peer's real price is unknown until it
        // accepts), so we require only a strictly positive balance and settle the
        // actual cost after execution. (Previously this reserved f64::MAX, making
        // any un-budgeted remote dispatch impossible — a money-path bug.)
        // The no-budget sentinel is f64::MAX (a FINITE value — is_finite() is true
        // for it), so detect "unbounded" as >= f64::MAX (also catches infinity).
        let unbounded = offer.max_price_per_hour >= f64::MAX;
        let max_cost = if unbounded {
            0.0
        } else {
            offer.max_price_per_hour / 3600.0 * offer.estimated_duration_secs
        };
        let insufficient = if unbounded {
            balance_before <= 0.0
        } else {
            balance_before < max_cost
        };
        if insufficient {
            log_transaction(
                state,
                verbose,
                tx_num,
                user_id,
                "EXECUTE",
                0.0,
                balance_before,
                None,
                0.0,
                "FAIL",
            );
            let detail = if unbounded {
                format!(
                    "Insufficient credits: a positive balance is required, have {:.4}",
                    balance_before
                )
            } else {
                format!(
                    "Insufficient credits: need {:.4}, have {:.4}",
                    max_cost, balance_before
                )
            };
            return error_response(&detail, "INSUFFICIENT_CREDITS", 402);
        }
    }

    let quic_transport = state.quic.get().cloned();
    // ONE budget for the whole dispatch, not one per phase. The preferred-peer
    // offer and the broadcast race run strictly in sequence, so a deadline
    // taken fresh by each let a dispatch run for twice `peer_dispatch_deadline`
    // — up to 60s against a client that had already given up at 15s, still
    // holding a worker and still billable.
    let dispatch_expires_at = Instant::now() + peer_dispatch_deadline(offer.timeout_secs);
    let time_left = || dispatch_expires_at.saturating_duration_since(Instant::now());
    let mut winning_peer: Option<String> = None;
    let mut winning_result: Option<task_board::TaskResult> = None;
    let mut winning_transport: Option<String> = None;

    // 1) Push to already-connected QUIC subscribers first (zero extra latency).
    //    Skipped for a pinned offer: this pushes to EVERY subscriber and takes
    //    whichever answers first, which is the one thing a pin forbids.
    if let (None, Some(ref qt)) = (pin, &quic_transport) {
        if let Some((url, res)) = qt.broadcast_offer_to_subscribers(&offer) {
            winning_peer = Some(url);
            winning_result = Some(res);
            winning_transport = Some("subscribed".to_string());
        }
    }

    // 1.5) Marketplace policy pre-selection (task 5): try the single
    // best-admitted peer directly, via the SAME per-peer offer mechanism
    // (`PeerClient::offer_task`, normal accept/timeout semantics) used by
    // the broadcast race below. On accept, this IS the winner — the
    // broadcast race (step 2) never runs. On decline/timeout/unreachable,
    // fall through unchanged to step 2, which may re-offer to the same
    // peer — that's fine (matches the legacy path's own retry-by-broadcast
    // behavior).
    // Bounded to the SAME deadline the broadcast race (step 2) uses via
    // `peer_dispatch_deadline` — `PeerClient::offer_task`'s own internal
    // timeout defaults to ~310s (offer.timeout_secs + 10, or 310 when
    // unset), which would otherwise let a reachable-but-hung pre-selected
    // peer stall the whole request far longer than the broadcast race's
    // ~12s-slack/30s-fallback bound. The offer itself runs on a worker
    // thread (mirroring step 2's pattern, including looking up the client
    // fresh inside the thread to avoid holding the dashmap `Ref` across
    // threads) and we only ever *wait* up to the deadline here — we never
    // race it against the broadcast loop. On timeout/decline/error we
    // fall straight through to step 2 below, strictly sequentially, so at
    // most one of {pre-selected peer, broadcast winner} can ever produce
    // a `winning_result`; a still-running abandoned offer thread cannot
    // cause a double-charge because the local dispatch logic only acts on
    // whichever single `TaskResult` this function returns.
    // Tracks the preferred peer's URL when step 1.5 times out or errors
    // (i.e. the offer thread may still be running the job on that peer,
    // since offers are one-phase and only return on completion). Set only
    // on the timeout/err path, never on the success path — used to exclude
    // that peer from step 2's broadcast below.
    let mut abandoned_preferred_peer: Option<String> = None;
    // A pin has already chosen the peer; the policy pre-selection would be
    // choosing a second time, from the whole mesh.
    if winning_peer.is_none() && pin.is_none() {
        if let Some(ref peer_url) = preferred_peer {
            if state.peer_manager.get_client(peer_url).is_some() {
                let (tx, rx) = std::sync::mpsc::channel::<Result<task_board::TaskResult, String>>();
                let state_c = state.clone();
                let offer_c = offer.clone();
                let peer_url_c = peer_url.clone();
                std::thread::spawn(move || {
                    let result = match state_c.peer_manager.get_client(&peer_url_c) {
                        Some(client) => client.offer_task(&offer_c),
                        None => Err("peer unreachable".to_string()),
                    };
                    let _ = tx.send(result);
                });
                if let Ok(Ok(result)) = rx.recv_timeout(time_left()) {
                    winning_peer = Some(peer_url.clone());
                    winning_result = Some(result);
                    winning_transport = Some("http".to_string());
                } else {
                    // Timed out (RecvTimeoutError) or the peer
                    // declined/errored (Ok(Err(_))). Because offers are
                    // one-phase (`PeerClient::offer_task` only returns
                    // once the peer FINISHES executing), a timeout here
                    // means the preferred peer may still be executing
                    // this same task_id. Record it so step 2 excludes it
                    // from the broadcast — otherwise the same task_id
                    // would be re-offered to a peer that could still be
                    // running it, duplicating execution (worst case: the
                    // same peer runs the same job twice). Cross-peer
                    // redundant execution across *different* peers in the
                    // step-2 broadcast race (offer-to-all, first-accept-
                    // wins) is pre-existing, intentionally out of scope
                    // here — exactly-once execution is deferred to the
                    // proof-of-execution/settlement work (spec #3).
                    abandoned_preferred_peer = Some(peer_url.clone());
                }
            }
        }
    }

    // Peers to broadcast to in step 2: all known peers minus the abandoned
    // preferred peer (if any).
    // `dispatch_set` is every peer when unpinned, and the single pinned peer
    // otherwise — so a pinned offer reaches that peer and no other.
    let broadcast_peer_urls = broadcast_targets(&dispatch_set, abandoned_preferred_peer.as_deref());

    // 2) If no subscriber took it, offer to all peers in parallel; first to accept wins.
    if winning_peer.is_none() && !broadcast_peer_urls.is_empty() {
        let (tx, rx) =
            std::sync::mpsc::channel::<Option<(String, task_board::TaskResult, String)>>();
        for peer_url in &broadcast_peer_urls {
            let tx = tx.clone();
            let state_c = state.clone();
            let offer_c = offer.clone();
            let quic_c = quic_transport.clone();
            let peer_url = peer_url.clone();
            std::thread::spawn(move || {
                let (offer_result, transport_used) =
                    offer_to_peer(&state_c, quic_c.as_ref(), &peer_url, &offer_c);
                let _ = tx.send(offer_result.ok().map(|r| (peer_url, r, transport_used)));
            });
        }
        drop(tx);
        // Bounded wait: the first peer to accept wins. A declining/unreachable
        // peer sends `None` and we keep waiting for the others, but the total
        // wait is capped (peer_dispatch_deadline) so one slow/unresponsive peer
        // can't hang the request for up to offer_task's 310s fallback. On
        // timeout we stop waiting and fall through to the 503 below; any
        // still-running offer threads send into the dropped receiver harmlessly.
        for _ in 0..broadcast_peer_urls.len() {
            match rx.recv_timeout(time_left()) {
                Ok(Some((url, res, trans))) => {
                    winning_peer = Some(url);
                    winning_result = Some(res);
                    winning_transport = Some(trans);
                    break;
                }
                Ok(None) => continue, // peer declined/unreachable; wait for others
                Err(_) => break,      // deadline reached or all senders gone
            }
        }
    }

    if let (Some(peer_url), Some(result), Some(transport_used)) =
        (winning_peer, winning_result, winning_transport)
    {
        let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
        // Dispatch to peers = always alien compute; owner is not exempt from billing here.
        let cost = result.actual_cost;
        let balance_after = balance_before - cost;

        // Teach the router what this peer actually cost. `duration_ms` here is
        // the whole round trip the caller waited for -- offer, execution and
        // return -- which is exactly the quantity routing ranks on. Keyed by
        // the reported worker name because a peer's own worker id is not ours;
        // a name we don't know is simply not recorded.
        state
            .workers
            .observe_latency_by_name(&result.worker_name, duration_ms, true);

        log_transaction_with_worker_info(
            state,
            verbose,
            tx_num,
            user_id,
            "EXECUTE",
            cost,
            balance_after,
            Some(&result.worker_name),
            duration_ms,
            "OK",
            Some(result.price_per_hour),
            Some(&result.executor_owner),
            result.worker_pid.as_deref(),
            // A peer's address is never disclosed over the mesh, so a
            // dispatched (alien-compute) transaction has no worker IP to log.
            // Locally-executed transactions still record theirs (see the
            // `x-zakuro-ip` path in the local execute arm).
            None,
            Some(request_id),
        );

        if state.is_billing_enabled() && cost > 0.0 {
            state.credits.set_balance(user_id, balance_after);
            // Surface overspend instead of silently clamping to zero: if the peer
            // charged more than the requester could cover, the post-balance is
            // negative. Record the true value and warn so the overspend is visible
            // (reconciliation / dashboard flush) rather than hidden (audit C2).
            if balance_after < 0.0 {
                eprintln!(
                    "  [BILLING] OVERSPEND user={} cost={:.4} balance_before={:.4} balance_after={:.4} request_id={}",
                    user_id, cost, balance_before, balance_after, request_id
                );
            }
            // Update ledger caches so /me reflects the deduction immediately.
            state
                .ledger
                .local_credits
                .entry(user_id.to_string())
                .and_modify(|b| *b -= cost);
            state
                .ledger
                .authoritative_balances
                .entry(user_id.to_string())
                .and_modify(|b| *b -= cost);
            state.tx_buffer.push_transaction(BufferedTransaction {
                request_id: request_id.to_string(),
                user_id: user_id.to_string(),
                tx_type: "commit".to_string(),
                amount: cost,
                balance_after,
                worker_id: result.worker_name.clone(),
                duration_ms,
                source_node: state.config.node_name.clone(),
                worker_name: Some(result.worker_name.clone()),
                worker_uri: Some(result.worker_uri.clone()),
                price_per_hour: result.price_per_hour,
                voucher_nonce: offer_voucher_nonce(&offer),
            });
        }

        if cost > 0.0 {
            // Commission is the ONE rate `verified_commission_c` that
            // `execute_prepare` already verified at mint time (dashboard
            // signature + `voucher_commission_valid`) before this offer was ever
            // dispatched — 0.0 only when vouchers are not required (legacy free/
            // uncommissioned payout). We do NOT re-derive it here via
            // `offer_commission_c`: that returned 0.0 whenever this broker's
            // cached pubkey was missing/rotated, paying the executor the FULL
            // cost while the executor-side `redeem_offer_voucher` still charged
            // the voucher's own commission at the dashboard → net minting of
            // `commission` credits. Threading the mint-verified c means the
            // earn(payout) leg and the dashboard redeem always agree.
            //
            // Gross basis is `cost` (= result.actual_cost) — the SAME amount the
            // requester was debited above — so the legs net to zero: requester
            // −cost, executor +payout, platform +commission, payout+commission==cost.
            // `settle_executor_payout` gates the platform-house credit on
            // `state.is_billing_enabled()`, matching the requester debit's gate
            // above so both legs stay symmetric; commission is credited to
            // platform-house authoritatively by the dashboard at
            // `/voucher/redeem` (executor-side, see `redeem_offer_voucher`) — the
            // local credit here is a cache mirror only, no separate batch-sync
            // delta is emitted for it.
            settle_executor_payout(
                state,
                user_id,
                cost,
                verified_commission_c,
                &peer_url,
                WorkerName::reported(&result.worker_name),
                request_id,
                duration_ms,
            );
        }

        let response_body = base64::Engine::decode(
            &base64::engine::general_purpose::STANDARD,
            &result.payload_b64,
        )
        .unwrap_or_default();

        // This broker never ran a `RoutingDecision` for this job — there was
        // no local worker (or `remote_only` demanded a peer), so the ONLY
        // decision made here was to dispatch remotely rather than run
        // nothing. That's still a decision worth surfacing (#267): billing
        // makes "why did this run on a paid peer" a real question, and
        // without this a peer-routed job looks identical to a local one.
        let reason = format!(
            "Peer dispatch: no local worker; sent to {} via {}",
            result.worker_name, transport_used
        );
        let headers = [
            header_or("Content-Type", "application/octet-stream"),
            header_or("X-Zakuro-Request-Id", request_id),
            header_or("X-Zakuro-Worker", result.worker_name.as_str()),
            header_or("X-Zakuro-Cost", &format!("{:.6}", cost)),
            header_or(
                "X-Zakuro-Credits-Remaining",
                &format!("{:.6}", balance_after),
            ),
            header_or("X-Zakuro-Duration-Ms", &format!("{:.2}", duration_ms)),
            header_or("X-Zakuro-Transport", transport_used.as_str()),
            header_or("X-Zakuro-Reason", &sanitize_reason_header(&reason)),
        ];
        let mut resp = BrokerResponse {
            status: 200,
            headers: Vec::new(),
            body: response_body,
        };
        resp.headers.extend(headers);
        return resp;
    }

    log_transaction(
        state,
        verbose,
        tx_num,
        user_id,
        "EXECUTE",
        0.0,
        balance_before,
        None,
        0.0,
        "FAIL",
    );
    error_response("No worker available (local or peer)", "NO_WORKERS", 503)
}

/// Where the time went inside one `/execute`.
///
/// `X-Zakuro-Duration-Ms` is a single number covering everything up to
/// settlement, so a broker spending two seconds somewhere can report only that
/// it did. On 2026-09-19 a node was answering `add(2, 3)` in 3.05 s of which
/// 0.78 s was the caller's network and ~1 ms was the worker — measured from
/// outside, because nothing inside said which boundary the rest sat behind.
/// Recording the crossings is the difference between "the broker is slow" and
/// a fix.
///
/// Marks are cheap enough to take unconditionally (one `Instant::now()` each,
/// tens of nanoseconds); only the reporting is opt-in, so a trace never has to
/// be arranged in advance to be available.
#[derive(Debug, Clone)]
pub(crate) struct Phases {
    start: Instant,
    /// `(label, cumulative micros since start)`, in the order crossed.
    marks: Vec<(&'static str, u64)>,
}

impl Phases {
    pub(crate) fn new(start: Instant) -> Self {
        Phases {
            start,
            marks: Vec::with_capacity(8),
        }
    }

    /// Record that `label` has just finished.
    pub(crate) fn mark(&mut self, label: &'static str) {
        let us = self.start.elapsed().as_micros() as u64;
        self.marks.push((label, us));
    }

    /// Each phase's OWN cost in milliseconds, as `auth=0.05 route=1.20 …`.
    ///
    /// Deltas rather than cumulative totals: the question is always which
    /// phase owns the time, and a reader should not have to subtract.
    pub(crate) fn header(&self) -> String {
        let mut prev = 0u64;
        let mut out = String::new();
        for (label, at) in &self.marks {
            if !out.is_empty() {
                out.push(' ');
            }
            let own = at.saturating_sub(prev);
            out.push_str(&format!("{}={:.2}", label, own as f64 / 1000.0));
            prev = *at;
        }
        out
    }
}

#[cfg(test)]
mod voucher_need_tests {
    use super::{voucher_need, VoucherNeed};

    /// Free work never needs a voucher: there is no commission on nothing.
    #[test]
    fn free_work_needs_no_voucher() {
        assert_eq!(
            voucher_need(true, true, true, true),
            VoucherNeed::None,
            "free, even with vouchers required"
        );
    }

    #[test]
    fn a_fleet_that_does_not_use_vouchers_mints_none() {
        assert_eq!(voucher_need(false, false, true, true), VoucherNeed::None);
    }

    /// Billed work on our own hardware: mint, and redeem at settlement. This
    /// is the case the batch endpoint was silently skipping.
    #[test]
    fn billed_work_on_our_own_hardware_is_minted() {
        assert_eq!(
            voucher_need(false, true, true, false),
            VoucherNeed::Mint,
            "self-executed settles here whatever the authority says"
        );
    }

    #[test]
    fn billed_work_we_settle_for_is_minted() {
        assert_eq!(voucher_need(false, true, false, true), VoucherNeed::Mint);
    }

    /// Neither ours to run nor ours to settle. Minting would burn a dashboard
    /// nonce nobody redeems; running anyway would be uncommissioned. Refuse.
    #[test]
    fn billed_work_that_is_neither_ours_to_run_nor_to_settle_is_refused() {
        assert_eq!(voucher_need(false, true, false, false), VoucherNeed::Refuse);
    }
}

#[cfg(test)]
mod bearer_tests {
    use super::bearer_token;

    #[test]
    fn a_real_token_is_taken() {
        assert_eq!(
            bearer_token(Some("Bearer zk_alice_abc123")).as_deref(),
            Some("zk_alice_abc123")
        );
    }

    #[test]
    fn surrounding_whitespace_is_not_part_of_the_token() {
        assert_eq!(
            bearer_token(Some("Bearer   zk_alice_abc123  ")).as_deref(),
            Some("zk_alice_abc123")
        );
    }

    /// The case the comment in `execute_prepare` was written for: a client
    /// interpolating an unset variable sends the scheme and nothing else. That
    /// is "no credential", not "an invalid credential" — failing it would turn
    /// a keyless local request into a 401.
    #[test]
    fn a_bearer_with_nothing_after_it_is_no_token_at_all() {
        assert_eq!(bearer_token(Some("Bearer ")), None);
        assert_eq!(bearer_token(Some("Bearer    ")), None);
    }

    #[test]
    fn an_absent_or_foreign_scheme_is_no_token() {
        assert_eq!(bearer_token(None), None);
        assert_eq!(bearer_token(Some("")), None);
        assert_eq!(bearer_token(Some("Basic abc")), None);
        // Case matters: the scheme is matched exactly, as it was before.
        assert_eq!(bearer_token(Some("bearer abc")), None);
    }
}

#[cfg(test)]
mod authority_balance_tests {
    use super::{balance_plan, BalancePlan};

    /// The first request for a user is the only one that waits on the mesh.
    #[test]
    fn nothing_known_means_ask() {
        assert_eq!(balance_plan(None), BalancePlan::Ask);
    }

    #[test]
    fn a_fresh_figure_is_served_and_nothing_is_asked() {
        assert_eq!(balance_plan(Some((42.0, false))), BalancePlan::Serve(42.0));
    }

    /// The change that takes the round trip off the hot path: a stale figure
    /// still answers the request, and the refresh happens behind it. Blocking
    /// here is what made every `/execute` pay a mesh round trip before it had
    /// even chosen a worker — ~2s against a worker that answered in 1ms.
    #[test]
    fn a_stale_figure_is_served_and_refreshed_behind_the_request() {
        assert_eq!(
            balance_plan(Some((42.0, true))),
            BalancePlan::ServeAndRefresh(42.0)
        );
    }

    /// A zero balance is a real answer, not a missing one. Treating it as
    /// "nothing known" would make every request for a broke user pay the
    /// round trip again — exactly the users most likely to be retrying.
    #[test]
    fn a_cached_zero_is_an_answer_not_an_absence() {
        assert_eq!(balance_plan(Some((0.0, false))), BalancePlan::Serve(0.0));
    }
}

#[cfg(test)]
mod phase_trace_tests {
    use super::Phases;
    use std::time::Instant;

    fn with_marks(marks: &[(&'static str, u64)]) -> Phases {
        Phases {
            start: Instant::now(),
            marks: marks.to_vec(),
        }
    }

    /// Marks are cumulative; the report is not. A reader asking "which phase
    /// owns the two seconds" must not have to subtract to find out.
    #[test]
    fn the_report_gives_each_phase_its_own_cost() {
        let p = with_marks(&[
            ("auth", 50),
            ("balance", 1_250),
            ("route", 1_550),
            ("forward", 2_039_380),
        ]);
        assert_eq!(
            p.header(),
            "auth=0.05 balance=1.20 route=0.30 forward=2037.83"
        );
    }

    #[test]
    fn a_walk_with_no_marks_reports_nothing_rather_than_panicking() {
        assert_eq!(with_marks(&[]).header(), "");
    }

    /// A clock that appears to go backwards between two marks (coarse timer,
    /// or a mark recorded out of order) must not underflow into a colossal
    /// duration — the report is diagnostic, and a nonsense number in it sends
    /// the reader after the wrong phase.
    #[test]
    fn a_non_monotonic_pair_reports_zero_not_an_underflow() {
        let p = with_marks(&[("auth", 500), ("balance", 100)]);
        assert_eq!(p.header(), "auth=0.50 balance=0.00");
    }
}

/// Values produced by the prepare phase and consumed by the forward+finish phase.
/// Carries every field that `handle_execute`'s forward+finish half needs so that
/// `execute_prepare` can return them in one bundle.
struct PreparedForward {
    worker_uri: String,
    body: Vec<u8>,
    request_id: String,
    tx_num: u64,
    effective_timeout: f64,
    user_id: String,
    authority: Authority,
    reservation_id: String,
    balance_before: f64,
    /// Full worker snapshot — needed by `commit_credits` and the retry/timeout
    /// billing paths which access worker.id, worker.uri, worker.name, and
    /// worker.pricing. Carrying the struct rather than individual fields avoids
    /// partial duplication and lets us pass `&p.worker` directly to helpers.
    worker: Worker,
    /// Whether this execution is free (local worker or self-owned).
    is_local: bool,
    /// Credits reserved for the request (used to cap timeout charges).
    reservation_amount: f64,
    /// Instance-affinity action header ("create_instance" / "call_method" / None).
    instance_action: Option<String>,
    /// Instance ID from the affinity header.
    instance_id: Option<String>,
    /// Monotonic clock captured at the start of the request.
    start: Instant,
    /// Platform commission rate stamped in the dashboard voucher minted for
    /// this remote job (0.0 for local jobs / no voucher required). Consumed by
    /// `commit_credits` → `settle_executor_payout`.
    commission_c: f64,
    /// The minted voucher's `task_nonce`, redeemed at settlement in
    /// `commit_credits` (empty when no voucher was minted for this job).
    voucher_task_nonce: String,
    /// The winning `RoutingDecision`'s reason (#267) — why THIS worker, over
    /// every alternative the router considered. Threaded through so
    /// `handle_execute` can put it on the wire as `X-Zakuro-Reason`; sent
    /// through `sanitize_reason_header` first, never raw.
    reason: String,
    /// Where the time has gone so far. See [`Phases`].
    phases: Phases,
    /// Whether the caller asked for the breakdown (`X-Zakuro-Trace: 1`).
    trace: bool,
}

/// Fail-closed voucher mint for the direct-forward remote path (a remote
/// worker selected outside `dispatch_to_peers` — non-P2P billing routing, or
/// instance-affinity pinning to a remote worker). Mirrors the offer path's
/// mint-or-reject, but also verifies the returned voucher's signature and
/// extracts `commission_c` + `task_nonce` here since there is no separate
/// executor-side `verify_offer_voucher` step for this path: settlement
/// happens entirely on the requester's own broker in `commit_credits`.
/// Returns `Err(response)` — the caller must reject the job with it rather
/// than falling back to an uncommissioned / unvouchered dispatch.
fn mint_and_verify_remote_voucher(
    state: &Arc<BrokerState>,
    budget: f64,
    mint_key: Option<&str>,
) -> Result<(f64, String), BrokerResponse> {
    let (_json, _sig, v) = mint_and_verify_voucher(state, budget, mint_key)?;
    Ok((v.commission_c, v.task_nonce))
}

/// Shared fail-closed mint+verify used by BOTH remote paths. Obtains a
/// dashboard-signed voucher for `budget`, REQUIRES a cached dashboard pubkey,
/// verifies the Ed25519 signature over the exact bytes, and enforces
/// `voucher_commission_valid` on the stamped `commission_c`. Any failure — no
/// api creds, mint error, no cached pubkey, bad signature, invalid/zero
/// commission — returns `Err(response)` so the caller can REJECT the job at
/// mint time (pre-dispatch), never running it uncommissioned. Returns the
/// verbatim `(signed_json, sig)` (to attach to a peer offer) plus the parsed
/// `Voucher` so a single verified `commission_c` drives BOTH the executor
/// payout and the dashboard redeem — they can never disagree.
///
/// `mint_key`: the credential the voucher is minted under. The dashboard
/// records the voucher's requester and resolves the commission tier from this
/// key, so for a job a *foreign* user submits with `Authorization: Bearer`, it
/// is THEIR key; `None` falls back to this broker's own key (the owner's jobs,
/// and paths that have no requester credential in hand).
fn mint_and_verify_voucher(
    state: &Arc<BrokerState>,
    budget: f64,
    mint_key: Option<&str>,
) -> Result<(String, String, super::voucher::Voucher), BrokerResponse> {
    let (api_url, own_key) = match (&state.config.api_url, &state.config.api_key) {
        (Some(u), Some(k)) => (u, k),
        _ => {
            return Err(error_response(
                "Voucher required for remote dispatch but broker is not configured for \
                 dashboard vouchers (missing api_url/api_key)",
                "VOUCHER_UNAVAILABLE",
                503,
            ));
        }
    };
    let api_key = mint_key.filter(|k| !k.trim().is_empty()).unwrap_or(own_key);
    let (signed_json, sig) =
        super::node_sync::obtain_voucher(api_url, api_key, budget.max(0.000_001)).map_err(|e| {
            eprintln!("  [VOUCHER] issue failed: {e}");
            error_response(
                &format!("Voucher required for remote dispatch but mint failed: {e}"),
                "VOUCHER_MINT_FAILED",
                503,
            )
        })?;
    let dash_pubkeys = cached_voucher_pubkeys(state);
    if dash_pubkeys.is_empty() {
        return Err(error_response(
            "Voucher required for remote dispatch but no dashboard voucher pubkey cached yet",
            "VOUCHER_UNAVAILABLE",
            503,
        ));
    }
    let v = super::voucher::verify_voucher_now(&dash_pubkeys, &signed_json, &sig, 0.0).map_err(
        |e| {
            eprintln!("  [VOUCHER] minted voucher failed verification: {e}");
            error_response(
                &format!("Voucher verification failed: {e}"),
                "VOUCHER_VERIFY_FAILED",
                503,
            )
        },
    )?;
    if !voucher_commission_valid(v.commission_c) {
        eprintln!(
            "  [VOUCHER] minted voucher has invalid/zero commission_c={}, rejecting (fail-closed)",
            v.commission_c
        );
        return Err(error_response(
            "Voucher minted but commission_c invalid; refusing to dispatch uncommissioned",
            "VOUCHER_COMMISSION_INVALID",
            503,
        ));
    }
    Ok((signed_json, sig, v))
}

/// Pure fail-closed gate: a voucher's `commission_c` is only usable to settle
/// a `voucher_required` remote job when it is a real, in-range, positive rate.
/// `0.0` (no commission — e.g. a legacy/tampered/unverifiable voucher) and any
/// out-of-`[0.0, 1.0)` or non-finite value (NaN from a malformed payload) must
/// reject rather than silently settle uncommissioned. Factored out as a pure
/// function so the fail-closed decision is directly unit-testable without
/// standing up the mint/verify network round-trip.
fn voucher_commission_valid(c: f64) -> bool {
    c.is_finite() && c > 0.0 && c < 1.0
}

/// The requester's balance according to their authority peer, without paying
/// for the answer twice.
///
/// Asking the authority is a synchronous HTTP round trip across the mesh, and
/// this ran on EVERY `/execute`, before routing, for a number that changes
/// slowly. Measured 2026-09-19 against the 10-broker mesh: `add(2, 3)` took
/// 3.05s end to end, of which 0.78s was the caller's network and ~1ms was the
/// worker — the rest was the broker asking another machine what it had
/// already been told, on a request that then ran for free on its own hardware.
///
/// Three cases, and only the first costs anything:
///
/// - nothing cached — ask, and wait. The first request for a user, once.
/// - cached and stale — serve it and refresh behind the request. A balance a
///   second old is what the previous request already routed on; blocking to
///   confirm it buys nothing a caller can use.
/// - cached and fresh — serve it.
///
/// Serving a stale figure cannot overspend: reservations deduct from the same
/// cached number, so spending inside the window is accounted for locally and
/// settles against the authority afterwards. That is the reasoning the
/// `Authority::Local` path has always run on (see `Ledger::balance_window`);
/// this is the branch it was never extended to.
fn peer_balance(state: &Arc<BrokerState>, peer_url: &str, user_id: &str) -> f64 {
    let ttl = super::ledger::Ledger::balance_window();
    match balance_plan(state.peer_manager.cached_balance(user_id, ttl)) {
        BalancePlan::Serve(value) => value,
        BalancePlan::ServeAndRefresh(value) => {
            spawn_balance_refresh(state, peer_url, user_id);
            value
        }
        BalancePlan::Ask => match state.peer_manager.get_client(peer_url) {
            Some(client) => match client.get_balance(user_id) {
                Ok(v) => {
                    state.peer_manager.store_balance(user_id, v);
                    v
                }
                // Never cache a failed fetch: 0.0 is indistinguishable from a
                // real zero balance to every later reader, and would lock the
                // user out for the life of the entry.
                Err(_) => state.ledger.get_balance(user_id),
            },
            None => state.ledger.get_balance(user_id),
        },
    }
}

/// What a request should do about the authority balance it has, or has not,
/// been told.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum BalancePlan {
    /// Cached and inside the window: answer from it.
    Serve(f64),
    /// Cached but past the window: answer from it anyway, and go and find out
    /// behind the request. Blocking a caller to confirm a figure the previous
    /// caller already routed on buys nothing that caller can use.
    ServeAndRefresh(f64),
    /// Nothing known. The only case that waits for the mesh, and it happens
    /// once per user rather than once per request.
    Ask,
}

/// The decision, as a pure function of what the cache holds.
pub(crate) fn balance_plan(cached: Option<(f64, bool)>) -> BalancePlan {
    match cached {
        None => BalancePlan::Ask,
        Some((value, false)) => BalancePlan::Serve(value),
        Some((value, true)) => BalancePlan::ServeAndRefresh(value),
    }
}

/// Refresh one user's cached balance off the request path, at most one
/// refresh per user at a time.
///
/// The single-flight claim is the point: without it, a burst of ten requests
/// arriving the moment an entry expires is ten simultaneous queries to the
/// same broker, which is how per-request latency climbed with concurrency
/// rather than staying flat.
fn spawn_balance_refresh(state: &Arc<BrokerState>, peer_url: &str, user_id: &str) {
    if !state.peer_manager.claim_balance_refresh(user_id) {
        return;
    }
    let state = state.clone();
    let peer_url = peer_url.to_string();
    let user_id = user_id.to_string();
    std::thread::spawn(move || {
        if let Some(client) = state.peer_manager.get_client(&peer_url) {
            if let Ok(v) = client.get_balance(&user_id) {
                state.peer_manager.store_balance(&user_id, v);
            }
        }
        state.peer_manager.release_balance_refresh(&user_id);
    });
}

/// Who is asking, as `execute` needs it: [`authenticated_user`]'s rule, with
/// the keyless local-mode path resolved to a concrete identity so the billing
/// step downstream has someone to name.
///
/// A batch establishes this ONCE and then places many tasks against it, which
/// is why it is a function rather than the first forty lines of
/// `execute_prepare`.
fn identify(state: &Arc<BrokerState>, request: &BrokerRequest) -> Result<String, BrokerResponse> {
    Ok(match authenticated_user(state, request)? {
        Some(uid) => uid,
        // Local mode only, and only because `authenticated_user` already
        // refused the keyless path everywhere else.
        None => request
            .header("X-Zakuro-User")
            .unwrap_or_else(|| ANONYMOUS_USER.to_string()),
    })
}

/// Whether a job must carry a dashboard-signed voucher, and whether this
/// broker is allowed to mint one for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VoucherNeed {
    /// Free work, or vouchers not in use here: run without one.
    None,
    /// Mint before the work runs, and redeem at settlement.
    Mint,
    /// Required, but this broker is not the settlement authority. Refuse:
    /// minting here would consume a dashboard nonce nobody ever redeems, and
    /// running anyway would be running uncommissioned.
    Refuse,
}

/// The rule, as a pure function of the four things that decide it.
///
/// Extracted because `/execute` and `/execute/batch` must apply the SAME rule
/// — the batch endpoint shipped without it (#322) and would have run batches
/// uncommissioned on any fleet with `ZAKURO_REQUIRE_VOUCHER` set, which is
/// every fleet that has ever measured a `voucher` phase.
pub(crate) fn voucher_need(
    is_free: bool,
    required: bool,
    self_executed: bool,
    redeems_here: bool,
) -> VoucherNeed {
    if is_free || !required {
        return VoucherNeed::None;
    }
    match self_executed || redeems_here {
        true => VoucherNeed::Mint,
        false => VoucherNeed::Refuse,
    }
}

/// The bearer token a request carries, if it carries a usable one.
///
/// An empty or whitespace-only token is NOT a token. A client that builds
/// `Authorization: Bearer ` out of an unset environment variable must fall
/// through to the keyless path rather than fail validation — the header is
/// present but says nothing.
pub(crate) fn bearer_token(header: Option<&str>) -> Option<String> {
    header
        .and_then(|a| a.strip_prefix("Bearer "))
        .map(|t| t.trim().to_string())
        .filter(|t| !t.is_empty())
}

/// Result of the prepare phase.
#[allow(clippy::large_enum_variant)]
enum Prepared {
    /// Ready to forward to a local worker — all pre-forward work is done.
    Forward(PreparedForward),
    /// Short-circuit: prepare already produced a final response
    /// (auth failure, 402, 413, local-mode no-worker 503, or the entire
    /// P2P dispatch_to_peers path which returns its own BrokerResponse).
    Done(BrokerResponse),
}

/// Pre-forward half of execute: authenticate, balance, route, reserve credits,
/// WAL RESERVED, read body. Returns either `Prepared::Forward` (ready to call
/// `forward_to_worker`) or `Prepared::Done` (early response).
///
/// Zero behavior change vs the original `handle_execute` up to the forward call.
fn execute_prepare(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
    verbose: bool,
    arrived: Instant,
    inflight: &mut Option<super::InflightHold>,
) -> Prepared {
    let start = Instant::now();
    // Timed from ARRIVAL, not from here: the production route hands prepare to
    // the blocking pool, and a request can wait there for as long as the work
    // itself takes. A walk that starts once prepare is already running cannot
    // see the one delay that grows with load.
    let mut phases = Phases::new(arrived);
    phases.mark("queue");
    let trace = request
        .header("X-Zakuro-Trace")
        .is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes"));
    let request_id = uuid::Uuid::new_v4().to_string();
    let tx_num = REQUEST_COUNTER.fetch_add(1, Ordering::SeqCst) + 1;

    // Instance affinity headers (set by RemoteProxy for stateful class instances)
    let instance_action = request.header("X-Zakuro-Instance-Action");
    let instance_id = request.header("X-Zakuro-Instance-Id");

    // Kept for voucher minting: a foreign requester's voucher is minted under
    // THEIR credential (see `mint_and_verify_voucher`).
    let requester_key = bearer_token(request.header("Authorization").as_deref());
    let user_id = match identify(state, request) {
        Ok(uid) => uid,
        Err(resp) => return Prepared::Done(resp),
    };
    // Paid work from here on: take the guard only once the caller is
    // authenticated, so an anonymous request cannot cancel a benchmark. The
    // caller keeps it for the whole forward.
    *inflight = Some(super::InflightHold::new(state));

    phases.mark("auth");

    // Parse requirements from header
    let requirements: ResourceRequirements = request
        .header("X-Zakuro-Requirements")
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default();

    // Reject invalid budget_credits early — must be positive if present
    if let Some(b) = requirements.budget_credits {
        if b <= 0.0 {
            return Prepared::Done(error_response(
                "budget_credits must be positive",
                "BAD_REQUEST",
                400,
            ));
        }
    }

    // Required capability tags (zc#403): fail with a clear error naming the
    // missing tag instead of falling back to a node without it. The registry
    // includes peer-synced workers, so a tagged peer satisfies it.
    if let Some(e) = router::tags_unsatisfied(&state.workers.healthy(), &requirements.tags) {
        return Prepared::Done(error_response(&e.message, &e.code, 503));
    }

    // Determine P2P authority for this user
    let authority = state.peer_manager.determine_authority(&user_id);

    // Get user balance — P2P-aware
    let balance_before = match &authority {
        Authority::Local => {
            // Authoritative: read from DashMap (loads from PG on first access)
            state.ledger.load_balance_if_needed(&user_id)
        }
        Authority::Peer(url) => peer_balance(state, url, &user_id),
        Authority::Standalone => state.ledger.load_balance_if_needed(&user_id),
    };

    phases.mark("balance");

    // Sync in-memory credit manager with ledger balance (for router credit checks + rate limiting)
    let _ = state.credits.get_or_create(&user_id, balance_before);
    if matches!(authority, Authority::Peer(_)) {
        // Non-authoritative: mark balance as prefetched from peer
        state
            .credits
            .set_prefetched_balance(&user_id, balance_before);
    } else {
        state.credits.set_balance(&user_id, balance_before);
    }

    // --- Instance affinity: route call_method to the pinned worker ---
    let pinned_worker = if matches!(
        instance_action.as_deref(),
        Some("call_method") | Some("release_instance")
    ) {
        if let Some(ref iid) = instance_id {
            if let Some(worker_id) = state.instance_registry.get(iid) {
                state.workers.get(&worker_id)
            } else {
                // Instance not in registry — return clear error
                log_transaction(
                    state,
                    verbose,
                    tx_num,
                    &user_id,
                    "CALL_METHOD",
                    0.0,
                    balance_before,
                    None,
                    0.0,
                    "FAIL",
                );
                return Prepared::Done(error_response(
                    &format!("Instance not found in broker registry: {}", iid),
                    "INSTANCE_NOT_FOUND",
                    404,
                ));
            }
        } else {
            None
        }
    } else {
        None
    };

    // Select worker: use pinned worker for call_method, otherwise normal routing
    let routing = if let Some(worker) = pinned_worker {
        // Pinned worker for instance affinity — skip router
        if worker.status != WorkerStatus::Healthy {
            log_transaction(
                state,
                verbose,
                tx_num,
                &user_id,
                "CALL_METHOD",
                0.0,
                balance_before,
                Some(&worker.name),
                0.0,
                "FAIL",
            );
            // Clean up stale instance binding
            if let Some(ref iid) = instance_id {
                state.instance_registry.remove(iid.as_str());
            }
            return Prepared::Done(error_response(
                "Pinned worker is unhealthy, instance binding removed",
                "WORKER_UNHEALTHY",
                503,
            ));
        }
        RoutingDecision {
            estimated_cost: worker
                .pricing
                .estimate_cost(requirements.estimated_duration_secs),
            reason: format!("Instance affinity: pinned to {}", worker.name),
            alternatives_count: 0,
            worker,
        }
    } else if state.is_local_mode() || !state.is_billing_enabled() {
        // No billing → skip credit checks, use any worker
        match choose_worker(state, verbose, |adaptive| {
            state
                .router
                .select_worker_no_checks(&state.workers, &requirements, adaptive)
        }) {
            Ok(r) => r,
            Err(e) => {
                log_transaction(
                    state,
                    verbose,
                    tx_num,
                    &user_id,
                    "EXECUTE",
                    0.0,
                    balance_before,
                    None,
                    0.0,
                    "FAIL",
                );
                let status = if e.code == "QUOTA_EXCEEDED" { 429 } else { 503 };
                return Prepared::Done(error_response(&e.message, &e.code, status));
            }
        }
    } else if state.peer_manager.is_enabled() {
        // ── Publish-lock model (P2P + billing) ────────────────────────
        // 1) Try LOCAL workers first (self-execution = free), unless remote_only
        // 2) If no local worker (or remote_only) → publish task to peers
        let is_self_owned = state.config.owner_user_id.as_deref() == Some(user_id.as_str());
        // Targeted addressing: clients pin to a BROKER (target_node), never a
        // worker — the broker managing a set of workers has sole authority
        // over which worker runs a job. `target_worker` is a client-facing
        // no-op for routing (kept in the request schema for
        // backward-compat/observability only); see
        // docs/superpowers/specs/2026-07-11-zc-key-derived-identity-amendment.md
        // "Routing addendum".
        //
        // Resolved by fingerprint only (node_identity::node_filter_matches) — a
        // hostname/label target never resolves to "local", even if it happens to
        // look like a handle.
        let target_node = requirements.target_node.as_deref();
        let force_remote = requirements.remote_only
            || target_node
                .is_some_and(|tn| !node_identity::node_filter_matches(&state.node_key, tn));
        let try_local: Option<RoutingDecision> = if force_remote {
            None
        } else {
            let live_ts_ip =
                super::discovery::get_mesh_ip().or_else(|| state.own_wireguard_ip.clone());
            choose_worker(state, verbose, |adaptive| {
                state.router.select_local_worker(
                    &state.workers,
                    live_ts_ip.as_deref(),
                    &requirements,
                    adaptive,
                )
            })
            .ok()
        };
        if let Some(local_decision) = try_local {
            local_decision
        } else {
            // No local worker (or remote_only=true) → build offer and dispatch to peer brokers.
            {
                let body = match body_or_413(request) {
                    Ok(b) => b,
                    Err(resp) => return Prepared::Done(resp),
                };
                // When vouchers are required, obtain AND VERIFY a dashboard-signed
                // voucher authorizing this spend, then attach it to the offer.
                // Off by default (no added latency).
                //
                // Fail-closed AT MINT — same verify-at-mint discipline as the
                // direct path's `mint_and_verify_voucher`: require the cached
                // dashboard pubkey, verify the signature, and enforce
                // `voucher_commission_valid`. Any failure REJECTS the job here,
                // pre-dispatch. Crucially, the ONE verified `commission_c` is
                // captured now and threaded into `dispatch_to_peers` for the
                // executor payout — settlement no longer re-derives commission
                // via `offer_commission_c` (which returned 0.0 on a missing/
                // rotated pubkey and paid the executor the FULL cost while the
                // executor-side redeem still credited platform commission →
                // MINTED credits). Mint-time verify + threaded c means the
                // earn(payout) leg and the dashboard redeem always agree.
                let (voucher_signed_json, voucher_sig, offer_commission_c_verified) =
                    if voucher_required() {
                        let budget = requirements.budget_credits.unwrap_or(0.0);
                        if budget <= 0.0 {
                            return Prepared::Done(error_response(
                                "Voucher required for remote dispatch but no positive \
                                 budget_credits supplied",
                                "VOUCHER_UNAVAILABLE",
                                503,
                            ));
                        }
                        match mint_and_verify_voucher(state, budget, requester_key.as_deref()) {
                            Ok((j, s, v)) => (j, s, v.commission_c),
                            Err(resp) => return Prepared::Done(resp),
                        }
                    } else {
                        (String::new(), String::new(), 0.0)
                    };
                let offer = task_board::TaskOffer {
                    task_id: request_id.clone(),
                    payload_b64: base64::Engine::encode(
                        &base64::engine::general_purpose::STANDARD,
                        body,
                    ),
                    max_price_per_hour: if let Some(budget) = requirements.budget_credits {
                        let hours = requirements.estimated_duration_secs / 3600.0;
                        if hours > 0.0 {
                            budget / hours
                        } else {
                            f64::MAX
                        }
                    } else {
                        f64::MAX
                    },
                    estimated_duration_secs: requirements.estimated_duration_secs,
                    timeout_secs: requirements.timeout_secs,
                    cpus: requirements.cpus,
                    memory_bytes: requirements.memory_bytes,
                    gpus: requirements.gpus,
                    worker_type: requirements.worker_type.clone(),
                    tags: requirements.tags.clone(),
                    requester_user_id: user_id.clone(),
                    source_broker: state.config.node_name.clone().unwrap_or_default(),
                    peer_key: state.peer_manager.peer_key().to_string(),
                    // One-phase by default; the dispatcher sets this per-peer in
                    // two-phase mode (Task 4). Keeps current behavior until then.
                    two_phase: false,
                    voucher_signed_json,
                    voucher_sig,
                    // A client-supplied target_worker is never forwarded into the
                    // offer — worker selection is the accepting broker's private
                    // authority, not something a client (or a relaying peer) can
                    // steer. `target_worker` stays reserved on TaskOffer for
                    // internal/observability use only.
                    target_worker: String::new(),
                    // A NODE pin does travel: which broker runs the work is the
                    // requester's to choose, and `dispatch_to_peers` needs it to
                    // send the offer to that peer alone instead of racing the
                    // whole mesh for it.
                    target_node: target_node.unwrap_or_default().to_string(),
                    // Set per send by the QUIC transport (`sign_for_quic`); the
                    // HTTP path signs with `X-Node-*` headers instead.
                    node_sig: None,
                };
                state.stats.record_task_offer(TaskOfferRecord {
                    task_id: request_id.clone(),
                    timestamp: Local::now(),
                    requester_user_id: user_id.clone(),
                    max_price_per_hour: offer.max_price_per_hour,
                    source_broker: offer.source_broker.clone(),
                });

                // ── Marketplace policy pre-selection (task 5) ─────────────
                // Pick the single best-admitted peer (resource-sufficient,
                // fresh advert, lowest observed latency) and hand it to
                // `dispatch_to_peers` to try FIRST, directly, ahead of the
                // broadcast race. `ZAKURO_MARKETPLACE_SELECT=0` disables this
                // (preferred_peer stays None) for safe rollout — behavior is
                // then byte-for-byte identical to the legacy path.
                let preferred_peer = if marketplace_select_enabled() {
                    preselect_executor_peer(state, &requirements)
                } else {
                    None
                };

                return Prepared::Done(dispatch_to_peers(
                    state,
                    offer,
                    start,
                    &user_id,
                    is_self_owned,
                    &request_id,
                    tx_num,
                    verbose,
                    balance_before,
                    preferred_peer,
                    offer_commission_c_verified,
                ));
            }
        }
    } else {
        // Non-P2P billing mode: use standard routing with credit checks
        match choose_worker(state, verbose, |adaptive| {
            state.router.select_worker(
                &state.workers,
                &state.credits,
                &user_id,
                balance_before,
                &requirements,
                adaptive,
            )
        }) {
            Ok(r) => r,
            Err(ref e) if e.code == "INSUFFICIENT_CREDITS" || e.code == "TIMEOUT_INCOMPATIBLE" => {
                if requirements.remote_only {
                    log_transaction(
                        state,
                        verbose,
                        tx_num,
                        &user_id,
                        "EXECUTE",
                        0.0,
                        balance_before,
                        None,
                        0.0,
                        "FAIL",
                    );
                    let status = if e.code == "INSUFFICIENT_CREDITS" {
                        402
                    } else {
                        503
                    };
                    return Prepared::Done(error_response(&e.message, &e.code, status));
                }
                // The free local fallback is for the OWNER's own jobs. A foreign
                // requester who cannot afford the job gets the 402 below — running
                // it free on this node's worker was an unbilled compute leak.
                let owner_here = state.config.owner_user_id.as_deref() == Some(user_id.as_str());
                let healthy = if owner_here {
                    state.workers.healthy()
                } else {
                    Vec::new()
                };
                match healthy.into_iter().find(|w| state.is_local_worker(&w.uri)) {
                    Some(local_worker) => RoutingDecision {
                        worker: local_worker,
                        estimated_cost: 0.0,
                        reason: "Local fallback - free execution".to_string(),
                        alternatives_count: 0,
                    },
                    None => {
                        log_transaction(
                            state,
                            verbose,
                            tx_num,
                            &user_id,
                            "EXECUTE",
                            0.0,
                            balance_before,
                            None,
                            0.0,
                            "FAIL",
                        );
                        let status = if e.code == "INSUFFICIENT_CREDITS" {
                            402
                        } else {
                            503
                        };
                        return Prepared::Done(error_response(&e.message, &e.code, status));
                    }
                }
            }
            Err(e) => {
                let status = match e.code.as_str() {
                    "INSUFFICIENT_CREDITS" => 402,
                    "RATE_LIMITED" | "QUOTA_EXCEEDED" => 429,
                    "NO_WORKERS"
                    | "NO_CAPACITY"
                    | "TIMEOUT_INCOMPATIBLE"
                    | "NO_WORKERS_WITH_TAGS" => 503,
                    _ => 400,
                };
                log_transaction(
                    state,
                    verbose,
                    tx_num,
                    &user_id,
                    "EXECUTE",
                    0.0,
                    balance_before,
                    None,
                    0.0,
                    "FAIL",
                );
                return Prepared::Done(error_response(&e.message, &e.code, status));
            }
        }
    };

    // At this point, routing selected a local worker → execute directly.
    // (Remote execution in P2P mode already returned above via the publish-lock path.)
    let is_self_owned = state.config.owner_user_id.as_deref() == Some(&user_id);
    // "Free" means: no billing authority at all, or the owner running their
    // own jobs. Landing on THIS node's own worker is NOT what makes a job
    // free — a foreign requester who addresses this broker directly pays the
    // worker's price like anyone else, and the owner earns it (see the
    // self-executed branch in `commit_credits`). Before this, every direct
    // request to a fleet broker that its own worker could serve ran at
    // cost 0 while the same job forwarded to a peer was billed.
    let self_executed = ran_on_our_hardware(state, &routing.worker);
    let is_local = execution_is_free(state.is_billing_enabled(), is_self_owned, self_executed);

    phases.mark("route");

    // Derive effective timeout from budget_credits if provided.
    // budget_credits / (price_per_hour / 3600) = max seconds the budget covers.
    let effective_timeout = if let Some(budget) = requirements.budget_credits {
        let price_per_sec = routing.worker.pricing.price_per_hour / 3600.0;
        let max_secs = if price_per_sec > 0.0 {
            budget / price_per_sec
        } else {
            86_400.0
        };
        if requirements.timeout_secs > 0.0 {
            max_secs.min(requirements.timeout_secs)
        } else {
            max_secs
        }
    } else {
        requirements.timeout_secs
    };

    // Calculate reservation amount: if a timeout is specified, reserve based on
    // effective_timeout * price_per_hour so a malicious user can at most lose credits
    // equal to their balance (capped by timeout). Otherwise use estimated cost.
    let reservation_amount = if !is_local && effective_timeout > 0.0 {
        // Reserve for the full timeout duration — this is the max the user can lose.
        let timeout_cost = routing.worker.pricing.estimate_cost(effective_timeout);
        // Cap reservation at user's balance — the user can at most lose what they have.
        timeout_cost.min(balance_before)
    } else {
        routing.estimated_cost
    };

    // ── Fail-closed voucher minting for the direct-forward remote path ──
    // Covers every route to a remote worker OTHER than `dispatch_to_peers`
    // (which mints its own voucher above, before building the offer): the
    // non-P2P billing path (`state.router.select_worker`) and
    // instance-affinity pinning to a remote worker. `is_local` is already
    // final at this point, so `!is_local` here always means "remote worker,
    // billing enabled" (the no-billing/local-mode branch forces `is_local`).
    //
    // Mint when the nonce will be redeemed, which `redeems_here` answers for
    // every authority now that `commit_credits`'s `Peer` arm settles the
    // executor side instead of stopping at the charge (#333). A mint or
    // verification failure still REJECTS the job rather than running it
    // uncommissioned.
    //
    // This deliberately goes through the same `voucher_need` as
    // `/execute/batch`. The rule used to be written out twice — once here and
    // once there — which is exactly how the batch endpoint shipped without it
    // (#322) and ran uncommissioned on every fleet with vouchers on.
    let (commission_c, voucher_task_nonce): (f64, String) = match voucher_need(
        is_local,
        voucher_required(),
        self_executed,
        redeems_here(&authority),
    ) {
        VoucherNeed::None => (0.0, String::new()),
        VoucherNeed::Mint => match mint_and_verify_remote_voucher(
            state,
            reservation_amount.max(routing.estimated_cost),
            requester_key.as_deref(),
        ) {
            Ok(v) => v,
            Err(resp) => return Prepared::Done(resp),
        },
        VoucherNeed::Refuse => {
            return Prepared::Done(error_response(
                "Voucher required for remote dispatch but this broker cannot redeem \
                 one for the requester; refusing to run uncommissioned",
                "VOUCHER_NON_LOCAL_AUTHORITY",
                503,
            ));
        }
    };

    phases.mark("voucher");

    // Executor reading the requester's balance for a voucher-backed job: let
    // the hub see the voucher nonce on the read (zc#400). Served from the
    // freshness cache when it is warm, so this adds no hub call in the common case.
    if !is_local && !voucher_task_nonce.is_empty() {
        state
            .ledger
            .get_balance_for_voucher(&user_id, Some(&voucher_task_nonce));
    }

    // Reserve credits — P2P-aware (skip for local worker - free execution)
    let reservation_id = if is_local {
        format!("local-{}", request_id)
    } else {
        match reserve_credits(
            state,
            &authority,
            &user_id,
            reservation_amount,
            &request_id,
            verbose,
            tx_num,
            balance_before,
        ) {
            Ok(id) => id,
            Err(resp) => return Prepared::Done(resp),
        }
    };

    // WAL: record reservation (skip for local worker)
    if !is_local {
        let _ = state.wal.append(&WalEntry {
            request_id: request_id.clone(),
            user_id: user_id.clone(),
            reservation_id: reservation_id.clone(),
            estimated_cost: reservation_amount,
            actual_cost: None,
            worker_id: routing.worker.id.clone(),
            worker_name: Some(routing.worker.name.clone()),
            duration_ms: None,
            timestamp: chrono::Utc::now(),
            status: WalStatus::Reserved,
            voucher_nonce: nonce_opt(&voucher_task_nonce),
        });
    }

    phases.mark("reserve");

    // Read request body BEFORE inserting into active_requests so a 413 early-return
    // does not leave a stale entry (matches original pre-split behavior where the
    // active_guard drop and the active_requests insert were both skipped on 413).
    let body = match body_or_413(request) {
        Ok(b) => b.to_vec(),
        Err(resp) => return Prepared::Done(resp),
    };

    // Track request (RAII in-flight guard is created in handle_execute just before
    // forward_to_worker so the guard's drop always pairs with the forward attempt).
    state
        .active_requests
        .insert(request_id.clone(), routing.worker.id.clone());

    phases.mark("body");

    let worker_uri = format!("{}/execute", routing.worker.uri.trim_end_matches('/'));
    let reason = routing.reason.clone();

    Prepared::Forward(PreparedForward {
        worker_uri,
        body,
        request_id,
        tx_num,
        effective_timeout,
        user_id,
        authority,
        reservation_id,
        balance_before,
        worker: routing.worker,
        is_local,
        reservation_amount,
        instance_action,
        instance_id,
        start,
        commission_c,
        voucher_task_nonce,
        reason,
        phases,
        trace,
    })
}

fn handle_execute(
    state: Arc<BrokerState>,
    request: &BrokerRequest,
    verbose: bool,
) -> BrokerResponse {
    let mut inflight = None;
    let prepared = execute_prepare(&state, request, verbose, Instant::now(), &mut inflight);
    // Held to the end of the request, forward and settlement included.
    let _inflight_hold = &inflight;
    let mut p = match prepared {
        Prepared::Done(r) => return r,
        Prepared::Forward(p) => p,
    };

    // Manually increment in-flight counter (no RAII guard — execute_finish
    // is now responsible for decrementing on every exit path).
    state.workers.increment_active(&p.worker.id);

    let forward = forward_to_worker(
        pick_forward_agent(
            &state.http_client,
            state.http_client_mesh.as_ref(),
            &p.worker_uri,
        ),
        &p.worker_uri,
        &p.body,
        &p.request_id,
        p.effective_timeout,
    )
    .map(into_worker_reply)
    .map_err(|e| e.to_string());
    p.phases.mark("forward");

    execute_finish(&state, verbose, p, forward)
}

/// Build the broker's async runtime.
///
/// `worker_threads` sizes tokio's async worker pool:
/// - `None` → multi-thread, one worker per CPU. Production default and the
///   configuration the async-migration benchmark was run against.
/// - `Some(n)` with `n >= 1` → multi-thread with exactly `n` workers.
/// - `Some(0)` → **current-thread** runtime: the async work runs on the
///   broker's own thread, so it spawns **no** persistent worker threads.
///
/// The `Some(0)` mode exists for the test suite. Tests start hundreds of
/// brokers in one process and never shut their runtimes down; a per-CPU (or
/// even 2-thread) worker pool *per leaked broker* accumulates ~350–1100 live
/// threads on a 20-core box, and that oversubscription starves latency-sensitive
/// tests like `test_p2p_mesh_fibonacci_500` into spurious global-timeout
/// failures. A current-thread runtime leaks ~0 persistent threads per broker,
/// so the cumulative count stays flat no matter how many brokers the suite
/// spawns. The blocking pool (capped at 64, created on demand and reaped when
/// idle) still offloads the synchronous `/execute` work in every mode.
fn build_broker_runtime(worker_threads: Option<usize>) -> std::io::Result<tokio::runtime::Runtime> {
    if matches!(worker_threads, Some(0)) {
        return tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .max_blocking_threads(64)
            .build();
    }
    let mut builder = tokio::runtime::Builder::new_multi_thread();
    builder.enable_all().max_blocking_threads(64);
    if let Some(n) = worker_threads {
        builder.worker_threads(n.max(1));
    }
    builder.build()
}

/// Serve the broker HTTP API on an axum/tokio runtime bound to `host:port`.
///
/// A single catch-all fallback builds a transport-agnostic `BrokerRequest` and
/// runs the unchanged `handle()` on a bounded `spawn_blocking` pool (so the
/// long, blocking `/execute` path can never starve the async accept loop or
/// explode into an unbounded thread-per-request as the old tiny_http frontend
/// did). `handle()` itself does all routing — unknown routes fall through to
/// its own 404. Blocks the calling thread until the server stops.
/// Resolves on SIGTERM (`systemctl stop`/`restart`) or SIGINT (Ctrl-C), and
/// clears `running` as it resolves so the cleanup thread's loop (the one that
/// owns the graceful-shutdown flush block) stops waiting on its next tick
/// instead of sleeping through the shutdown. Without this, nothing ever
/// cleared `running`, so a SIGTERM killed the process before either the WAL
/// or the tx_buffer got flushed (crash-durability gap: ~2.9% payout loss
/// under chaos testing).
async fn shutdown_signal(running: Arc<AtomicBool>) {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };

    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut sig) => {
                sig.recv().await;
            }
            Err(e) => {
                eprintln!("  [SHUTDOWN] failed to install SIGTERM handler: {}", e);
                std::future::pending::<()>().await;
            }
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {}
        _ = terminate => {}
    }

    eprintln!("  [SHUTDOWN] signal received, starting graceful shutdown...");
    running.store(false, Ordering::Relaxed);
}

fn serve_axum(
    state: Arc<BrokerState>,
    host: String,
    port: u16,
    verbose: bool,
    running: Arc<AtomicBool>,
) -> std::io::Result<()> {
    use axum::extract::ConnectInfo;
    use axum::response::IntoResponse;

    let rt = build_broker_runtime(state.config.runtime_worker_threads)?;

    rt.block_on(async move {
        // /execute fast path: run execute_prepare / execute_finish directly on the
        // async runtime instead of bouncing each through a spawn_blocking handoff
        // (two thread handoffs per request). Only safe when the hot path can never
        // block:
        //   * standalone ledger (`!is_api_mode()`) — no synchronous dashboard-API
        //     auth/balance calls on the request path,
        //   * keys not validated with the hub (#384) — that is a blocking round trip,
        //   * no P2P (`!peer_manager.is_enabled()`) — no synchronous peer
        //     reserve/commit calls,
        //   * WAL `fsync` is off the request thread (the dedicated flush worker).
        // Auto-enabled in that mode. `ZC_INLINE_EXECUTE` overrides either way:
        // `1`/`true` forces it on (operator asserts a non-blocking hot path),
        // any other value forces it off (keep the spawn_blocking path).
        let inline_safe = !state.ledger.is_api_mode()
            && !state.ledger.validates_keys_with_hub()
            && !state.peer_manager.is_enabled();
        let inline_forced = std::env::var("ZC_INLINE_EXECUTE").ok();
        let inline_execute = match inline_forced.as_deref() {
            Some(v) => v == "1" || v.eq_ignore_ascii_case("true"),
            None => inline_safe,
        };
        if inline_execute {
            eprintln!(
                "[PERF] /execute inline fast path ENABLED ({})",
                if inline_forced.is_some() {
                    "forced via ZC_INLINE_EXECUTE"
                } else {
                    "auto: standalone ledger, no P2P"
                }
            );
        }
        let app = axum::Router::new()
            // ── Batch execute: many tasks, one round trip, one reservation.
            .route(
                "/execute/batch",
                axum::routing::post({
                    let state = state.clone();
                    move |ConnectInfo(peer): ConnectInfo<SocketAddr>,
                          req: axum::extract::Request| {
                        let state = state.clone();
                        async move {
                            let breq = BrokerRequest::from_axum(req, Some(peer)).await;
                            handle_execute_batch(state, breq, verbose)
                                .await
                                .into_response()
                        }
                    }
                }),
            )
            // ── Async /execute route: worker round-trip runs on the tokio
            // runtime instead of holding a blocking-pool thread.
            .route(
                "/execute",
                axum::routing::post({
                    let state = state.clone();
                    move |ConnectInfo(peer): ConnectInfo<SocketAddr>,
                          req: axum::extract::Request| {
                        let state = state.clone();
                        async move {
                            let mut inflight: Option<super::InflightHold> = None;
                            let breq = BrokerRequest::from_axum(req, Some(peer)).await;
                            // Before the blocking hop, so the wait for a pool
                            // slot lands in the trace rather than vanishing.
                            let arrived = Instant::now();
                            // Phase 1: auth, routing, WAL reserve — synchronous/blocking.
                            let prepared = if inline_execute {
                                execute_prepare(&state, &breq, verbose, arrived, &mut inflight)
                            } else {
                                let st = state.clone();
                                match tokio::task::spawn_blocking(move || {
                                    let mut held = None;
                                    let p =
                                        execute_prepare(&st, &breq, verbose, arrived, &mut held);
                                    (p, held)
                                })
                                .await
                                {
                                    Ok((p, held)) => {
                                        inflight = held;
                                        p
                                    }
                                    Err(_) => {
                                        return BrokerResponse::json_bytes(
                                            br#"{"error":"handler panicked","code":"INTERNAL"}"#
                                                .to_vec(),
                                            500,
                                        )
                                        .into_response()
                                    }
                                }
                            };
                            // Held to the end of the request, forward and settlement included.
                            let _inflight_hold = &inflight;
                            let mut p = match prepared {
                                Prepared::Done(r) => return r.into_response(),
                                Prepared::Forward(p) => p,
                            };
                            // Phase 2: async worker forward (does not hold a blocking thread).
                            state.workers.increment_active(&p.worker.id);
                            let forward = forward_to_worker_async(
                                pick_forward_client(
                                    &state.async_http,
                                    state.async_http_mesh.as_ref(),
                                    &p.worker_uri,
                                ),
                                &p.worker_uri,
                                p.body.clone(),
                                &p.request_id,
                                p.effective_timeout,
                            )
                            .await;
                            p.phases.mark("forward");
                            // Phase 3: billing, WAL commit, response — synchronous/blocking.
                            // Capture worker_id before `p` is moved into the closure so we can
                            // decrement the in-flight counter if execute_finish panics.
                            let worker_id = p.worker.id.clone();
                            if inline_execute {
                                // Inline path mirrors the spawn_blocking branch's panic
                                // safety: catch_unwind so a panicking execute_finish still
                                // balances the increment_active above (otherwise the worker
                                // would leak an in-flight slot and skew routing).
                                match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                    execute_finish(&state, verbose, p, forward)
                                })) {
                                    Ok(r) => r.into_response(),
                                    Err(_) => {
                                        state.workers.decrement_active(&worker_id);
                                        BrokerResponse::json_bytes(
                                            br#"{"error":"handler panicked","code":"INTERNAL"}"#
                                                .to_vec(),
                                            500,
                                        )
                                        .into_response()
                                    }
                                }
                            } else {
                                let st = state.clone();
                                match tokio::task::spawn_blocking(move || {
                                    execute_finish(&st, verbose, p, forward)
                                })
                                .await
                                {
                                    Ok(r) => r.into_response(),
                                    Err(_) => {
                                        // execute_finish panicked: it never decremented the counter,
                                        // so we must balance the increment_active call above.
                                        state.workers.decrement_active(&worker_id);
                                        BrokerResponse::json_bytes(
                                            br#"{"error":"handler panicked","code":"INTERNAL"}"#
                                                .to_vec(),
                                            500,
                                        )
                                        .into_response()
                                    }
                                }
                            }
                        }
                    }
                }),
            )
            .fallback(
                move |ConnectInfo(peer): ConnectInfo<SocketAddr>, req: axum::extract::Request| {
                    let state = state.clone();
                    async move {
                        let breq = BrokerRequest::from_axum(req, Some(peer)).await;
                        match tokio::task::spawn_blocking(move || handle(state, &breq, verbose))
                            .await
                        {
                            Ok(resp) => resp.into_response(),
                            Err(_join_err) => {
                                // Handler panicked: mirror an internal error.
                                BrokerResponse::json_bytes(
                                    br#"{"error":"handler panicked","code":"INTERNAL"}"#.to_vec(),
                                    500,
                                )
                                .into_response()
                            }
                        }
                    }
                },
            );

        let listener = tokio::net::TcpListener::bind((host.as_str(), port)).await?;
        axum::serve(
            listener,
            app.into_make_service_with_connect_info::<SocketAddr>(),
        )
        .with_graceful_shutdown(shutdown_signal(running))
        .await
    })
}

/// Start the QUIC transport for peer-to-peer task offers, when P2P is on and
/// [`quic_wanted`] allows it. It's off with `ZAKURO_DISABLE_QUIC=1` (UDP/QUIC
/// between nodes blocked or unreliable), and on the proxy route, whose
/// container relay carries TCP only (mesh-routes §4). This broker then
/// advertises `quic_port` 0 in `/peer/identity`, peers offer to it over HTTP,
/// and [`offer_transport`] sends its own offers over HTTP. `start_server`
/// calls this once, with `vpn::route()`: the agent restarts the broker when
/// the route changes.
fn start_quic_transport(
    state: &Arc<BrokerState>,
    config: &BrokerConfig,
    route: &crate::vpn::Route,
    disable_env: Option<&str>,
) {
    if !state.peer_manager.is_enabled() {
        return;
    }
    if !quic_wanted(disable_env, route) {
        if route.is_proxy() {
            eprintln!(
                "  [QUIC] off: the mesh is reached through the zakuro-wg container, which relays TCP only; peer offers use HTTP"
            );
        }
        return;
    }

    let quic_port = config.quic_port.unwrap_or(config.port + 1);
    let quic_addr = SocketAddr::from(([0, 0, 0, 0], quic_port));

    match super::quic::QuicTransport::new(quic_addr, state.clone()) {
        Ok(qt) => {
            let actual_port = qt.local_addr().map(|a| a.port()).unwrap_or(quic_port);
            state.quic_port.store(actual_port, Ordering::Relaxed);
            let local = qt.local_addr().map(|a| a.to_string()).unwrap_or_default();
            let _ = state.quic.set(qt);
            eprintln!("  [QUIC] Listening on {} (peer task transport)", local);

            // Subscribe to peers' task feeds so we get offers pushed immediately (ultra reactive).
            let our_url = format!(
                "http://{}:{}",
                state.own_wireguard_ip.as_deref().unwrap_or("127.0.0.1"),
                config.port
            );
            super::quic::run_subscription_client(
                state.clone(),
                our_url,
                std::sync::Arc::new(execute_feed_offer),
            );
        }
        Err(e) => {
            eprintln!("  [QUIC] Failed to start: {} (falling back to HTTP)", e);
        }
    }

    // Spawn a delayed QUIC port discovery (peers may not be up yet)
    let state_for_discovery = state.clone();
    async_exec::spawn_detached(move || {
        thread::sleep(std::time::Duration::from_millis(500));
        state_for_discovery.peer_manager.discover_quic_ports();
    });
}

/// Start the broker server
/// Test-only: loopback ports whose broker must NOT probe the host for a mesh.
///
/// `detect_discovery_mode` reads host state (mesh interface address, a TCP probe
/// of `<subnet>.1`, `ZAKURO_PEERS`), so the same test broker was in local mode in
/// CI and in mesh mode on a mesh member, where keyless `/execute` is a 401 (#346).
/// The in-process test broker registers its port here to get `Local` always.
#[cfg(test)]
pub(crate) fn hermetic_ports() -> &'static std::sync::Mutex<std::collections::HashSet<u16>> {
    static P: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<u16>>> =
        std::sync::OnceLock::new();
    P.get_or_init(Default::default)
}

/// Discovery mode for this broker: host detection, except for hermetic test brokers.
fn discovery_mode_for(config: &BrokerConfig) -> DiscoveryMode {
    #[cfg(test)]
    if hermetic_ports()
        .lock()
        .map(|p| p.contains(&config.port))
        .unwrap_or(false)
    {
        return DiscoveryMode::Local;
    }
    detect_discovery_mode(&config.discovery.subnet)
}

pub fn start_server(config: BrokerConfig) -> std::io::Result<()> {
    let addr = format!("{}:{}", config.host, config.port);
    let bind_host = config.host.clone();
    let bind_port = config.port;

    let verbose = config.verbose;
    let daemon = config.daemon;
    let mut broker_state = BrokerState::with_config(config.clone());

    // Startup handshake: verify broker identity with the dashboard.
    // This resolves the real owner_user_id from the API key and ensures
    // the broker only operates with a verified identity.
    if broker_state.ledger.trusts_key_shape() {
        eprintln!(
            "  [AUTH] WARNING: {}=1 — user keys are NOT validated against the hub; \
             the user billed is parsed from the key's shape, so anyone who knows a \
             user id can spend that user's credits. Emergency use only; unset it.",
            crate::broker::key_auth::TRUST_SHAPE_ENV
        );
    }
    if broker_state.is_billing_enabled() {
        match broker_state.verify_owner_with_dashboard() {
            Some(uid) => {
                eprintln!(
                    "  [HANDSHAKE] Verified owner: {} (dashboard confirmed)",
                    uid
                );
            }
            None => {
                eprintln!("  [HANDSHAKE] WARNING: Could not verify owner with dashboard — billing continues with configured credentials");
            }
        }
    }

    let state = Arc::new(broker_state);

    // Offline-first roster warm start: seed `node_roster` from the last
    // dashboard fetch cached to `~/.zakuro/roster.json`, so a broker that
    // restarts with the dashboard unreachable still has an authorized-node
    // roster (for both inbound `check_node_sig` and outbound discovery's
    // `RosterCache::fingerprint_authorized`) instead of starting empty and
    // rejecting every peer until the next live fetch succeeds.
    for (pk, revoked) in super::roster_cache::RosterCache::load().entries() {
        state.node_roster.insert(pk, revoked);
    }

    // Warm start: restore the peer set persisted at the end of the previous
    // run's discovery round (`peers.json`), so a restarted broker has known
    // peers immediately instead of waiting on gossip/mesh-scan/dashboard to
    // rebuild the set from scratch.
    if state.peer_manager.is_enabled() {
        state.peer_manager.load_persisted();
    }

    // Start QUIC transport for peer-to-peer task offers, decided once here from
    // the mesh route (mesh-routes §4).
    start_quic_transport(
        &state,
        &config,
        &crate::vpn::route(),
        std::env::var("ZAKURO_DISABLE_QUIC").ok().as_deref(),
    );

    // Replay WAL before accepting requests
    recovery::replay_wal(
        &state.wal,
        &state.ledger,
        &state.tx_buffer,
        state.config.node_name.as_deref(),
    );

    // Running flag for graceful shutdown
    let running = Arc::new(AtomicBool::new(true));

    // Dedicated WAL flush worker: owns every fsync so no request thread blocks on
    // durable I/O (group commit, age-bounded). `append` only pushes to the
    // lock-free buffer; this worker drains + fsyncs on the age bound / size
    // threshold and does a final drain when `running` clears.
    let state_wal = state.clone();
    let running_wal = running.clone();
    async_exec::spawn_detached(move || {
        state_wal.wal.run_flush_worker(&running_wal);
    });

    // Start background cleanup thread (includes WAL compaction every 5 min).
    // Its JoinHandle is kept (not detached) so `start_server` can block on it
    // after the HTTP server stops accepting connections — that's what
    // guarantees the graceful-shutdown flush below actually runs to
    // completion before the process exits on SIGTERM/SIGINT (see
    // `shutdown_signal` in `serve_axum`).
    let state_clone = state.clone();
    let running_cleanup = running.clone();
    let cleanup_handle = std::thread::Builder::new()
        .name("zc-cleanup".into())
        .spawn(move || {
            let mut compaction_counter: u64 = 0;
            while running_cleanup.load(Ordering::Relaxed) {
                thread::sleep(std::time::Duration::from_secs(
                    state_clone.config.health_check_interval,
                ));

                state_clone
                    .workers
                    .mark_stale(state_clone.config.worker_timeout as i64);
                // Remove workers stale for >2× the timeout (well beyond recoverable)
                let removed = state_clone
                    .workers
                    .remove_stale(state_clone.config.worker_timeout as i64 * 2);
                if !removed.is_empty() {
                    eprintln!("  [HEALTH] Removed {} stale worker(s)", removed.len());
                }
                // Release two-phase offers reserved but never committed/cancelled
                // (lost commit/cancel) so worker slots don't leak.
                sweep_expired_offers(
                    &state_clone,
                    std::time::Duration::from_secs(PENDING_OFFER_TTL_SECS),
                );
                state_clone.stats.tick_rps();

                // Deployment reconciler: fetch desired state from the hub and
                // drive local docker containers toward it (every 3 ticks ≈
                // 15s at default 5s interval — see `deploy::tick`, which is
                // itself a no-op when api_url/api_key aren't configured, same
                // precondition WORKER_SYNC below has). Reuses this thread
                // rather than spawning a dedicated one: the reconciler's own
                // work (docker CLI calls, HTTP polling for health) is no more
                // blocking than the worker-sync/roster-refresh calls already
                // sharing this loop.
                if compaction_counter.is_multiple_of(3) {
                    super::deploy::tick(&state_clone);
                }

                // Periodic worker sync (every 12 ticks ≈ 60s at default 5s interval)
                if compaction_counter.is_multiple_of(12) {
                    if let Some(ref owner_id) = state_clone.config.owner_user_id {
                        // Only sync workers that belong to this node (local or matching
                        // local WireGuard IP). P2P-discovered remote workers are synced
                        // by their own brokers with the correct source_node.
                        let local_ip = super::discovery::get_effective_node_ip();
                        let workers: Vec<_> = state_clone
                            .workers
                            .list()
                            .into_iter()
                            .filter(|w| match w.wireguard_ip.as_deref() {
                                Some("127.0.0.1") | Some("::1") | Some("localhost") | None => true,
                                Some(ip) => local_ip.as_deref() == Some(ip),
                            })
                            .collect();
                        let node_name = state_clone.config.node_name.as_deref();
                        // Same key this node registers on the roster below, so the
                        // dashboard can join worker rows to a live broker.
                        let node_pubkey = state_clone.node_key.public_b64();

                        if let (Some(ref api_url), Some(ref api_key)) =
                            (&state_clone.config.api_url, &state_clone.config.api_key)
                        {
                            match super::ledger::Ledger::sync_workers_via_api(
                                owner_id,
                                &workers,
                                api_url,
                                api_key,
                                node_name,
                                local_ip.as_deref(),
                                Some(node_pubkey.as_str()),
                            ) {
                                Ok(outcome) => {
                                    let repriced =
                                        state_clone.workers.apply_hub_prices(&outcome.prices);
                                    println!(
                                        "  [WORKER_SYNC] Synced {} worker(s) to {} via API ({} repriced by the hub)",
                                        workers.len(),
                                        api_url,
                                        repriced
                                    );
                                }
                                Err(e) => {
                                    eprintln!("  [WORKER_SYNC] API sync failed: {}", e);
                                }
                            }
                        }
                    }
                }

                // Zero-trust mesh: register this node's signing key and refresh the
                // authorized-node roster + dashboard voucher pubkey (every 12 ticks).
                if compaction_counter.is_multiple_of(12) {
                    if let (Some(ref api_url), Some(ref api_key)) =
                        (&state_clone.config.api_url, &state_clone.config.api_key)
                    {
                        let pubkey = state_clone.node_key.public_b64();
                        // Task 9 consumes `self_endpoint` to filter this broker's own
                        // address out of the peer list it derives from the roster.
                        //
                        // What this route can carry to our port (mesh-routes §4):
                        // the host address, the sidecar's address for a relayed
                        // port, or nothing. Recomputed every round, so a route
                        // change reaches the hub and the roster without a restart.
                        let route = crate::vpn::route();
                        let endpoint =
                            mesh_endpoint_for(route.advertised_ip(state_clone.config.port), state_clone.config.port);
                        let self_endpoint = endpoint.clone();
                        // Loud on purpose: with ZAKURO_PEERS still set the broker
                        // works cluster-native, and a silent fallback is how the
                        // mesh path stays unused. Rate-limited so a broker stuck
                        // without a tunnel (Fix 1's failure mode) doesn't page an
                        // stderr scraper every ~60s forever.
                        match MESH_ENDPOINT_LOG_GATE
                            .on_tick(endpoint.is_some(), super::node_identity::now_secs())
                        {
                            MeshEndpointLogAction::NoEndpoint => eprintln!(
                                "  [NODE_SYNC] no mesh address on the {} route - registering without one",
                                route.kind().label()
                            ),
                            MeshEndpointLogAction::Recovered => println!(
                                "  [NODE_SYNC] mesh endpoint present again - registering as reachable"
                            ),
                            MeshEndpointLogAction::None => {}
                        }
                        // Whether this host can run a deployment at all. The
                        // hub judges deploy-host eligibility on it; without
                        // it a live broker with no docker is offered in the
                        // hosts list and whatever lands there sits `pending`
                        // forever. One `docker info` per node-sync round
                        // (~60s), alongside the HTTP calls already here.
                        let deploy_runtime = super::deploy::runtime_available();
                        if let Err(e) = super::node_sync::register_node(
                            api_url,
                            api_key,
                            &pubkey,
                            endpoint.as_deref(),
                            Some(deploy_runtime),
                        ) {
                            eprintln!("  [NODE_SYNC] register failed: {e}");
                        } else {
                            // Registered: this node can submit what it measures.
                            crate::bench_node::schedule::spawn_once(state_clone.clone());
                            // Spaces: claim loop (idle until `zc spaces enable`).
                            crate::spaces::schedule::spawn_once(state_clone.clone());
                        }
                        match super::node_sync::fetch_roster_full(api_url, api_key) {
                            Ok((pairs, endpoints)) => {
                                let fresh: std::collections::HashSet<String> =
                                    pairs.iter().map(|(k, _)| k.clone()).collect();
                                for (pk, revoked) in pairs.clone() {
                                    state_clone.node_roster.insert(pk, revoked);
                                }
                                // Drop nodes no longer in the roster (no empty-window race).
                                state_clone.node_roster.retain(|k, _| fresh.contains(k));
                                // Cache the live roster to disk so a restarted broker (or
                                // a discovery round while the dashboard is down) has an
                                // offline fallback (finding 2 — T1 roster cache wiring).
                                let mut cache =
                                    super::roster_cache::RosterCache::from_entries(pairs);
                                cache.set_endpoints(endpoints);
                                cache.persist();

                                // Close the loop: dial peers discovered through the
                                // roster, not just the ones named in ZAKURO_PEERS.
                                // Roster endpoints are bare "ip:port" (see
                                // `RosterCache`'s doc comment); `peer_manager`
                                // registers and compares peers as full
                                // "http://ip:port" base URLs, so
                                // `roster_peer_entries` translates before merging.
                                // Self-filtering is by identity, not address —
                                // see that function's doc comment.
                                let roster_peers = roster_peer_entries(
                                    &cache,
                                    Some(pubkey.as_str()),
                                    self_endpoint.as_deref(),
                                );

                                // Resolve identities BEFORE deduping. A
                                // ZAKURO_PEERS entry and a roster entry for the
                                // same broker are two spellings of one node
                                // (`http://zc-broker-1.zc-broker...:9000` vs
                                // `http://10.13.13.7:9000`); comparing URL
                                // strings — as the previous merge did — sees two
                                // peers and registers both, giving one broker two
                                // PeerClients, two health probes, two task-feed
                                // subscriptions, and two identical `zc://node-<fp>`
                                // rows in `zc brokers`.
                                state_clone.peer_manager.ensure_fingerprints_cached();

                                let evicted = merge_roster_peers(
                                    &state_clone.peer_manager,
                                    &roster_peers,
                                );
                                if !evicted.is_empty() {
                                    println!(
                                        "  [NODE_SYNC] Evicted {} roster-derived peer(s) no longer on the roster",
                                        evicted.len()
                                    );
                                }
                            }
                            Err(e) => eprintln!("  [NODE_SYNC] roster fetch failed: {e}"),
                        }
                        match super::node_sync::fetch_voucher_pubkey(api_url) {
                            Ok(pks) => {
                                if let Ok(mut w) = state_clone.dash_voucher_pubkey.write() {
                                    *w = pks;
                                }
                            }
                            Err(e) => eprintln!("  [NODE_SYNC] voucher pubkey fetch failed: {e}"),
                        }
                    }
                }

                // Purge instance bindings for unhealthy workers
                let unhealthy_ids: Vec<String> = state_clone
                    .workers
                    .list()
                    .iter()
                    .filter(|w| w.status == WorkerStatus::Unhealthy)
                    .map(|w| w.id.clone())
                    .collect();
                if !unhealthy_ids.is_empty() {
                    state_clone
                        .instance_registry
                        .retain_workers(|worker_id| !unhealthy_ids.iter().any(|u| u == worker_id));
                }

                // The transaction flush used to live here, at the end of this
                // loop body, and that is what #341 was: this thread also makes
                // blocking hub calls (roster fetch, voucher pubkey, worker
                // sync, the docker reconciler). One of them wedged on a live
                // broker for eight hours. The broker kept serving `/execute`
                // and charging clients the whole time, and not one of those
                // transactions was ever delivered — the thread that would have
                // sent them was stuck earlier in the same body.
                //
                // It now runs on `zc-flush`, which does nothing else. The
                // delay of a stale roster is a stale roster; the delay of an
                // unsent transaction is unbilled work.
                // Also flush WAL write buffer
                if let Err(e) = state_clone.wal.flush_buffer() {
                    eprintln!("  [WAL] flush_buffer failed: {}", e);
                }

                // P2P: peer health check (every 12 ticks ≈ 60s)
                if compaction_counter.is_multiple_of(12) && state_clone.peer_manager.is_enabled() {
                    state_clone.peer_manager.health_check_all();
                }

                // P2P: roster-gated peer discovery round — merge signed gossip from
                // known peers (re-probing each hint via `discovery::accept_peer`) and
                // backfill via mesh scan when the peer set is empty (every 6 ticks
                // ≈ 30s). Gated on P2P being enabled and this node already having a
                // mesh IP (no mesh, no subnet to scan).
                if compaction_counter.is_multiple_of(6)
                    && state_clone.peer_manager.is_enabled()
                    && super::discovery::get_mesh_ip().is_some()
                {
                    // Prefer the live in-memory roster; fall back to the on-disk
                    // cache when it's empty (dashboard has never been reached
                    // this run, or `node_roster` was cleared) so discovery still
                    // has an authorized-node set to gate against offline
                    // (finding 2 — T1 roster cache wiring).
                    let roster = if state_clone.node_roster.is_empty() {
                        super::roster_cache::RosterCache::load()
                    } else {
                        super::roster_cache::RosterCache::from_entries(
                            state_clone
                                .node_roster
                                .iter()
                                .map(|e| (e.key().clone(), *e.value()))
                                .collect(),
                        )
                    };
                    super::discovery::run_discovery_round(&state_clone, &roster);
                }

                // QUIC: discover peer QUIC ports (on first tick and then periodically)
                if (compaction_counter <= 1 || compaction_counter.is_multiple_of(12))
                    && state_clone.peer_manager.is_enabled()
                    && state_clone.quic.get().is_some()
                {
                    state_clone.peer_manager.discover_quic_ports();
                }

                // P2P: reconcile stale prefetched balances (every 6 ticks ≈ 30s)
                if compaction_counter.is_multiple_of(6) && state_clone.peer_manager.is_enabled() {
                    let user_ids = state_clone.credits.get_all_user_ids();
                    for uid in user_ids {
                        if state_clone.credits.needs_reconciliation(&uid, 30) {
                            state_clone.credits.set_reconciling(&uid);
                            let authority = state_clone.peer_manager.determine_authority(&uid);
                            if let Authority::Peer(ref url) = authority {
                                if let Some(client) = state_clone.peer_manager.get_client(url) {
                                    match client.get_balance(&uid) {
                                        Ok(balance) => {
                                            state_clone
                                                .credits
                                                .set_prefetched_balance(&uid, balance);
                                        }
                                        Err(_) => {
                                            // Leave as reconciling until next attempt
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // WAL compaction every ~5 minutes (60 ticks at 5s interval)
                compaction_counter += 1;
                if compaction_counter.is_multiple_of(60) {
                    if let Err(e) = state_clone.wal.compact() {
                        eprintln!("  [WAL] Compaction failed: {}", e);
                    }
                }
            }

            if let Err(e) = state_clone.wal.flush_buffer() {
                eprintln!("  [WAL] flush_buffer failed: {}", e);
            }
        })
        .expect("failed to spawn zc-cleanup thread");

    // Settlement delivery, on a thread of its own.
    //
    // Nothing else belongs here. Everything this loop does not do — roster
    // fetches, worker sync, docker reconciliation — is something that can
    // block, and when it blocked on `zc-cleanup` it took billing delivery with
    // it silently (#341): clients were charged, transactions were buffered,
    // and the shutdown flush at the end of that thread never ran either,
    // because the thread never got there. So the restart that was supposed to
    // drain the backlog dropped it instead.
    //
    // Both the periodic flush and the final one live here now.
    let state_flush = state.clone();
    let running_flush = running.clone();
    let flush_handle = std::thread::Builder::new()
        .name("zc-flush".into())
        .spawn(move || {
            let interval =
                std::time::Duration::from_secs(state_flush.config.health_check_interval.max(1));
            while running_flush.load(Ordering::Relaxed) {
                thread::sleep(interval);
                if let (Some(ref api_url), Some(ref api_key)) =
                    (&state_flush.config.api_url, &state_flush.config.api_key)
                {
                    state_flush
                        .tx_buffer
                        .flush_to_api(api_url, api_key, &state_flush.wal);
                }
            }
            if let (Some(ref api_url), Some(ref api_key)) =
                (&state_flush.config.api_url, &state_flush.config.api_key)
            {
                eprintln!("  [FLUSH] Shutdown: flushing remaining transactions...");
                state_flush
                    .tx_buffer
                    .flush_to_api(api_url, api_key, &state_flush.wal);
            }
        })
        .expect("failed to spawn zc-flush thread");

    // Opt-in periodic self-update (no-op unless ZAKURO_AUTO_UPDATE is on).
    super::auto_update::spawn(state.clone());

    // Start worker discovery (WireGuard or local fallback)
    if config.enable_discovery {
        let state_for_discovery = state.clone();
        let discovery_config = config.discovery.clone();
        let discovery_verbose = verbose;

        // Detect mode before spawning thread so we can log it
        let mode = discovery_mode_for(&config);

        // Set local mode flag (free execution when not on WireGuard)
        let is_local = matches!(mode, DiscoveryMode::Local);
        state.set_local_mode(is_local);

        if verbose && !daemon {
            match &mode {
                DiscoveryMode::WireGuard { subnet } => {
                    println!(
                        "  {} WireGuard network detected (subnet: {}.0/24)",
                        "[DISCOVERY]".cyan(),
                        subnet
                    );
                }
                DiscoveryMode::Local => {
                    println!(
                        "  {} Local mode - free execution, scanning localhost:3960-3962",
                        "[DISCOVERY]".yellow()
                    );
                }
            }
        }

        async_exec::spawn_detached(move || {
            let discovery = Discovery::new(discovery_config, state_for_discovery);
            discovery.run(discovery_verbose);
        });
    }

    // Console output
    if !daemon {
        // Log ledger status
        if state.ledger.is_api_mode() {
            println!("  {} API mode - using dashboard API", "[LEDGER]".cyan());
        } else {
            println!(
                "  {} Standalone mode - using local in-memory operations",
                "[LEDGER]".yellow()
            );
        }

        // Log billing status
        if state.is_billing_enabled() {
            println!(
                "  {} Billing enabled (dashboard API authority)",
                "[BILLING]".cyan()
            );
        } else {
            println!(
                "  {} Billing disabled — all executions are free (no API credentials)",
                "[BILLING]".yellow()
            );
        }

        // Log P2P status
        if state.peer_manager.is_enabled() {
            println!(
                "  {} P2P credit operations enabled ({} peers)",
                "[P2P]".cyan(),
                state.peer_manager.peer_count(),
            );
        }

        println!("  {} Listening on {}", "[BROKER]".green().bold(), addr);

        if verbose {
            println!();
            println!("  {}", "Live Transactions:".bold().underline());
            println!("  {}", "─".repeat(80));
            println!(
                "  {}    {:>4}  {:>12} {:>8}  {:>10} {:>10} {:>8}  {}",
                "TIME".dimmed(),
                "#".dimmed(),
                "USER".dimmed(),
                "ACTION".dimmed(),
                "COST".dimmed(),
                "BALANCE".dimmed(),
                "LATENCY".dimmed(),
                "WORKER".dimmed(),
            );
            println!("  {}", "─".repeat(80));
        }
    }

    // Serve on the axum/tokio runtime. Each request runs the unchanged
    // handle() on a bounded spawn_blocking pool, so long /execute calls never
    // block the accept loop or explode into unbounded threads.
    //
    // `serve_axum` returns once `shutdown_signal` observes SIGTERM/SIGINT and
    // axum finishes draining in-flight connections. At that point `running`
    // is already false, but the background threads may still be mid-sleep
    // before they notice — so join them here rather than letting `main()`
    // exit out from under them and lose buffered transactions.
    //
    // `zc-flush` is joined FIRST and it is the one that matters: it owns the
    // graceful-shutdown flush. When that flush lived on `zc-cleanup` (#341) a
    // wedged cleanup thread meant the drain never happened, so a restart
    // intended to recover the backlog destroyed it instead.
    let serve_result = serve_axum(state, bind_host, bind_port, verbose, running);
    let _ = flush_handle.join();
    let _ = cleanup_handle.join();
    serve_result
}

#[cfg(test)]
mod dispatch_deadline_tests {
    use super::peer_dispatch_deadline;
    use std::time::Duration;

    #[test]
    fn unset_timeout_caps_at_30s_not_the_peer_clients_310s_default() {
        // offer.timeout_secs == 0 must NOT inherit PeerClient::offer_task's 310s
        // fallback — a slow/unresponsive peer would otherwise hang the request
        // for >5 minutes (rx.recv had no deadline).
        assert_eq!(peer_dispatch_deadline(0.0), Duration::from_secs(30));
    }

    #[test]
    fn explicit_timeout_is_honored_with_slack() {
        // A real long task keeps its budget plus slack for transport overhead.
        assert_eq!(peer_dispatch_deadline(5.0), Duration::from_secs_f64(17.0));
    }

    /// Regression test for the step-1.5 pre-selected-peer bug: a reachable
    /// but hung peer must not be able to stall the request out to
    /// `PeerClient::offer_task`'s own ~310s internal timeout (unset
    /// `timeout_secs` -> 310s fallback). The fix bounds the wait on the
    /// worker-thread channel with `peer_dispatch_deadline`, exactly
    /// mirroring the pattern this test exercises directly against a stub
    /// peer that accepts the TCP connection and then never responds.
    #[test]
    fn preselected_offer_wait_is_bounded_by_dispatch_deadline_not_offer_tasks_310s() {
        use crate::broker::peer::PeerClient;
        use crate::broker::task_board;
        use std::io::Read;
        use std::net::TcpListener;

        // A raw TCP stub: accept the connection (so PeerClient's fast
        // connect-timeout doesn't fire) but never write a response, so
        // PeerClient::offer_task would otherwise block on its own
        // timeout_global (310s for an unset offer.timeout_secs).
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut buf = [0u8; 1024];
                // Read the request but send nothing back; hold the
                // connection open until the test process exits.
                let _ = stream.read(&mut buf);
                std::thread::sleep(Duration::from_secs(600));
            }
        });

        let client = PeerClient::new(format!("http://{addr}"), "test-key".to_string());
        let offer: task_board::TaskOffer = serde_json::from_str(
            r#"{"task_id":"t-bound","payload_b64":"","max_price_per_hour":100.0,"estimated_duration_secs":1.0,"timeout_secs":0.0,"requester_user_id":"u","source_broker":"n"}"#,
        )
        .unwrap();

        // Mirror the exact step-1.5 pattern: offer on a worker thread,
        // recv_timeout bounded by peer_dispatch_deadline.
        let (tx, rx) = std::sync::mpsc::channel::<Result<task_board::TaskResult, String>>();
        let offer_c = offer.clone();
        std::thread::spawn(move || {
            let _ = tx.send(client.offer_task(&offer_c));
        });

        let deadline = peer_dispatch_deadline(offer.timeout_secs);
        assert_eq!(
            deadline,
            Duration::from_secs(30),
            "sanity: unset timeout_secs -> 30s bound"
        );

        let start = std::time::Instant::now();
        let outcome = rx.recv_timeout(deadline);
        let elapsed = start.elapsed();

        assert!(
            outcome.is_err(),
            "stub peer never responds, so the channel recv must itself time out"
        );
        // The wait must fall through at ~peer_dispatch_deadline (30s), with
        // generous scheduling slack — and, critically, nowhere close to
        // offer_task's own ~310s internal timeout, which was the bug.
        assert!(
            elapsed < Duration::from_secs(60),
            "pre-selected offer wait was not bounded by peer_dispatch_deadline: took {elapsed:?}"
        );
    }

    /// Regression test for the step-1.5-timeout-then-step-2-rebroadcast bug
    /// (task 5, Critical finding): when the pre-selected peer's direct offer
    /// times out or errors, it may STILL be executing the task (offers are
    /// one-phase — `PeerClient::offer_task` only returns on completion). The
    /// fix excludes that abandoned peer from step 2's broadcast set so the
    /// same task_id is never re-offered to a peer that may still be running
    /// it.
    #[test]
    fn broadcast_targets_excludes_abandoned_preferred_peer() {
        use super::broadcast_targets;

        let peers = vec![
            "http://peer-a".to_string(),
            "http://peer-b".to_string(),
            "http://peer-c".to_string(),
        ];

        // No abandoned peer (step 1.5 succeeded, or preferred_peer was
        // None) -> broadcast set is unchanged.
        assert_eq!(broadcast_targets(&peers, None), peers);

        // Step 1.5 timed out/errored on peer-b -> it must be excluded from
        // the fallback broadcast, but the other peers are untouched.
        let targets = broadcast_targets(&peers, Some("http://peer-b"));
        assert_eq!(
            targets,
            vec!["http://peer-a".to_string(), "http://peer-c".to_string()]
        );
        assert!(
            !targets.contains(&"http://peer-b".to_string()),
            "abandoned preferred peer must not be re-offered the same task_id"
        );

        // Excluding a peer not in the set is a no-op (defensive).
        assert_eq!(broadcast_targets(&peers, Some("http://peer-z")), peers);
    }

    fn peers() -> Vec<String> {
        vec![
            "http://peer-a".to_string(),
            "http://peer-b".to_string(),
            "http://peer-c".to_string(),
        ]
    }

    /// Unpinned dispatch is unchanged: every peer, first accept wins.
    #[test]
    fn an_unpinned_offer_still_goes_to_every_peer() {
        use super::dispatch_targets;
        assert_eq!(
            dispatch_targets(&peers(), None, |_| unreachable!("no pin to resolve")),
            Some(peers())
        );
    }

    /// The bug: a pinned offer went into the same first-accept-wins race as
    /// an unpinned one, so naming a node made the work run on a random other
    /// node. It must reach the pinned peer and nobody else.
    #[test]
    fn a_pinned_offer_goes_only_to_the_pinned_peer() {
        use super::dispatch_targets;
        let set = dispatch_targets(&peers(), Some("zc://node-fd29ea8fe9ffa2e0"), |fp| {
            (fp == "zc://node-fd29ea8fe9ffa2e0").then(|| "http://peer-b".to_string())
        });
        assert_eq!(set, Some(vec!["http://peer-b".to_string()]));
    }

    /// A pin no peer answers for is a routing failure, not an invitation to
    /// run the job somewhere else. Returning the full peer set here is what
    /// made a pin to a nonexistent node execute happily on cloudcompute.
    #[test]
    fn a_pin_no_peer_answers_for_dispatches_nowhere() {
        use super::dispatch_targets;
        assert_eq!(
            dispatch_targets(&peers(), Some("zc://node-deadbeefdeadbeef"), |_| None),
            None
        );
    }

    /// An older peer sends the field absent, which serde fills with "". That
    /// is "no pin", not "pinned to nothing".
    #[test]
    fn an_absent_or_blank_target_node_is_not_a_pin() {
        use super::offer_pin;
        let mut o: crate::broker::task_board::TaskOffer = serde_json::from_str(
            r#"{"task_id":"t","payload_b64":"","max_price_per_hour":1.0,"estimated_duration_secs":1.0,"timeout_secs":0.0,"requester_user_id":"u","source_broker":"n"}"#,
        )
        .unwrap();
        assert_eq!(o.target_node, "");
        assert_eq!(offer_pin(&o), None);
        o.target_node = "   ".to_string();
        assert_eq!(offer_pin(&o), None);
        o.target_node = "zc://node-fd29ea8fe9ffa2e0".to_string();
        assert_eq!(offer_pin(&o), Some("zc://node-fd29ea8fe9ffa2e0"));
    }
}

#[cfg(test)]
mod runtime_tests {
    use super::build_broker_runtime;

    #[test]
    fn runtime_honors_explicit_worker_thread_count() {
        let rt = build_broker_runtime(Some(2)).unwrap();
        assert_eq!(rt.metrics().num_workers(), 2);
    }

    #[test]
    fn runtime_defaults_to_multi_thread_when_unset() {
        // Production passes None → tokio's default (num_cpus) multi-thread pool,
        // unchanged from the benchmarked configuration.
        let rt = build_broker_runtime(None).unwrap();
        assert!(rt.metrics().num_workers() >= 1);
    }

    #[test]
    fn runtime_zero_workers_is_current_thread() {
        // Some(0) → current-thread runtime: no persistent worker threads, so the
        // many brokers a parallel `cargo test` leaks don't oversubscribe the CPU.
        // A current-thread runtime reports exactly one "worker" (itself).
        let rt = build_broker_runtime(Some(0)).unwrap();
        assert_eq!(rt.metrics().num_workers(), 1);
    }
}

#[cfg(test)]
mod panic_fix_tests {
    use super::header_or;
    use super::{check_node_sig, worker_to_info, BrokerRequest};

    #[test]
    fn worker_to_info_client_hides_ip_peer_keeps_it() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::worker::{Worker, WorkerRegistry};
        let reg = WorkerRegistry::new();
        let key = NodeKey::generate();
        let mut w = Worker::new(
            "id1".into(),
            "worker-xyz".into(),
            "http://10.13.13.21:3960".into(),
            "zakuro".into(),
        );
        w.source_node = Some("node-i9".into());
        w.node_fp = "abc123".into();
        w.slot = "3960".into();
        // client-facing: key-derived zc:// uri, node handle, label, no IP anywhere in the JSON
        let ci = worker_to_info(&w, &reg, &key, true, false);
        assert_eq!(ci.uri, "zc://worker-abc123-3960");
        assert_eq!(ci.node.as_deref(), Some("zc://node-i9"));
        assert_eq!(ci.label.as_deref(), Some("worker-xyz"));
        let cj = serde_json::to_string(&ci).unwrap();
        assert!(!cj.contains("10.13.13.") && !cj.contains(":3960") && !cj.contains("http://"));
        // peer-facing: real uri retained
        let pi = worker_to_info(&w, &reg, &key, false, false);
        assert_eq!(pi.uri, "http://10.13.13.21:3960");
    }

    #[test]
    fn worker_to_info_carries_provider_fields_for_peers() {
        // zc#172: /peer/workers must carry the provider fields, or a peer
        // broker rebuilds this worker without them and its model index never
        // learns about the provider.
        use crate::broker::node_identity::NodeKey;
        use crate::broker::worker::{ProviderType, Worker, WorkerRegistry};
        let reg = WorkerRegistry::new();
        let key = NodeKey::generate();
        let mut w = Worker::new(
            "id3".into(),
            "zc-serve-116c1f8b".into(),
            "http://192.168.0.167:8600".into(),
            "llm".into(),
        );
        w.provider_type = ProviderType::Specialized;
        w.served_models = vec!["116c1f8b-7a22-452a-867c-f8b20afdb355".into()];
        w.price_per_mtok = 1.5;
        let pi = worker_to_info(&w, &reg, &key, false, false);
        assert_eq!(pi.provider_type, ProviderType::Specialized);
        assert_eq!(pi.served_models, w.served_models);
        assert_eq!(pi.price_per_mtok, 1.5);
        // and they survive serialization in the lowercase wire form
        let j = serde_json::to_value(&pi).unwrap();
        assert_eq!(j["provider_type"], "specialized");
        assert_eq!(
            j["served_models"][0],
            "116c1f8b-7a22-452a-867c-f8b20afdb355"
        );
    }

    #[test]
    fn no_client_surface_emits_ip() {
        // Render a full /workers client payload (WorkerListResponse, the actual
        // GET /workers response body) for a worker whose internal uri carries a
        // mesh IP, and confirm the IP never crosses the client boundary.
        use crate::broker::node_identity::NodeKey;
        use crate::broker::worker::{Worker, WorkerRegistry};
        let reg = WorkerRegistry::new();
        let key = NodeKey::generate();
        let mut w = Worker::new(
            "id2".into(),
            "worker-abc".into(),
            "http://10.13.13.5:3960".into(),
            "zakuro".into(),
        );
        w.node_fp = key.fingerprint();
        w.slot = "3960".into();
        let ci = worker_to_info(&w, &reg, &key, true, false);
        let body = serde_json::to_string(&super::WorkerListResponse {
            total: 1,
            workers: vec![ci],
        })
        .unwrap();
        assert!(!body.contains("10.13.13."));
        assert!(body.contains("zc://worker-"));
    }

    #[test]
    fn client_response_uses_key_derived_node_uri() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::worker::{Worker, WorkerRegistry};
        let key = NodeKey::generate();
        let handle = super::node_handle_for(&key, Some("lxd"));
        assert_eq!(handle, key.node_uri());
        assert!(handle.starts_with("zc://node-"));
        assert!(!handle.contains("lxd")); // hostname is not the identity

        // Also verify it flows through worker_to_info for a local worker (no source_node).
        let reg = WorkerRegistry::new();
        let w = Worker::new(
            "id2".into(),
            "local-worker".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        let ci = worker_to_info(&w, &reg, &key, true, false);
        assert_eq!(ci.node.as_deref(), Some(key.node_uri().as_str()));
    }

    /// The whole point: an unmeasured worker's estimate must not read as a
    /// confident zero. When `include_estimate` is requested, the group is
    /// present but its median/spread are `None`, not `Some(0.0)`.
    #[test]
    fn worker_to_info_never_measured_is_none_not_zero() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::worker::{Worker, WorkerRegistry};
        let reg = WorkerRegistry::new();
        let key = NodeKey::generate();
        let w = Worker::new(
            "id-unmeasured".into(),
            "worker-fresh".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        let info = worker_to_info(&w, &reg, &key, true, true);
        let est = info.estimate.expect("estimate requested, must be present");
        assert_eq!(est.observations, 0.0);
        assert_eq!(est.median_service_ms, None);
        assert_eq!(est.log_sd, None);

        // In JSON, that must be a literal `null`, not `0` or absent — the
        // whole ask is that "never measured" is visibly distinct.
        let j = serde_json::to_value(&info).unwrap();
        assert!(j["estimate"]["median_service_ms"].is_null());
        assert_eq!(j["estimate"]["observations"], 0.0);
    }

    /// A worker with real observations reports its posterior median, spread
    /// and observation count through the same group.
    #[test]
    fn worker_to_info_reports_the_posterior_once_measured() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::worker::{Worker, WorkerRegistry};
        let reg = WorkerRegistry::new();
        let key = NodeKey::generate();
        let mut w = Worker::new(
            "id-measured".into(),
            "worker-warm".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        for ms in [10.0, 20.0, 40.0] {
            w.stats.observe(ms, true);
        }
        let info = worker_to_info(&w, &reg, &key, true, true);
        let est = info.estimate.expect("estimate requested");
        assert_eq!(est.observations, 3.0);
        let median = est.median_service_ms.expect("three observations");
        assert!((median - 20.0).abs() < 1e-9, "got {median}");
        assert!(est.log_sd.is_some(), "spread known once n >= 2");
    }

    /// The estimate costs nothing unless asked for: by default (as every
    /// existing caller of `worker_to_info` does) the group is omitted from
    /// the JSON entirely, not merely null, so a plain `/workers` or
    /// `/peer/workers` response is the same size it always was.
    #[test]
    fn worker_to_info_omits_estimate_unless_requested() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::worker::{Worker, WorkerRegistry};
        let reg = WorkerRegistry::new();
        let key = NodeKey::generate();
        let mut w = Worker::new(
            "id-default".into(),
            "worker-default".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        w.stats.observe(5.0, true);
        let info = worker_to_info(&w, &reg, &key, true, false);
        assert!(info.estimate.is_none());
        let j = serde_json::to_value(&info).unwrap();
        assert!(
            j.get("estimate").is_none(),
            "the field itself is absent, not null: {j}"
        );
    }

    #[test]
    fn capped_charge_never_exceeds_reserved() {
        use super::capped_charge;
        assert!((capped_charge(0.05, 0.02) - 0.02).abs() < 1e-9); // over → capped
        assert!((capped_charge(0.01, 0.02) - 0.01).abs() < 1e-9); // under → unchanged
        assert_eq!(capped_charge(f64::NAN, 0.02), 0.0); // non-finite → 0
        assert_eq!(capped_charge(-1.0, 0.02), 0.0); // negative → 0
    }

    #[test]
    fn header_or_accepts_valid_value() {
        let (k, v) = header_or("X-Zakuro-Worker", "node-01");
        assert_eq!(k, "X-Zakuro-Worker");
        assert_eq!(v, "node-01");
    }

    #[test]
    fn check_node_sig_accepts_rostered_signer_rejects_others() {
        use crate::broker::node_identity::{NodeKey, ReplayGuard};
        use dashmap::DashMap;
        use tiny_http::Method;

        let key = NodeKey::generate();
        let path = "/peer/tasks/offer";
        let body = br#"{"fn":"greet"}"#.to_vec();
        let hdrs = key.sign_headers("POST", path, &body);

        let build = |headers: Vec<(String, String)>, body: Vec<u8>| BrokerRequest {
            method: Method::Post,
            path: path.to_string(),
            query: String::new(),
            headers,
            body,
            peer_addr: None,
        };

        let roster = DashMap::new();
        roster.insert(key.public_b64(), false); // authorized
        let guard = ReplayGuard::new();
        let now = crate::broker::node_identity::now_secs();

        // valid, rostered → Ok(signer)
        let req = build(hdrs.clone(), body.clone());
        assert_eq!(
            check_node_sig(&roster, &guard, &req, now).unwrap(),
            key.public_b64()
        );

        // revoked → rejected
        roster.insert(key.public_b64(), true);
        let g2 = ReplayGuard::new();
        let req2 = build(hdrs.clone(), body.clone());
        assert!(check_node_sig(&roster, &g2, &req2, now).is_err());
        roster.insert(key.public_b64(), false);

        // tampered body → bad signature
        let g3 = ReplayGuard::new();
        let req3 = build(hdrs.clone(), b"{}".to_vec());
        assert!(check_node_sig(&roster, &g3, &req3, now).is_err());

        // unsigned → rejected
        let g4 = ReplayGuard::new();
        let req4 = build(vec![], body);
        assert!(check_node_sig(&roster, &g4, &req4, now).is_err());
    }

    #[test]
    fn peer_peers_requires_valid_node_signature_and_signs_response() {
        use crate::broker::node_identity::{verify_sig, NodeKey};
        use crate::broker::BrokerState;
        use std::sync::Arc;
        use tiny_http::Method;

        let state = BrokerState::new();
        let signer = NodeKey::generate();
        state.node_roster.insert(signer.public_b64(), false); // authorized
        let state = Arc::new(state);

        // Unsigned request → 401, never served.
        let unsigned = BrokerRequest {
            method: Method::Get,
            path: "/peer/peers".to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: None,
        };
        let resp = super::handle(Arc::clone(&state), &unsigned, false);
        assert_eq!(resp.status, 401);

        // Signed by a rostered node → 200, and the response itself carries a
        // valid X-Node-Id/X-Node-Sig over the exact body bytes.
        let hdrs = signer.sign_headers("GET", "/peer/peers", b"");
        let signed = BrokerRequest {
            method: Method::Get,
            path: "/peer/peers".to_string(),
            query: String::new(),
            headers: hdrs,
            body: vec![],
            peer_addr: None,
        };
        let resp = super::handle(Arc::clone(&state), &signed, false);
        assert_eq!(resp.status, 200);

        let get = |name: &str| -> Option<String> {
            resp.headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case(name))
                .map(|(_, v)| v.clone())
        };
        let node_id = get("X-Node-Id").expect("response signed with X-Node-Id");
        let sig = get("X-Node-Sig").expect("response signed with X-Node-Sig");
        assert_eq!(node_id, state.node_key.public_b64());
        assert!(verify_sig(&node_id, &resp.body, &sig));

        let parsed: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert!(parsed["peers"].as_array().is_some());
    }

    #[test]
    fn header_or_does_not_panic_on_peer_supplied_garbage() {
        // A peer could return a worker name with non-ASCII bytes (>127), which
        // HTTP header validation rejects — the old `.unwrap()` panicked here.
        // header_or must NOT panic; it falls back to a marker header.
        let (k, v) = header_or("X-Zakuro-Worker", "wörker\u{00ff}");
        assert_eq!(k, "X-Zakuro-Invalid");
        assert_eq!(v, "1");
    }

    #[test]
    fn health_endpoint_body_has_no_mesh_ip() {
        // GET /health end-to-end: the client body must report connectivity as
        // a bool only — never the raw mesh IP (10.13.13.x) or a loopback
        // address masquerading as an identity.
        use crate::broker::BrokerState;
        use std::sync::Arc;
        use tiny_http::Method;

        let mut state = BrokerState::new();
        state.own_wireguard_ip = Some("10.13.13.42".to_string());
        let state = Arc::new(state);

        let req = BrokerRequest {
            method: Method::Get,
            path: "/health".to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: None,
        };
        let resp = super::handle(state, &req, false);
        let body = String::from_utf8(resp.body).unwrap();
        assert!(
            !body.contains("10.13.13."),
            "health body leaked mesh IP: {body}"
        );
        assert!(
            !body.contains("127.0.0.1"),
            "health body leaked loopback: {body}"
        );
        assert!(body.contains("wireguard_connected"));
        assert!(!body.contains("\"wireguard_ip\""));
    }

    /// zc#365: `/shadow` serves the adaptive policy's ledger without a key,
    /// so a week of it can be collected from a broker that never logs it.
    #[test]
    fn shadow_ledger_is_served() {
        use crate::broker::BrokerState;
        use std::sync::Arc;
        use tiny_http::Method;

        let state = Arc::new(BrokerState::new());
        let req = BrokerRequest {
            method: Method::Get,
            path: "/shadow".to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: None,
        };
        let resp = super::handle(state, &req, false);
        assert_eq!(resp.status, 200);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(body["schema"], "zc.shadow/1");
        assert_eq!(body["decisions"], 0);
    }

    /// zc#305: `/health` is the surface a scraper can reach without a key, so
    /// it is where the running build has to be disclosed for a fleet to be
    /// reconciled at all.
    #[test]
    fn health_discloses_the_running_build() {
        use crate::broker::BrokerState;
        use std::sync::Arc;
        use tiny_http::Method;

        let state = Arc::new(BrokerState::new());
        let req = BrokerRequest {
            method: Method::Get,
            path: "/health".to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: None,
        };
        let resp = super::handle(state, &req, false);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        let build: crate::build_id::BuildId =
            serde_json::from_value(body["build"].clone()).expect("/health carries a build block");
        assert_eq!(build, *crate::build_id::current());
        assert_eq!(build.version, env!("CARGO_PKG_VERSION"));
        assert_eq!(
            build.binary_sha256.as_ref().map(|h| h.len()),
            Some(64),
            "the binary hash is a full SHA-256, truncated only for display"
        );
    }

    /// Fix E: `/health` must never contradict itself. `wireguard_connected`
    /// and `mesh_tunnel` describe the same fact, so "connected but tunnel
    /// down" is an impossible pair. Before the fix the two were computed from
    /// two different detectors and this state was reachable both in-container
    /// (no `ip` binary) and here (a cached `own_wireguard_ip` that
    /// `mesh_tunnel` never consulted).
    #[test]
    fn health_wireguard_connected_and_mesh_tunnel_never_disagree() {
        use crate::broker::BrokerState;
        use std::sync::Arc;
        use tiny_http::Method;

        let mut state = BrokerState::new();
        state.own_wireguard_ip = Some("10.13.13.42".to_string());
        let state = Arc::new(state);

        let req = BrokerRequest {
            method: Method::Get,
            path: "/health".to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: None,
        };
        let resp = super::handle(state, &req, false);
        let body: serde_json::Value =
            serde_json::from_slice(&resp.body).expect("/health returns JSON");

        let connected = body["wireguard_connected"]
            .as_bool()
            .expect("wireguard_connected is a bool");
        let tunnel = body["mesh_tunnel"]
            .as_str()
            .expect("mesh_tunnel is a string");

        // Shapes are unchanged: bool, and the "up"/"down" enum.
        assert!(tunnel == "up" || tunnel == "down", "mesh_tunnel={tunnel}");
        assert_eq!(
            connected,
            tunnel == "up",
            "/health contradicts itself: wireguard_connected={connected} mesh_tunnel={tunnel}"
        );
    }

    #[test]
    fn stats_worker_and_response_serialization_has_no_mesh_ip() {
        // WorkerStats.uri and StatsResponse.wireguard_ip are the two
        // /stats fields that used to carry the raw mesh IP straight to the
        // client. Assert both are IP-free once redacted the way the /stats
        // handler builds them (key-derived uri; wireguard_ip: None).
        use crate::broker::stats::{StatsCollector, StatsResponse, WorkerStats};

        let ws = WorkerStats {
            id: "id1".into(),
            name: "worker-abc".into(),
            uri: "zc://worker-abc123-3960".into(), // as built via w.zc_uri()
            status: "healthy".into(),
            cpus_available: 1.0,
            memory_available_gib: 1.0,
            gpus_available: 0,
            price_per_hour: 0.0,
            active_requests: 0,
            avg_latency_ms: 0.0,
        };
        let ws_json = serde_json::to_string(&ws).unwrap();
        assert!(!ws_json.contains("10.13.13."));
        assert!(!ws_json.contains("127.0.0.1"));
        assert!(ws_json.contains("zc://worker-"));

        let resp = StatsResponse {
            host: "0.0.0.0".into(),
            port: 8080,
            transactions: vec![],
            task_offers: vec![],
            workers: vec![ws],
            metrics: StatsCollector::new().metrics(0, 0, true, false, None),
            rps_history: vec![],
            wireguard_ip: None,
            wireguard_connected: true,
        };
        let resp_json = serde_json::to_string(&resp).unwrap();
        assert!(
            !resp_json.contains("10.13.13."),
            "stats body leaked mesh IP: {resp_json}"
        );
        assert!(
            !resp_json.contains("127.0.0.1"),
            "stats body leaked loopback: {resp_json}"
        );
    }

    #[test]
    fn mesh_endpoint_is_ip_plus_bound_port() {
        // The advertised port is whatever this broker actually bound, not a
        // hardcoded 9000 -- a user may run a broker anywhere.
        assert_eq!(
            super::mesh_endpoint_for(Some("10.13.13.6".to_string()), 9100).as_deref(),
            Some("10.13.13.6:9100")
        );
        assert_eq!(super::mesh_endpoint_for(None, 9000), None);
    }

    // --- Fix 2: rate-limited "no mesh endpoint" logging ---

    #[test]
    fn mesh_endpoint_log_gate_logs_on_first_absence() {
        let gate = super::MeshEndpointLogGate::new();
        assert_eq!(
            gate.on_tick(false, 1_000),
            super::MeshEndpointLogAction::NoEndpoint
        );
    }

    #[test]
    fn mesh_endpoint_log_gate_suppresses_repeat_within_interval() {
        let gate = super::MeshEndpointLogGate::new();
        assert_eq!(
            gate.on_tick(false, 1_000),
            super::MeshEndpointLogAction::NoEndpoint
        );
        // Still absent 60s later (one more tick) -- must not log again yet.
        assert_eq!(
            gate.on_tick(false, 1_060),
            super::MeshEndpointLogAction::None
        );
    }

    #[test]
    fn mesh_endpoint_log_gate_logs_again_after_interval_elapses() {
        let gate = super::MeshEndpointLogGate::new();
        assert_eq!(
            gate.on_tick(false, 1_000),
            super::MeshEndpointLogAction::NoEndpoint
        );
        // ~30 minutes later, still absent -- loud again.
        assert_eq!(
            gate.on_tick(false, 1_000 + 30 * 60),
            super::MeshEndpointLogAction::NoEndpoint
        );
    }

    #[test]
    fn mesh_endpoint_log_gate_logs_recovery_on_transition_back() {
        let gate = super::MeshEndpointLogGate::new();
        assert_eq!(
            gate.on_tick(false, 1_000),
            super::MeshEndpointLogAction::NoEndpoint
        );
        assert_eq!(
            gate.on_tick(true, 1_005),
            super::MeshEndpointLogAction::Recovered
        );
    }

    #[test]
    fn mesh_endpoint_log_gate_stays_silent_while_connected() {
        // A broker that has always had a mesh endpoint (the common case)
        // must never log anything -- no transition, no periodic reminder.
        let gate = super::MeshEndpointLogGate::new();
        assert_eq!(
            gate.on_tick(true, 1_000),
            super::MeshEndpointLogAction::None
        );
        assert_eq!(
            gate.on_tick(true, 1_000 + 30 * 60),
            super::MeshEndpointLogAction::None
        );
    }

    // --- Fix 4: roster -> peer URL derivation (self-filter + http:// prefix) ---

    /// Project `roster_peer_entries` down to just its URLs, the shape the
    /// pre-Fix-D assertions were written against.
    fn urls_of(entries: Vec<super::RosterPeer>) -> Vec<String> {
        entries.into_iter().map(|e| e.url).collect()
    }

    /// Fix D: the self-filter must key on IDENTITY, so it still works when
    /// this node's tunnel is down.
    ///
    /// This is the flap case and it is the whole point: `self_endpoint` is
    /// derived from `mesh_ip()`, so it is `None` exactly when the tunnel is
    /// down — while this node's own STALE endpoint is still on the roster,
    /// because registration treats an omitted endpoint as "unchanged". The
    /// address filter is therefore disabled precisely when it has something
    /// to filter, and the broker dials itself.
    #[test]
    fn roster_peer_entries_excludes_self_by_pubkey_when_tunnel_is_down() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let self_key = NodeKey::generate();
        let peer_key = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![
            (self_key.public_b64(), false),
            (peer_key.public_b64(), false),
        ]);
        // This node's own stale endpoint is still advertised on the roster.
        cache.set_endpoints(vec![
            (self_key.public_b64(), "10.13.13.5:9000".to_string()),
            (peer_key.public_b64(), "10.13.13.6:9000".to_string()),
        ]);

        // Tunnel down => self_endpoint is None, so ONLY identity can filter.
        let urls = urls_of(super::roster_peer_entries(
            &cache,
            Some(&self_key.public_b64()),
            None,
        ));

        assert_eq!(
            urls,
            vec!["http://10.13.13.6:9000".to_string()],
            "broker registered itself as a peer while its tunnel was down"
        );
    }

    /// The identity filter must not depend on the roster row's address at all:
    /// even if this node's roster endpoint has been reassigned to a different
    /// address than it last advertised, the row is still self.
    #[test]
    fn roster_peer_entries_excludes_self_even_when_its_address_changed() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let self_key = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![(self_key.public_b64(), false)]);
        cache.set_endpoints(vec![(
            self_key.public_b64(),
            "10.13.13.99:9000".to_string(),
        )]);

        let urls = urls_of(super::roster_peer_entries(
            &cache,
            Some(&self_key.public_b64()),
            Some("10.13.13.5:9000"),
        ));
        assert!(
            urls.is_empty(),
            "self row survived the identity filter: {urls:?}"
        );
    }

    /// A revoked node must stay unaddressable even if it is somehow also this
    /// node's own key — revocation and reachability are the same row.
    #[test]
    fn roster_peer_entries_still_drops_revoked_rows_with_identity_filter_on() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let self_key = NodeKey::generate();
        let revoked = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![
            (self_key.public_b64(), false),
            (revoked.public_b64(), true),
        ]);
        cache.set_endpoints(vec![(revoked.public_b64(), "10.13.13.7:9000".to_string())]);

        assert!(super::roster_peer_entries(&cache, Some(&self_key.public_b64()), None).is_empty());
    }

    /// The fingerprint travelling with the URL is the one Fix C dedups on, so
    /// it must actually match the node's key-derived identity.
    #[test]
    fn roster_peer_entries_carry_the_nodes_fingerprint() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let peer_key = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![(peer_key.public_b64(), false)]);
        cache.set_endpoints(vec![(peer_key.public_b64(), "10.13.13.6:9000".to_string())]);

        let entries = super::roster_peer_entries(&cache, None, None);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].fp, peer_key.fingerprint());
        assert_eq!(entries[0].url, "http://10.13.13.6:9000");
    }

    #[test]
    fn roster_peer_urls_skips_revoked_entries() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let key = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![(key.public_b64(), true)]);
        cache.set_endpoints(vec![(key.public_b64(), "10.13.13.6:9000".to_string())]);

        assert!(super::roster_peer_entries(&cache, None, None).is_empty());
    }

    #[test]
    fn roster_peer_urls_excludes_self_endpoint() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let self_key = NodeKey::generate();
        let peer_key = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![
            (self_key.public_b64(), false),
            (peer_key.public_b64(), false),
        ]);
        cache.set_endpoints(vec![
            (self_key.public_b64(), "10.13.13.5:9000".to_string()),
            (peer_key.public_b64(), "10.13.13.6:9000".to_string()),
        ]);

        let urls = urls_of(super::roster_peer_entries(
            &cache,
            None,
            Some("10.13.13.5:9000"),
        ));
        assert_eq!(urls, vec!["http://10.13.13.6:9000".to_string()]);
    }

    #[test]
    fn roster_peer_urls_prefixes_bare_addresses_with_http() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let key = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![(key.public_b64(), false)]);
        cache.set_endpoints(vec![(key.public_b64(), "10.13.13.6:9000".to_string())]);

        assert_eq!(
            urls_of(super::roster_peer_entries(&cache, None, None)),
            vec!["http://10.13.13.6:9000".to_string()]
        );
    }

    #[test]
    fn roster_peer_urls_empty_roster_yields_empty_vec() {
        use crate::broker::roster_cache::RosterCache;

        let cache = RosterCache::from_entries(vec![]);
        assert!(super::roster_peer_entries(&cache, None, None).is_empty());
    }

    #[test]
    fn roster_peer_urls_skips_empty_and_whitespace_only_endpoints() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::roster_cache::RosterCache;

        let blank_key = NodeKey::generate();
        let good_key = NodeKey::generate();
        let mut cache = RosterCache::from_entries(vec![
            (blank_key.public_b64(), false),
            (good_key.public_b64(), false),
        ]);
        cache.set_endpoints(vec![
            (blank_key.public_b64(), "   ".to_string()),
            (good_key.public_b64(), "10.13.13.6:9000".to_string()),
        ]);

        assert_eq!(
            urls_of(super::roster_peer_entries(&cache, None, None)),
            vec!["http://10.13.13.6:9000".to_string()]
        );
    }

    // --- A node that joins the mesh after this broker started ----------------

    /// Drive one node-sync round's roster merge the way the tick loop does:
    /// the hub's raw roster body -> `parse_roster`/`parse_endpoints` ->
    /// `RosterCache` -> `roster_peer_entries` -> `merge_roster_peers`. Only the
    /// HTTP round-trip is skipped, so this exercises the production chain
    /// rather than a re-implementation of it.
    fn node_sync_round(pm: &crate::broker::peer::PeerManager, roster_body: &str) -> Vec<String> {
        use crate::broker::node_sync::{parse_endpoints, parse_roster};
        use crate::broker::roster_cache::RosterCache;

        let mut cache = RosterCache::from_entries(parse_roster(roster_body));
        cache.set_endpoints(parse_endpoints(roster_body));
        let roster_peers = super::roster_peer_entries(&cache, None, None);
        super::merge_roster_peers(pm, &roster_peers)
    }

    /// THE question this whole path exists to answer: a broker that started
    /// with an empty roster must start routing work to a node that advertises
    /// its mesh endpoint later, without either side restarting.
    ///
    /// "Routable" is asserted by IDENTITY, not just by URL presence, because
    /// registering the address alone is not enough to use a peer: `/brokers`
    /// drops a peer whose fingerprint is unresolved, and the executor-
    /// settlement lookup (`get_url_for_fingerprint`) resolves nothing for it.
    /// Before the roster row's identity was seeded here, that fingerprint
    /// arrived only from a signed `/peer/health` probe — so on a broker whose
    /// probes fail (tunnel down, sidecar not yet up) the new node stayed
    /// invisible for as long as the process lived, restart included, since a
    /// `peers.json` written with a blank fingerprint reloads just as blank.
    #[test]
    fn a_node_that_joins_the_roster_later_becomes_routable_without_a_restart() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::peer::PeerManager;

        let joiner = NodeKey::generate();
        let pm = PeerManager::new(Some("10.13.13.5"), &[], 9000, "k".into(), true);

        // This broker starts up against a roster with no endpoints at all.
        assert!(node_sync_round(&pm, "[]").is_empty());
        assert_eq!(pm.peer_count(), 0);

        // The new node registers its mesh endpoint with the hub; the next
        // node-sync round sees it. No restart, no probe.
        let body = format!(
            r#"[{{"node_pubkey":"{}","revoked":false,"mesh_endpoint":"10.13.13.35:9000"}}]"#,
            joiner.public_b64()
        );
        assert!(node_sync_round(&pm, &body).is_empty());

        let url = "http://10.13.13.35:9000".to_string();
        assert_eq!(pm.peer_urls(), vec![url.clone()], "peer was never dialed");
        assert!(pm.is_roster_derived(&url), "lost roster provenance");
        assert_eq!(
            pm.get_url_for_fingerprint(&joiner.fingerprint()),
            Some(url),
            "the new node is registered but not addressable by identity: \
             /brokers omits it and executor settlement cannot resolve it"
        );
    }

    /// The seeded identity is the roster's claim about who SHOULD answer at an
    /// address; a probe reports who DOES. If they ever disagree the probe must
    /// win, or a stale roster row could redirect an executor payout.
    #[test]
    fn a_probed_identity_is_never_overwritten_by_the_roster() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::peer::PeerManager;

        let rostered = NodeKey::generate();
        let url = "http://10.13.13.35:9000";
        let probed_fp = "aaaaaaaaaaaaaaaa";

        let pm = PeerManager::new(Some("10.13.13.5"), &[], 9000, "k".into(), true);
        pm.register_roster_peer(url.to_string());
        pm.set_peer_fingerprint(url, probed_fp);

        let body = format!(
            r#"[{{"node_pubkey":"{}","revoked":false,"mesh_endpoint":"10.13.13.35:9000"}}]"#,
            rostered.public_b64()
        );
        node_sync_round(&pm, &body);

        assert_eq!(
            pm.peer_fingerprint(url).as_deref(),
            Some(format!("zc://node-{probed_fp}").as_str()),
            "the roster overwrote an identity a live probe had observed"
        );
    }

    /// Seeding identity must not imply reachability: an address on the roster
    /// is not evidence that anything answers there, and marking such a peer
    /// reachable would offer it work that can only fail.
    #[test]
    fn a_seeded_roster_peer_is_not_reported_reachable() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::peer::PeerManager;

        let joiner = NodeKey::generate();
        let pm = PeerManager::new(Some("10.13.13.5"), &[], 9000, "k".into(), true);
        let body = format!(
            r#"[{{"node_pubkey":"{}","revoked":false,"mesh_endpoint":"10.13.13.35:9000"}}]"#,
            joiner.public_b64()
        );
        node_sync_round(&pm, &body);

        let reachable = pm
            .get_client("http://10.13.13.35:9000")
            .map(|c| c.is_reachable())
            .unwrap_or(false);
        assert!(!reachable, "an unprobed roster peer was marked reachable");
    }

    /// The merge still evicts and still protects `ZAKURO_PEERS`: a node that
    /// drops off the roster is dropped, a configured peer never is.
    #[test]
    fn merge_evicts_departed_roster_peers_and_spares_configured_ones() {
        use crate::broker::node_identity::NodeKey;
        use crate::broker::peer::PeerManager;

        let joiner = NodeKey::generate();
        let cfg = "http://zc-broker-1:9000".to_string();
        let pm = PeerManager::new(
            Some("10.13.13.5"),
            std::slice::from_ref(&cfg),
            9000,
            "k".into(),
            true,
        );

        let body = format!(
            r#"[{{"node_pubkey":"{}","revoked":false,"mesh_endpoint":"10.13.13.35:9000"}}]"#,
            joiner.public_b64()
        );
        node_sync_round(&pm, &body);
        assert_eq!(pm.peer_count(), 2);

        // The node leaves the roster.
        let evicted = node_sync_round(&pm, "[]");

        assert_eq!(evicted, vec!["http://10.13.13.35:9000".to_string()]);
        assert_eq!(pm.peer_urls(), vec![cfg], "evicted a ZAKURO_PEERS peer");
    }
}

#[cfg(test)]
mod two_phase_tests {
    use super::{
        cancel_offer, earn_refund_amount, offer_commission_c, reserve_offer, split_commission,
        sweep_expired_offers, take_committed, voucher_commission_valid,
    };
    use crate::broker::{task_board, BrokerState, PendingOffer};

    fn mk_offer(task_id: &str) -> task_board::TaskOffer {
        serde_json::from_str(&format!(
            r#"{{"task_id":"{}","payload_b64":"","max_price_per_hour":100.0,"estimated_duration_secs":1.0,"timeout_secs":10.0,"requester_user_id":"u","source_broker":"n"}}"#,
            task_id
        )).unwrap()
    }

    #[test]
    fn split_commission_ten_percent_exact() {
        let (payout, commission) = split_commission(100.0, 0.1);
        assert_eq!(commission, 10.0);
        assert_eq!(payout, 90.0);
        // No leak: the two legs sum back to gross exactly.
        assert_eq!(payout + commission, 100.0);
    }

    #[test]
    fn split_commission_min_charge_no_leak() {
        let gross = 0.001;
        let (payout, commission) = split_commission(gross, 0.1);
        // The exact-subtraction split must reconstruct gross to the last bit,
        // even when gross*c is not representable.
        assert_eq!(payout + commission, gross);
    }

    #[test]
    fn split_commission_zero_is_identity() {
        let (payout, commission) = split_commission(42.5, 0.0);
        assert_eq!(payout, 42.5);
        assert_eq!(commission, 0.0);
    }

    /// Conservation invariant of remote-dispatch settlement: for ANY cost and
    /// commission rate, executor earn + platform commission == the requester's
    /// charge (`cost`). This models both settlement branches in
    /// `dispatch_to_peers`: commissioned (payout,commission)=split_commission,
    /// and non-commissioned (earn=cost, commission=0). Guards against the
    /// wall-clock-duration earn regression that minted credits under load.
    #[test]
    fn settlement_conserves_for_all_commission_rates() {
        for &cost in &[0.001_f64, 1.0, 0.036668, 100.0, 0.0] {
            for &c in &[0.0_f64, 0.1, 0.5, 0.9, 0.999] {
                let (earn, commission) = if c > 0.0 {
                    split_commission(cost, c)
                } else {
                    (cost, 0.0)
                };
                assert_eq!(
                    earn + commission,
                    cost,
                    "conservation broken: cost={cost} c={c} earn={earn} commission={commission}"
                );
            }
        }
    }

    /// `settle_executor_payout` (used by BOTH the offer path and the
    /// direct-forward path, universally) is a thin wrapper around
    /// `split_commission` — this is the payout+commission==cost invariant it
    /// relies on, exercised directly at the exact rates named in the fix spec.
    #[test]
    fn settle_payout_conserves_at_named_commission_rates() {
        for &cost in &[0.001_f64, 1.0, 100.0] {
            for &c in &[0.0_f64, 0.1, 0.5] {
                let (payout, commission) = split_commission(cost, c);
                assert_eq!(payout + commission, cost, "cost={cost} c={c}");
                if c == 0.0 {
                    assert_eq!(commission, 0.0);
                    assert_eq!(payout, cost);
                } else {
                    assert!(commission > 0.0, "commission must be > 0 for c={c}");
                }
            }
        }
    }

    /// Money-critical chaos-found bug fix: when the executor's broker can't
    /// be paid (restarted between job completion and the earn RPC, or the
    /// peer is unresolvable), `settle_executor_payout` must refund the
    /// requester the `payout` leg instead of silently dropping it — otherwise
    /// requester -cost, executor +0, platform +commission leaks `payout`
    /// credits out of the system. This exercises the full conservation
    /// invariant, both on earn-success and earn-fail, at the named
    /// commission rates from the fix spec.
    #[test]
    fn earn_refund_conserves_on_success_and_failure() {
        for &cost in &[0.001_f64, 1.0, 0.036668, 100.0] {
            for &c in &[0.0_f64, 0.1, 0.5, 0.9] {
                let (payout, commission) = split_commission(cost, c);

                // earn succeeds: requester -cost, executor +payout, platform
                // +commission.
                let refund_ok = earn_refund_amount(payout, true);
                assert_eq!(refund_ok, 0.0);
                let requester_net_ok = -cost + refund_ok;
                let executor_delta_ok = payout;
                let platform_delta_ok = commission;
                let sum_ok = requester_net_ok + executor_delta_ok + platform_delta_ok;
                assert!(
                    sum_ok.abs() < 1e-9,
                    "earn-success conservation broken: cost={cost} c={c} sum={sum_ok}"
                );
                assert!(
                    (requester_net_ok - (-cost)).abs() < 1e-9,
                    "cost={cost} c={c}"
                );

                // earn fails: requester refunded `payout`, netting -commission;
                // executor gets nothing; platform still keeps its commission.
                let refund_fail = earn_refund_amount(payout, false);
                assert_eq!(refund_fail, payout);
                let requester_net_fail = -cost + refund_fail;
                let executor_delta_fail = 0.0;
                let platform_delta_fail = commission;
                let sum_fail = requester_net_fail + executor_delta_fail + platform_delta_fail;
                assert!(
                    sum_fail.abs() < 1e-9,
                    "earn-fail conservation broken: cost={cost} c={c} sum={sum_fail}"
                );
                assert!(
                    (requester_net_fail - (-commission)).abs() < 1e-9,
                    "requester should net exactly -commission when earn fails: cost={cost} c={c}"
                );
            }
        }
    }

    /// `commit_credits` `Authority::Local` None-arm (executor worker IP can't
    /// be resolved to a peer URL — the peer was temporarily evicted from the
    /// registry mid-restart under chaos): the requester was already debited
    /// `actual_cost` via `local_commit`, but NO executor earn, NO platform
    /// credit and NO voucher redeem happen. So the requester must be refunded
    /// the FULL `actual_cost` (not just payout), making them whole. This
    /// documents that net-zero conservation: requester -actual_cost
    /// +actual_cost == 0, executor 0, platform 0.
    #[test]
    fn unresolved_peer_full_refund_makes_requester_whole() {
        for &actual_cost in &[0.001_f64, 1.0, 0.036668, 100.0] {
            // Debit then full refund in the None arm.
            let requester_net = -actual_cost + actual_cost;
            let executor_delta = 0.0;
            let platform_delta = 0.0; // no earn, no commission, no redeem
            let sum = requester_net + executor_delta + platform_delta;
            assert!(
                sum.abs() < 1e-9,
                "unresolved-peer conservation broken: actual_cost={actual_cost} sum={sum}"
            );
            assert!(
                requester_net.abs() < 1e-9,
                "requester must be made whole (net 0): actual_cost={actual_cost}"
            );
        }
    }

    /// Fail-closed gate unit tests: `voucher_commission_valid` is the pure
    /// decision function both `mint_and_verify_remote_voucher` (direct-forward
    /// path) and the offer-path post-execution check consult. A `false` here
    /// must translate to a REJECT (mint-or-reject / logged commission-loss),
    /// never a silent fall-through to uncommissioned settlement.
    ///
    /// Integration gap: the full "mint fails at the network layer → the
    /// request is rejected with a 503" behavior is exercised by
    /// `mint_and_verify_remote_voucher`'s `Result<_, BrokerResponse>` return
    /// and consumed in `execute_prepare`/`dispatch_to_peers` via `return
    /// Prepared::Done(resp)` — that requires a running broker + mocked
    /// dashboard HTTP endpoint to test end-to-end, which the existing
    /// integration harness does not yet stand up for the voucher endpoints.
    /// This unit test covers the decision logic those call sites depend on.
    #[test]
    fn voucher_commission_valid_gate() {
        assert!(voucher_commission_valid(0.1));
        assert!(voucher_commission_valid(0.5));
        assert!(voucher_commission_valid(0.999));
        assert!(
            !voucher_commission_valid(0.0),
            "zero commission fails closed"
        );
        assert!(!voucher_commission_valid(1.0), "out of [0,1) fails closed");
        assert!(!voucher_commission_valid(1.5), "out of range fails closed");
        assert!(!voucher_commission_valid(-0.1), "negative fails closed");
        assert!(!voucher_commission_valid(f64::NAN), "NaN fails closed");
    }

    /// Offer-path (and direct-path) fail-closed reject at the config gate: a
    /// broker with no dashboard api creds configured MUST reject a
    /// voucher-required remote job with a 503 rather than dispatch it
    /// uncommissioned. This reaches the real `mint_and_verify_voucher` short of
    /// any network I/O (the api-creds check is the first gate), so it exercises
    /// the actual reject wiring both paths consume, not just the pure gate.
    #[test]
    fn mint_and_verify_voucher_rejects_without_api_creds() {
        let state = std::sync::Arc::new(BrokerState::new());
        let resp = super::mint_and_verify_voucher(&state, 5.0, None)
            .expect_err("no api creds → fail-closed reject");
        assert_eq!(resp.status, 503, "reject must be a 503");
    }

    /// A cached dashboard pubkey but no api creds still fails closed at the
    /// creds gate — verifies the fail-closed decision does not depend on the
    /// pubkey being absent.
    #[test]
    fn mint_and_verify_voucher_fails_closed_even_with_cached_pubkey() {
        let state = std::sync::Arc::new(BrokerState::new());
        if let Ok(mut g) = state.dash_voucher_pubkey.write() {
            *g = vec![crate::broker::node_identity::NodeKey::generate().public_b64()];
        }
        assert!(
            super::mint_and_verify_voucher(&state, 5.0, None).is_err(),
            "missing api creds must reject regardless of cached pubkey"
        );
    }

    /// Build a validly dashboard-signed voucher with the given `commission_c`,
    /// returning `(signed_json, sig_b64, dash_pubkey_b64)`.
    fn mk_signed_voucher(
        commission_c: f64,
    ) -> (
        String,
        String,
        String,
        crate::broker::node_identity::NodeKey,
    ) {
        use crate::broker::node_identity::NodeKey;
        let dash = NodeKey::generate();
        let signed = format!(
            r#"{{"v":1,"requester_user":"u","budget_credits":1000000.0,"task_nonce":"n","exp":9999999999,"commission_c":{}}}"#,
            commission_c
        );
        let sig = dash.sign(signed.as_bytes());
        let pubkey = dash.public_b64();
        (signed, sig, pubkey, dash)
    }

    #[test]
    fn offer_commission_c_reads_validly_signed_voucher() {
        let (signed, sig, pubkey, _dash) = mk_signed_voucher(0.1);
        let mut offer = mk_offer("t-c");
        offer.voucher_signed_json = signed;
        offer.voucher_sig = sig;
        assert_eq!(offer_commission_c(&offer, Some(&pubkey)), 0.1);
    }

    #[test]
    fn offer_commission_c_defaults_zero_without_voucher() {
        let offer = mk_offer("t-nc");
        assert!(offer.voucher_signed_json.is_empty());
        assert_eq!(offer_commission_c(&offer, Some("irrelevant")), 0.0);
    }

    #[test]
    fn offer_commission_c_parse_failure_falls_back_to_zero() {
        let mut offer = mk_offer("t-bad");
        offer.voucher_signed_json = "{not valid json".to_string();
        offer.voucher_sig = "somesig".to_string();
        // A parse failure must never throw money — fall back to no commission.
        assert_eq!(offer_commission_c(&offer, Some("irrelevant")), 0.0);
    }

    #[test]
    fn offer_commission_c_out_of_range_falls_back_to_zero() {
        let (signed, sig, pubkey, _dash) = mk_signed_voucher(1.0);
        let mut offer = mk_offer("t-oob");
        // commission_c == 1.0 is out of the [0,1) range → treat as no commission,
        // even though the signature is otherwise valid.
        offer.voucher_signed_json = signed;
        offer.voucher_sig = sig;
        assert_eq!(offer_commission_c(&offer, Some(&pubkey)), 0.0);
    }

    // ── FINDING 1 regression coverage: unverified voucher must never be
    // trusted for commission_c ──────────────────────────────────────────

    #[test]
    fn offer_commission_c_zero_when_signature_missing() {
        // A requester-controlled voucher JSON with commission_c stamped high,
        // but NO signature at all — must not be trusted.
        let mut offer = mk_offer("t-nosig");
        offer.voucher_signed_json = r#"{"v":1,"requester_user":"u","budget_credits":5.0,"task_nonce":"n","exp":9999999999,"commission_c":0.5}"#.to_string();
        offer.voucher_sig = String::new();
        assert_eq!(offer_commission_c(&offer, Some("some-pubkey")), 0.0);
    }

    #[test]
    fn offer_commission_c_zero_when_signature_invalid() {
        // Valid JSON shape, but the signature does not verify against the
        // cached dashboard pubkey (e.g. requester forged/self-signed it, or
        // tampered with commission_c after signing) — must fall back to 0.0,
        // not trust the embedded commission_c: 0.5.
        let (signed, _sig, pubkey, _dash) = mk_signed_voucher(0.5);
        let mut offer = mk_offer("t-badsig");
        offer.voucher_signed_json = signed;
        offer.voucher_sig = "not-a-real-signature".to_string();
        assert_eq!(offer_commission_c(&offer, Some(&pubkey)), 0.0);
    }

    #[test]
    fn offer_commission_c_zero_when_signed_by_wrong_key() {
        // Signed correctly, but by a DIFFERENT keypair than the one cached on
        // broker state — e.g. a requester running their own broker with a
        // self-signed "dashboard" voucher. Must not be trusted.
        let (signed, sig, _their_pubkey, _their_dash) = mk_signed_voucher(0.5);
        let (_real_signed, _real_sig, real_pubkey, _real_dash) = mk_signed_voucher(0.1);
        let mut offer = mk_offer("t-wrongkey");
        offer.voucher_signed_json = signed;
        offer.voucher_sig = sig;
        assert_eq!(offer_commission_c(&offer, Some(&real_pubkey)), 0.0);
    }

    #[test]
    fn offer_commission_c_zero_when_no_pubkey_cached() {
        // Broker hasn't synced a dashboard pubkey yet — must not trust any
        // voucher content, even a validly-shaped one.
        let (signed, sig, _pubkey, _dash) = mk_signed_voucher(0.5);
        let mut offer = mk_offer("t-nopubkey");
        offer.voucher_signed_json = signed;
        offer.voucher_sig = sig;
        assert_eq!(offer_commission_c(&offer, None), 0.0);
    }

    #[test]
    fn offer_commission_c_zero_when_tampered_after_signing() {
        // Signature was valid over the ORIGINAL bytes, but the JSON string
        // carried on the wire was mutated afterwards (e.g. commission_c
        // stripped to near-zero) — verify_voucher checks the signature over
        // the *exact bytes supplied*, so a mismatched sig must fail closed.
        let (signed, sig, pubkey, _dash) = mk_signed_voucher(0.5);
        let tampered = signed.replace("0.5", "0.0000001");
        let mut offer = mk_offer("t-tampered");
        offer.voucher_signed_json = tampered;
        offer.voucher_sig = sig;
        assert_eq!(offer_commission_c(&offer, Some(&pubkey)), 0.0);
    }

    #[test]
    fn reserve_offer_rejects_when_no_local_worker() {
        let state = BrokerState::new();
        let r = reserve_offer(&state, &mk_offer("t1"));
        assert!(r.is_err(), "no local worker → TaskReject");
    }

    #[test]
    fn verify_offer_voucher_gate() {
        use crate::broker::node_identity::NodeKey;
        // Serialize test runs that toggle ZAKURO_REQUIRE_VOUCHER (process-global env).
        static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _g = LOCK.lock().unwrap();

        let state = std::sync::Arc::new(BrokerState::new());
        let dash = NodeKey::generate();
        *state.dash_voucher_pubkey.write().unwrap() = vec![dash.public_b64()];

        // A dashboard-signed voucher with a generous budget, exp far in the future.
        let signed = r#"{"v":1,"requester_user":"u","budget_credits":1000000.0,"task_nonce":"n","exp":9999999999}"#;
        let sig = dash.sign(signed.as_bytes());
        let mut offer = task_board::TaskOffer {
            voucher_signed_json: signed.to_string(),
            voucher_sig: sig,
            ..mk_offer("t-v")
        };

        // required OFF → always Ok regardless of voucher
        std::env::remove_var("ZAKURO_REQUIRE_VOUCHER");
        assert!(super::verify_offer_voucher(&state, &offer).is_ok());

        // required ON → valid voucher passes
        std::env::set_var("ZAKURO_REQUIRE_VOUCHER", "1");
        assert!(super::verify_offer_voucher(&state, &offer).is_ok());

        // required ON, missing voucher → error
        let bare = mk_offer("t-bare");
        assert!(super::verify_offer_voucher(&state, &bare).is_err());

        // required ON, tampered budget → signature fails
        offer.voucher_signed_json = offer.voucher_signed_json.replace("1000000.0", "0.0000001");
        assert!(super::verify_offer_voucher(&state, &offer).is_err());

        std::env::remove_var("ZAKURO_REQUIRE_VOUCHER");
    }

    #[test]
    fn take_committed_removes_once() {
        let state = BrokerState::new();
        state.pending_offers.insert(
            "t1".into(),
            PendingOffer {
                offer: mk_offer("t1"),
                worker_id: "w1".into(),
                created: std::time::Instant::now(),
            },
        );
        assert!(take_committed(&state, "t1").is_some());
        assert!(
            take_committed(&state, "t1").is_none(),
            "second commit → None"
        );
    }

    #[test]
    fn cancel_is_idempotent() {
        let state = BrokerState::new();
        state.pending_offers.insert(
            "t1".into(),
            PendingOffer {
                offer: mk_offer("t1"),
                worker_id: "w1".into(),
                created: std::time::Instant::now(),
            },
        );
        cancel_offer(&state, "t1");
        assert!(!state.pending_offers.contains_key("t1"));
        cancel_offer(&state, "t1"); // absent → no panic
        cancel_offer(&state, "never"); // unknown → no panic
    }

    #[test]
    fn sweep_releases_stale_keeps_fresh() {
        let state = BrokerState::new();
        state.pending_offers.insert(
            "t2".into(),
            PendingOffer {
                offer: mk_offer("t2"),
                worker_id: "w".into(),
                created: std::time::Instant::now(),
            },
        );
        sweep_expired_offers(&state, std::time::Duration::from_secs(3600)); // fresh → kept
        assert!(state.pending_offers.contains_key("t2"));
        sweep_expired_offers(&state, std::time::Duration::ZERO); // any positive age → removed
        assert!(!state.pending_offers.contains_key("t2"));
    }
}

#[cfg(test)]
mod forward_async_tests {
    use super::forward_to_worker_async;

    #[tokio::test]
    async fn forward_async_round_trips_status_body_and_headers() {
        // Loopback mock: returns 200, a marker header, and a fixed body.
        let server = std::sync::Arc::new(tiny_http::Server::http("127.0.0.1:0").unwrap());
        let port = server.server_addr().to_ip().unwrap().port();
        std::thread::spawn(move || {
            for req in server.incoming_requests() {
                let r = tiny_http::Response::from_data(b"pong".to_vec())
                    .with_status_code(200)
                    .with_header(tiny_http::Header::from_bytes("X-Zakuro-Worker", "w1").unwrap())
                    .with_header(tiny_http::Header::from_bytes("Connection", "close").unwrap());
                let _ = req.respond(r);
            }
        });
        let client = reqwest::Client::new();
        let uri = format!("http://127.0.0.1:{}/execute", port);
        let reply = forward_to_worker_async(&client, &uri, b"ping".to_vec(), "rid-1", 0.0)
            .await
            .expect("forward ok");
        assert_eq!(reply.status, 200);
        assert_eq!(reply.body, b"pong");
        assert!(reply
            .headers
            .iter()
            .any(|(k, v)| k == "x-zakuro-worker" && v == "w1"));
    }
}

/// #242: a worker forward must be bounded, and a mesh worker must be reached
/// through the sidecar's CONNECT proxy — on a proxy-route host that is the only
/// route to the mesh, and without a timeout an unreachable worker hangs
/// `/execute` for as long as the caller waits.
#[cfg(test)]
mod forward_routing_tests {
    use super::{forward_timeout_secs, forward_to_worker_async_with};
    use std::time::{Duration, Instant};

    #[test]
    fn an_explicit_timeout_keeps_its_five_seconds_of_slack() {
        assert_eq!(forward_timeout_secs(10.0, 60.0), 15.0);
    }

    #[test]
    fn a_caller_that_names_no_timeout_still_gets_one() {
        assert_eq!(forward_timeout_secs(0.0, 60.0), 60.0);
    }

    /// The #242 hang itself: a worker that accepts the connection and never
    /// answers held `/execute` open for as long as the client waited (120 s
    /// measured), because a request naming no timeout was given none.
    #[tokio::test]
    async fn a_forward_without_a_caller_timeout_gives_up_instead_of_hanging() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            // Accept, then hold the connection open without ever responding.
            for stream in listener.incoming() {
                let held = stream.expect("accept");
                std::thread::sleep(Duration::from_secs(30));
                drop(held);
            }
        });

        let client = reqwest::Client::new();
        let uri = format!("http://127.0.0.1:{}/execute", port);
        let started = Instant::now();
        let outcome =
            forward_to_worker_async_with(&client, &uri, b"ping".to_vec(), "rid-242", 0.0, 1.0)
                .await;

        assert!(
            outcome.is_err(),
            "a worker that never answers must fail the forward, not hang it"
        );
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "forward gave up only after {:?}",
            started.elapsed()
        );
    }

    /// On a proxy-route host the sidecar is the only route onto the mesh, so a
    /// forward to a mesh worker has to leave through it (#242).
    #[tokio::test]
    async fn a_mesh_forward_leaves_through_the_sidecar_proxy() {
        use std::io::{BufRead, BufReader, Write};

        let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let proxy_addr = proxy.local_addr().unwrap().to_string();
        let seen = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
        let recorder = seen.clone();
        std::thread::spawn(move || {
            if let Some(Ok(stream)) = proxy.incoming().next() {
                let mut line = String::new();
                let _ = BufReader::new(&stream).read_line(&mut line);
                *recorder.lock().unwrap() = line;
                let mut out = &stream;
                let _ = out.write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n");
            }
        });

        let client = crate::broker::build_forward_client(Some(&proxy_addr));
        let _ = forward_to_worker_async_with(
            &client,
            "http://10.13.13.17:3960/execute",
            b"ping".to_vec(),
            "rid-proxy",
            0.0,
            2.0,
        )
        .await;

        let line = seen.lock().unwrap().clone();
        assert!(
            line.contains("10.13.13.17:3960"),
            "the sidecar proxy never saw the mesh worker; first request line was {line:?}"
        );
    }

    /// The retry path is bounded too. `execute_finish` retries a failed forward
    /// on another worker synchronously, so an unanswering worker there would
    /// hold `/execute` open just as the first forward did (#242).
    #[test]
    fn a_sync_retry_without_a_caller_timeout_gives_up_instead_of_hanging() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let held = stream.expect("accept");
                std::thread::sleep(Duration::from_secs(30));
                drop(held);
            }
        });

        let agent = ureq::Agent::new_with_config(ureq::Agent::config_builder().build());
        let uri = format!("http://127.0.0.1:{}/execute", port);
        let started = Instant::now();
        let outcome =
            super::forward_to_worker_with(&agent, &uri, b"ping", "rid-242-sync", 0.0, 1.0);

        assert!(
            outcome.is_err(),
            "a worker that never answers must fail the retry, not hang it"
        );
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "retry gave up only after {:?}",
            started.elapsed()
        );
    }

    #[test]
    fn mesh_workers_take_the_proxied_client_and_local_workers_the_direct_one() {
        let direct = reqwest::Client::new();
        let mesh = reqwest::Client::new();

        assert!(std::ptr::eq(
            super::pick_forward_client(&direct, Some(&mesh), "http://10.13.13.17:3960/execute"),
            &mesh
        ));
        assert!(std::ptr::eq(
            super::pick_forward_client(&direct, Some(&mesh), "http://127.0.0.1:3960/execute"),
            &direct
        ));
        // No sidecar on this host: every worker is dialed directly.
        assert!(std::ptr::eq(
            super::pick_forward_client(&direct, None, "http://10.13.13.17:3960/execute"),
            &direct
        ));
    }

    /// The sync forward must route the same way as the async one, and -- the
    /// point of the change -- must hand back the SAME long-lived agent every
    /// time. It used to build a throwaway one per forward, and a throwaway
    /// `ureq::Agent` is a throwaway connection pool, so every request to a
    /// peer opened a fresh TCP connection across the mesh.
    #[test]
    fn the_sync_forward_reuses_one_pooled_agent_per_route() {
        let direct = crate::broker::build_forward_agent(None);
        let mesh = crate::broker::build_forward_agent(Some("127.0.0.1:18888"));

        let mesh_uri = "http://10.13.13.17:3960/execute";
        let local_uri = "http://127.0.0.1:3960/execute";

        assert!(std::ptr::eq(
            super::pick_forward_agent(&direct, Some(&mesh), mesh_uri),
            &mesh
        ));
        assert!(std::ptr::eq(
            super::pick_forward_agent(&direct, Some(&mesh), local_uri),
            &direct
        ));
        assert!(std::ptr::eq(
            super::pick_forward_agent(&direct, None, mesh_uri),
            &direct
        ));

        // Same agent across calls: that is what keeps the connection pool.
        assert!(std::ptr::eq(
            super::pick_forward_agent(&direct, Some(&mesh), mesh_uri),
            super::pick_forward_agent(&direct, Some(&mesh), mesh_uri),
        ));
    }
}

/// CHANGE 2 tests: `GET /brokers` — IP-free key-derived broker listing.
#[cfg(test)]
mod brokers_endpoint_tests {
    use super::handle_brokers;
    use crate::broker::node_identity::NodeKey;
    use crate::broker::{BrokerState, PeerManager};
    use std::sync::Arc;

    /// A fake peer broker that answers `/peer/health` with a fixed
    /// key-derived `broker_id`, exactly like a real broker's
    /// `handle_peer_health` now does.
    fn spawn_fake_peer_health(broker_id: &str) -> u16 {
        let server = Arc::new(tiny_http::Server::http("127.0.0.1:0").unwrap());
        let port = server.server_addr().to_ip().unwrap().port();
        let broker_id = broker_id.to_string();
        std::thread::spawn(move || {
            for req in server.incoming_requests() {
                let body = format!(r#"{{"status":"healthy","broker_id":"{}"}}"#, broker_id);
                let resp = tiny_http::Response::from_data(body.into_bytes())
                    .with_status_code(200)
                    .with_header(
                        tiny_http::Header::from_bytes("Content-Type", "application/json").unwrap(),
                    );
                let _ = req.respond(resp);
            }
        });
        port
    }

    fn state_with_peers(peer_urls: &[String]) -> Arc<BrokerState> {
        let mut state = BrokerState::new();
        let key = Arc::new(NodeKey::generate());
        // Use a distinct loopback address for "self" so the hash-ring
        // normalization (which collapses ip:broker_port) doesn't fold a
        // 127.0.0.1-hosted fake peer onto "self" and drop it from the peer set.
        state.peer_manager = PeerManager::new_with_node_key(
            Some("127.0.0.2"),
            peer_urls,
            state.config.port,
            String::new(), // no shared peer_key needed for loopback /peer/health
            true,
            Some(key.clone()),
        );
        state.node_key = key;
        Arc::new(state)
    }

    #[test]
    fn self_id_is_key_derived_and_matches_node_key() {
        let state = state_with_peers(&[]);
        let resp = handle_brokers(&state);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(body["self"], state.node_key.node_uri());
        assert!(body["self"].as_str().unwrap().starts_with("zc://node-"));
        assert!(body["brokers"].as_array().unwrap().is_empty());
    }

    /// zc#305: one call to one broker is meant to reconcile the mesh, so the
    /// listing anchors on this broker's own build.
    #[test]
    fn brokers_listing_carries_this_brokers_own_build() {
        let state = state_with_peers(&[]);
        let resp = handle_brokers(&state);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        let build: crate::build_id::BuildId =
            serde_json::from_value(body["self_build"].clone()).expect("self_build is present");
        assert_eq!(build, *crate::build_id::current());
    }

    /// A peer that has not been adverted since this broker started has no
    /// cached build. It must read as `null` rather than be omitted or, worse,
    /// inherit this broker's own.
    #[test]
    fn a_peer_with_no_cached_advert_reports_a_null_build() {
        let fp_id = "zc://node-deadbeefcafebabe";
        let port = spawn_fake_peer_health(fp_id);
        let peer_url = format!("http://127.0.0.1:{}", port);

        let state = state_with_peers(std::slice::from_ref(&peer_url));
        let resp = handle_brokers(&state);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        let entry = &body["brokers"][0];
        assert_eq!(entry["id"], fp_id);
        assert!(entry["build"].is_null(), "unexpected build: {entry}");
    }

    #[test]
    fn known_peer_fingerprint_appears_as_zc_id_no_ip_leaked() {
        let fp_id = "zc://node-deadbeefcafebabe";
        let port = spawn_fake_peer_health(fp_id);
        let peer_url = format!("http://127.0.0.1:{}", port);

        let state = state_with_peers(std::slice::from_ref(&peer_url));
        let resp = handle_brokers(&state);
        let raw = String::from_utf8(resp.body.clone()).unwrap();

        // No IP-shaped string, and no raw peer_url, anywhere in the body.
        assert!(!raw.contains("127.0.0.1"), "leaked loopback IP: {raw}");
        assert!(!raw.contains(&port.to_string()), "leaked peer port: {raw}");
        assert!(!raw.contains(&peer_url), "leaked raw peer_url: {raw}");
        assert!(!regex_ish_ip_shaped(&raw), "body looks IP-shaped: {raw}");

        let body: serde_json::Value = serde_json::from_str(&raw).unwrap();
        let brokers = body["brokers"].as_array().unwrap();
        assert_eq!(brokers.len(), 1);
        assert_eq!(brokers[0]["id"], fp_id);
        assert_eq!(brokers[0]["reachable"], true);
    }

    /// Fix C, at the display layer: one physical broker must produce exactly
    /// ONE row, even while it is registered under two spellings — its
    /// `ZAKURO_PEERS` name and its roster mesh address. Listing the same
    /// `zc://node-<fp>` twice is precisely what this feature's acceptance
    /// criterion forbids.
    #[test]
    fn one_broker_registered_under_two_spellings_is_listed_once() {
        let fp_id = "zc://node-deadbeefcafebabe";
        // Two live endpoints answering with the SAME key-derived broker_id:
        // the two spellings of one broker.
        let port_a = spawn_fake_peer_health(fp_id);
        let port_b = spawn_fake_peer_health(fp_id);
        let url_a = format!("http://127.0.0.1:{port_a}");
        let url_b = format!("http://127.0.0.1:{port_b}");

        // Register the second spelling directly, the way the node-sync tick
        // adds a roster-derived peer alongside a configured one.
        // (`PeerManager::new` normalizes its argument list onto `ip:broker_port`
        // for the hash ring, so two loopback ports passed there would collapse
        // into one entry and the test would model nothing.)
        let state = state_with_peers(std::slice::from_ref(&url_a));
        state.peer_manager.register_peer(url_b);
        assert_eq!(
            state.peer_manager.peer_count(),
            2,
            "test setup: two spellings"
        );

        let resp = handle_brokers(&state);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        let brokers = body["brokers"].as_array().unwrap();

        assert_eq!(
            brokers.len(),
            1,
            "one broker listed twice under two spellings: {body}"
        );
        assert_eq!(brokers[0]["id"], fp_id);
        assert_eq!(brokers[0]["reachable"], true);
    }

    /// Distinct brokers must still each get a row — the dedup keys on
    /// identity, and must not collapse genuinely different peers.
    #[test]
    fn distinct_brokers_are_each_listed() {
        let port_a = spawn_fake_peer_health("zc://node-aaaaaaaaaaaaaaaa");
        let port_b = spawn_fake_peer_health("zc://node-bbbbbbbbbbbbbbbb");
        let state = state_with_peers(&[format!("http://127.0.0.1:{port_a}")]);
        state
            .peer_manager
            .register_peer(format!("http://127.0.0.1:{port_b}"));
        assert_eq!(state.peer_manager.peer_count(), 2, "test setup: two peers");

        let resp = handle_brokers(&state);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        let mut ids: Vec<&str> = body["brokers"]
            .as_array()
            .unwrap()
            .iter()
            .map(|b| b["id"].as_str().unwrap())
            .collect();
        ids.sort();
        assert_eq!(
            ids,
            vec!["zc://node-aaaaaaaaaaaaaaaa", "zc://node-bbbbbbbbbbbbbbbb"]
        );
    }

    #[test]
    fn unknown_peer_fingerprint_is_omitted_not_leaked_as_ip() {
        // Peer that never answers /peer/health at all (nothing listening) —
        // its fingerprint can never be learned, so per the documented
        // "unknown → omitted" choice it must not appear in the list, and
        // its bare peer_url/IP must never leak as a stand-in id.
        let dead_peer = "http://127.0.0.1:1".to_string(); // port 1: nothing listens
        let state = state_with_peers(std::slice::from_ref(&dead_peer));
        let resp = handle_brokers(&state);
        let raw = String::from_utf8(resp.body.clone()).unwrap();

        assert!(!raw.contains(&dead_peer), "leaked raw peer_url: {raw}");
        let body: serde_json::Value = serde_json::from_str(&raw).unwrap();
        assert!(
            body["brokers"].as_array().unwrap().is_empty(),
            "unreachable/unknown peer must be omitted: {raw}"
        );
    }

    /// Crude IP-shaped detector for the negative assertion above: four
    /// dot-separated all-numeric octets.
    fn regex_ish_ip_shaped(s: &str) -> bool {
        for window in s.split(|c: char| !c.is_ascii_digit() && c != '.') {
            let parts: Vec<&str> = window.split('.').collect();
            if parts.len() == 4
                && parts
                    .iter()
                    .all(|p| !p.is_empty() && p.parse::<u8>().is_ok())
            {
                return true;
            }
        }
        false
    }

    /// `GET /peers` must be as IP-free as `/brokers` — its handshake auth
    /// (`peer_handshake_auth`) is a shared-secret/loopback check, not true
    /// peer identity, so it's effectively a client-facing surface. This
    /// drives it end-to-end through `super::handle`, the same way real
    /// clients hit it.
    #[test]
    fn peers_endpoint_is_ip_free_and_key_derived() {
        use tiny_http::Method;

        let fp_id = "zc://node-feedfacecafebabe";
        let port = spawn_fake_peer_health(fp_id);
        let peer_url = format!("http://127.0.0.1:{}", port);

        let state = state_with_peers(std::slice::from_ref(&peer_url));
        let self_uri = state.node_key.node_uri();

        let req = crate::broker::http_adapter::BrokerRequest {
            method: Method::Get,
            path: "/peers".to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: None, // in-process caller => treated as loopback
        };
        let resp = super::handle(state, &req, false);
        let raw = String::from_utf8(resp.body.clone()).unwrap();

        // No IP-shaped string, no raw peer_url, no hostname-as-identity.
        assert!(!raw.contains("10.13.13."), "leaked mesh IP: {raw}");
        assert!(!raw.contains("127.0.0.1"), "leaked loopback IP: {raw}");
        assert!(!raw.contains(&port.to_string()), "leaked peer port: {raw}");
        assert!(!raw.contains(&peer_url), "leaked raw peer_url: {raw}");
        assert!(!raw.starts_with("http://"), "leaked raw http url: {raw}");
        assert!(
            !raw.contains("http://"),
            "leaked raw http url anywhere: {raw}"
        );
        assert!(!regex_ish_ip_shaped(&raw), "body looks IP-shaped: {raw}");

        let body: serde_json::Value = serde_json::from_str(&raw).unwrap();
        assert_eq!(body["node"], self_uri);
        assert!(body["node"].as_str().unwrap().starts_with("zc://node-"));

        let peers = body["peers"].as_array().unwrap();
        assert_eq!(peers.len(), 1);
        assert_eq!(peers[0], fp_id);
        assert_eq!(body["total"], 1);
    }
}

#[cfg(test)]
mod marketplace_preselection_guard_tests {
    use super::marketplace_select_enabled;

    /// Serialize env-var mutation across this module's tests (std::env is
    /// process-global) — cargo test runs are already forced single-threaded
    /// for this crate (`--test-threads=1`), but keep the guard local and
    /// explicit in case that ever changes.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Guard test for the `ZAKURO_MARKETPLACE_SELECT=0` escape hatch (task 5):
    /// pre-selection must default ON (unset, or any value other than exactly
    /// "0") and must be disabled only by the literal "0".
    #[test]
    fn marketplace_select_escape_hatch() {
        let _g = ENV_LOCK.lock().unwrap();

        std::env::remove_var("ZAKURO_MARKETPLACE_SELECT");
        assert!(marketplace_select_enabled(), "default (unset) must be ON");

        std::env::set_var("ZAKURO_MARKETPLACE_SELECT", "0");
        assert!(
            !marketplace_select_enabled(),
            "\"0\" must disable pre-selection"
        );

        std::env::set_var("ZAKURO_MARKETPLACE_SELECT", "1");
        assert!(
            marketplace_select_enabled(),
            "any non-\"0\" value must be ON"
        );

        std::env::remove_var("ZAKURO_MARKETPLACE_SELECT");
    }
}

#[cfg(test)]
mod executor_identity_tests {
    use crate::broker::peer::PeerManager;
    use crate::broker::worker::Worker;

    #[test]
    fn executor_fp_prefers_node_identity_and_refuses_unstamped_workers() {
        let mut w = Worker::new(
            "w1".into(),
            "worker-a".into(),
            "http://10.13.13.7:3960".into(),
            "zakuro".into(),
        );
        // Unstamped (no source_node seen yet) → no identity → settlement must refund,
        // never fall back to parsing the address out of `uri`.
        assert_eq!(super::executor_fp(&w), None);

        w.node_fp = "aaaaaaaaaaaaaaaa".into();
        assert_eq!(super::executor_fp(&w), Some("aaaaaaaaaaaaaaaa"));
    }

    /// Direction 1 of the deliberate behaviour change: a PROXIED peer — its
    /// base-URL host is the sidecar, not the worker's mesh IP — now resolves
    /// and gets paid. `get_url_for_ip` on the worker IP misses entirely, which
    /// is the bug this task fixes (executor worked for free).
    #[test]
    fn proxied_executor_resolves_by_fingerprint_where_ip_match_fails() {
        let pm = PeerManager::new(
            Some("10.13.13.2"),
            &["127.0.0.1:19001".to_string()],
            9000,
            "k".to_string(),
            true,
        );
        pm.set_peer_fingerprint("http://127.0.0.1:19001", "cccccccccccccccc");

        let mut w = Worker::new(
            "w2".into(),
            "worker-proxied".into(),
            "http://10.13.13.7:3960".into(),
            "zakuro".into(),
        );
        w.node_fp = "cccccccccccccccc".into();

        // Old address-keyed resolution: the worker's IP is not any peer's host.
        assert_eq!(
            pm.get_url_for_ip("10.13.13.7"),
            None,
            "precondition: the old IP-keyed lookup must miss for a proxied peer"
        );
        // New identity-keyed resolution: pays the right peer.
        assert_eq!(
            super::executor_fp(&w)
                .and_then(|fp| pm.get_url_for_fingerprint(fp))
                .as_deref(),
            Some("http://127.0.0.1:19001")
        );
    }

    /// Direction 2, the accepted regression: a DIRECT peer whose worker carries
    /// no stamped `node_fp` used to be paid via the lucky exact-host match and
    /// now routes to the pay-nobody / full-refund arm. Asserted explicitly so
    /// the trade-off is visible and cannot regress silently.
    #[test]
    fn direct_but_unstamped_executor_now_routes_to_full_refund_arm() {
        let pm = PeerManager::new(
            Some("10.13.13.2"),
            &["10.13.13.7:9000".to_string()],
            9000,
            "k".to_string(),
            true,
        );
        pm.set_peer_fingerprint("http://10.13.13.7:9000", "dddddddddddddddd");

        let w = Worker::new(
            "w3".into(),
            "worker-direct".into(),
            "http://10.13.13.7:3960".into(),
            "zakuro".into(),
        );
        // Old behaviour would have resolved this peer from the worker's IP…
        assert_eq!(
            pm.get_url_for_ip("10.13.13.7").as_deref(),
            Some("http://10.13.13.7:9000")
        );
        // …but with no stamped identity the earn path now resolves to None,
        // i.e. no payout, no redeem, requester refunded in full.
        assert_eq!(super::executor_fp(&w), None);
        assert_eq!(
            super::executor_fp(&w).and_then(|fp| pm.get_url_for_fingerprint(fp)),
            None
        );
    }
}

/// Covering tests that drive the REAL settlement path (`commit_credits`) and
/// assert which `match` arm ran, rather than re-implementing the resolution
/// expression. The discriminator is network-free and needs no stub server:
/// only the `Some(peer_url)` arm credits the platform-house commission (via
/// `settle_executor_payout`), and it refunds the requester only `payout`; the
/// `None` arm credits nobody and refunds the FULL `actual_cost`.
/// Drives the REAL `TaskResult` producer (`run_offer_on`) against a stub worker
/// and asserts the privacy invariant over the value the producer actually
/// emitted — not over a hand-set field. Mutating `worker_uri: worker.zc_uri()`
/// back to `worker.uri.clone()` in `run_offer_on` makes these tests fail.
///
/// Also drives the REAL `PeerIdentity` producer (`handle_peer_identity`)
/// against a genuinely registered worker, covering the payload Task 4 did
/// not: `producer_emits_no_address_in_peer_identity` below.
#[cfg(test)]
mod task_result_producer_tests {
    use super::*;
    use crate::broker::worker::Worker;
    use crate::broker::{BrokerConfig, BrokerState};
    use std::io::{Read, Write};
    use std::net::TcpListener;
    use std::sync::atomic::{AtomicU16, Ordering};
    use std::sync::Arc;

    /// Bind a port and HOLD the reservation — the listener is handed straight to
    /// the serving thread and never released, so no TOCTOU re-bind race can
    /// flake this under parallel execution (same discipline as
    /// `discovery.rs::reserve_port`). Uses a range disjoint from that test's.
    fn reserve_port() -> TcpListener {
        static NEXT: AtomicU16 = AtomicU16::new(50100);
        loop {
            let port = NEXT.fetch_add(1, Ordering::Relaxed);
            assert!(port < 51000, "reserve_port exhausted the test port range");
            if let Ok(l) = TcpListener::bind(("127.0.0.1", port)) {
                return l;
            }
        }
    }

    /// Minimal worker that answers any POST with a 200 and an `X-Zakuro-IP`
    /// header. The header is deliberately present and deliberately a dotted
    /// quad: if the producer ever reinstates the IP-header capture, the payload
    /// assertions below catch it.
    fn spawn_stub_worker(listener: TcpListener) {
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let mut stream = match stream {
                    Ok(s) => s,
                    Err(_) => continue,
                };
                let mut buf = [0u8; 2048];
                let _ = stream.read(&mut buf);
                let body = "ok";
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: application/octet-stream\r\nX-Zakuro-Pid: 4242\r\nX-Zakuro-IP: 10.13.13.7\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(resp.as_bytes());
                let _ = stream.flush();
            }
        });
    }

    fn mk_offer(task_id: &str) -> task_board::TaskOffer {
        serde_json::from_str(&format!(
            r#"{{"task_id":"{}","payload_b64":"","max_price_per_hour":100.0,"estimated_duration_secs":1.0,"timeout_secs":10.0,"requester_user_id":"u","source_broker":"n"}}"#,
            task_id
        ))
        .unwrap()
    }

    /// Produce a real `TaskResult` by running the real producer against a live
    /// stub worker whose URI is a genuine dialable `http://127.0.0.1:<port>`.
    fn produce_real_result() -> task_board::TaskResult {
        let listener = reserve_port();
        let port = listener.local_addr().unwrap().port();
        spawn_stub_worker(listener);

        let st = Arc::new(BrokerState::with_config(BrokerConfig::default()));
        let mut w = Worker::new(
            "wid".into(),
            "worker-exec".into(),
            format!("http://127.0.0.1:{}", port),
            "zakuro".into(),
        );
        w.node_fp = "aaaaaaaaaaaaaaaa".into();
        w.slot = "3960".into();

        super::run_offer_on(&st, &mk_offer("t-privacy"), &w, false)
            .expect("stub worker must answer so the producer builds a TaskResult")
    }

    #[test]
    fn producer_emits_no_address_in_task_result() {
        let r = produce_real_result();
        let json = serde_json::to_string(&r).unwrap();

        // Payload-level guards first: these are field-agnostic, so they hold
        // however a future regression smuggles an address in.
        assert!(
            !json.contains("http://"),
            "producer put a scheme+host on the wire: {json}"
        );
        assert!(
            !json.contains("worker_ip"),
            "worker_ip must be off the wire: {json}"
        );
        // Nothing matching a dotted quad may appear anywhere in the payload —
        // catches both `worker.uri` and a reinstated X-Zakuro-IP capture,
        // regardless of which field they land in.
        assert!(
            !contains_dotted_quad(&json),
            "producer put an IP address on the wire: {json}"
        );
        // The producer's own worker URI IS a dialable address; the emitted
        // handle must be the key-derived one instead.
        assert_eq!(
            r.worker_uri, "zc://worker-aaaaaaaaaaaaaaaa-3960",
            "producer must emit Worker::zc_uri(), not the dialable worker.uri"
        );
        // ...and the identity IS present.
        assert_eq!(r.executor_node_uri, st_node_uri(&r));
        assert!(
            r.executor_node_uri.starts_with("zc://node-"),
            "executor_node_uri must be the key-derived node identity: {:?}",
            r.executor_node_uri
        );
    }

    /// Produce a real `PeerIdentity` by driving the REAL producer
    /// (`handle_peer_identity`) against a `BrokerState` with a genuine
    /// registered worker whose `uri` is a dialable `http://127.0.0.1:<port>` —
    /// exactly the kind of value a regression could smuggle onto the wire.
    /// No stub server is needed: `handle_peer_identity` never dials the
    /// worker, it only reads registry state.
    fn produce_real_peer_identity() -> task_board::PeerIdentity {
        use crate::broker::http_adapter::BrokerRequest;
        use crate::broker::worker::WorkerRegistration;

        let config = BrokerConfig {
            owner_user_id: Some("1000000001".into()),
            node_name: Some("node-a".into()),
            ..Default::default()
        };
        let st = Arc::new(BrokerState::with_config(config));
        st.workers.register(WorkerRegistration {
            name: "worker-a".into(),
            uri: "http://127.0.0.1:39999".into(),
            worker_type: "zakuro".into(),
            resources: Default::default(),
            pricing: Default::default(),
            tags: vec![],
            max_timeout_secs: 0.0,
            hardware: Default::default(),
            wireguard_ip: None,
            is_docker: None,
            source_node: None,
            explicit_local: false,
            provider_type: Default::default(),
            served_models: vec![],
            price_per_mtok: 0.0,
        });

        let req = BrokerRequest {
            method: tiny_http::Method::Get,
            path: "/peer/identity".into(),
            query: "".into(),
            headers: vec![],
            body: vec![],
            peer_addr: None, // in-process caller -> is_loopback() == true, no peer key required
        };
        let resp = super::handle_peer_identity(&st, &req);
        assert_eq!(resp.status, 200, "handle_peer_identity must succeed");
        serde_json::from_slice(&resp.body).expect("handle_peer_identity must emit valid JSON")
    }

    #[test]
    fn producer_emits_no_address_in_peer_identity() {
        let id = produce_real_peer_identity();
        let json = serde_json::to_string(&id).unwrap();

        assert!(
            !json.contains("http://"),
            "producer put a scheme+host on the wire: {json}"
        );
        assert!(
            !contains_dotted_quad(&json),
            "producer put an IP address on the wire: {json}"
        );
        assert_eq!(id.workers.len(), 1, "the registered worker must be listed");
    }

    /// zc#305: the handshake states which binary answered it, so the
    /// capability flags beside it (`supports_two_phase`, …) stop being the
    /// only way to reason about a peer's age.
    #[test]
    fn peer_identity_discloses_the_running_build() {
        let id = produce_real_peer_identity();
        let build = id.build.expect("handshake must disclose a build");
        assert_eq!(build, *crate::build_id::current());
        assert!(build.is_known());
    }

    /// A peer that predates the field sends no `build` key at all.
    #[test]
    fn peer_identity_from_an_older_peer_deserializes_with_no_build() {
        let old_wire = r#"{"owner_user_id":"1000000001","node_name":"node-a",
            "verified":false,"workers":[],"quic_port":0}"#;
        let id: task_board::PeerIdentity = serde_json::from_str(old_wire).unwrap();
        assert!(id.build.is_none());
        assert!(!id.supports_two_phase);
    }

    /// The `executor_node_uri` a well-formed result must carry: the executing
    /// node's own identity, derived from the same key that signed the receipt.
    fn st_node_uri(r: &task_board::TaskResult) -> String {
        let node_id = r
            .executor_node_id
            .as_ref()
            .expect("producer signs the receipt, so node_id is present");
        format!(
            "zc://node-{}",
            crate::broker::node_identity::fingerprint_of_pubkey_b64(node_id).unwrap()
        )
    }

    /// True if `s` contains something shaped like an IPv4 address.
    fn contains_dotted_quad(s: &str) -> bool {
        let b: Vec<char> = s.chars().collect();
        let mut i = 0;
        while i < b.len() {
            let mut j = i;
            let mut groups = 0;
            loop {
                let start = j;
                while j < b.len() && b[j].is_ascii_digit() {
                    j += 1;
                }
                if j == start {
                    break;
                }
                groups += 1;
                if groups == 4 {
                    return true;
                }
                if j < b.len() && b[j] == '.' {
                    j += 1;
                } else {
                    break;
                }
            }
            i = if j > i { j } else { i + 1 };
        }
        false
    }

    /// QUIC one-shot offers used to have a SECOND `TaskResult` producer of
    /// their own in `quic.rs::handle_stream`. Since zc#423 they run through
    /// `run_peer_offer`, so the producer tested above is the only one; this
    /// guards against a private copy coming back in quic.rs (outside its
    /// tests). The QUIC wire tests in `quic.rs::offer_gate_tests` drive the
    /// real path and check the handle it emits.
    #[test]
    fn quic_has_no_task_result_producer_of_its_own() {
        let src = include_str!("quic.rs");
        let prod = &src[..src.find("#[cfg(test)]\nmod ").unwrap_or(src.len())];
        assert!(
            prod.contains("run_peer_offer(&state, &offer, require_voucher)"),
            "quic.rs one-shot offers must run through the shared executor"
        );
        assert!(
            !prod.contains("TaskResult {"),
            "quic.rs must not build its own TaskResult"
        );
        assert!(
            !src.contains("X-Zakuro-IP"),
            "quic.rs must not capture the worker IP header for the mesh payload"
        );
    }

    #[test]
    fn dotted_quad_detector_is_sound() {
        // Guard the guard: a detector that never fires would silently defang
        // `producer_emits_no_address_in_task_result`.
        assert!(contains_dotted_quad("http://10.13.13.7:3960"));
        assert!(contains_dotted_quad("127.0.0.1"));
        assert!(contains_dotted_quad(r#"{"worker_ip":"192.168.0.23"}"#));
        assert!(!contains_dotted_quad("zc://worker-aaaaaaaaaaaaaaaa-3960"));
        assert!(!contains_dotted_quad("zc://node-13a9551e881f7f8c"));
        assert!(!contains_dotted_quad("1234.5")); // duration_ms
        assert!(!contains_dotted_quad("0.789")); // actual_cost
    }
}

#[cfg(test)]
mod commit_credits_arm_tests {
    use super::*;
    use crate::broker::peer::PeerManager;
    use crate::broker::worker::Worker;
    use crate::broker::{BrokerConfig, BrokerState};
    use std::sync::{Arc, Mutex};

    /// A peer registered at a closed loopback port: `get_client` returns `Some`
    /// so the `Some` arm is fully exercised, and the `earn` RPC fails fast with
    /// connection-refused (no network, no timeout).
    const PEER_ADDR: &str = "127.0.0.1:19099";
    const PEER_URL: &str = "http://127.0.0.1:19099";
    const PEER_FP: &str = "cccccccccccccccc";

    fn state_with_seeded_peer() -> Arc<BrokerState> {
        // Default: a closed port, so no redeem can ever succeed. Tests that care
        // about the redeem leg use `state_with_seeded_peer_api` instead.
        state_with_seeded_peer_api("http://127.0.0.1:1")
    }

    fn state_with_seeded_peer_api(api_url: &str) -> Arc<BrokerState> {
        // api_url/api_key make `is_billing_enabled()` true without touching the
        // process-global env (no ZAKURO_MASTER_KEY race). Pre-seeding
        // `authoritative_balances` makes `load_balance_if_needed` short-circuit
        // before any dashboard HTTP call, so the test never leaves the process.
        let config = BrokerConfig {
            api_url: Some(api_url.into()),
            api_key: Some("k".into()),
            ..Default::default()
        };
        let mut st = BrokerState::with_config(config);
        st.peer_manager = PeerManager::new(
            Some("10.13.13.2"),
            &[PEER_ADDR.to_string()],
            9000,
            "k".to_string(),
            true,
        );
        st.peer_manager.set_peer_fingerprint(PEER_URL, PEER_FP);
        let st = Arc::new(st);
        st.ledger
            .authoritative_balances
            .insert("u1".to_string(), 100.0);
        st.ledger.local_credits.insert("u1".to_string(), 100.0);
        assert!(st.is_billing_enabled());
        st
    }

    /// The worker's URI host is deliberately the SAME host as the peer's base
    /// URL, so a reinstated `get_url_for_ip` fallback in the production match
    /// head WOULD resolve it. That is what makes
    /// `unstamped_worker_takes_full_refund_arm_via_commit_credits` a real
    /// mutation detector rather than a tautology.
    fn worker(node_fp: Option<&str>) -> Worker {
        let mut w = Worker::new(
            "wid".into(),
            "worker-exec".into(),
            "http://127.0.0.1:3960".into(),
            "zakuro".into(),
        );
        if let Some(fp) = node_fp {
            w.node_fp = fp.into();
        }
        w
    }

    fn run_commit(st: &Arc<BrokerState>, w: &Worker) {
        run_commit_with_nonce(st, w, "");
    }

    fn run_commit_with_nonce(st: &Arc<BrokerState>, w: &Worker, nonce: &str) {
        let (reservation_id, _) = st
            .ledger
            .local_reserve("u1", 10.0, "ref")
            .expect("reserve must succeed against the seeded balance");
        // authoritative: 100 - 10 = 90 held.
        super::commit_credits(
            st,
            &Authority::Local,
            false, // is_local = false → the remote settlement path
            &reservation_id,
            4.0,   // actual_cost
            100.0, // balance_before
            "req-1",
            "u1",
            w,
            1000.0, // duration_ms
            0.10,   // commission_c → payout 3.6, commission 0.4
            nonce,  // empty = no dashboard redeem HTTP
        );
    }

    /// Bind a port and HOLD the reservation — the listener goes straight to the
    /// serving thread and is never released, so there is no bind-drop-rebind
    /// TOCTOU race under parallel execution. Range is disjoint from both
    /// `discovery.rs::reserve_port` (41000-50000) and
    /// `task_result_producer_tests::reserve_port` (50100-51000).
    fn reserve_port() -> std::net::TcpListener {
        use std::sync::atomic::{AtomicU16, Ordering};
        static NEXT: AtomicU16 = AtomicU16::new(51100);
        loop {
            let port = NEXT.fetch_add(1, Ordering::Relaxed);
            assert!(port < 52000, "reserve_port exhausted the test port range");
            if let Ok(l) = std::net::TcpListener::bind(("127.0.0.1", port)) {
                return l;
            }
        }
    }

    /// A stub dashboard that COUNTS `/api/broker/voucher/redeem` hits and answers
    /// `{"redeemed":true}`. Returns the shared counter and its base URL. This is
    /// what makes the third money leg (the authoritative dashboard commission
    /// credit) observable: without it the leg could be deleted wholesale and no
    /// test would notice.
    fn spawn_redeem_stub() -> (Arc<std::sync::atomic::AtomicUsize>, String) {
        use std::io::{Read, Write};
        use std::sync::atomic::{AtomicUsize, Ordering};
        let listener = reserve_port();
        let url = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        let hits = Arc::new(AtomicUsize::new(0));
        let hits_srv = Arc::clone(&hits);
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let mut stream = match stream {
                    Ok(s) => s,
                    Err(_) => continue,
                };
                let mut buf = [0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                let req = String::from_utf8_lossy(&buf[..n]);
                // Count only the redeem endpoint, so an unrelated dashboard call
                // (e.g. a balance load) can never be mistaken for a redeem.
                if req.contains("/api/broker/voucher/redeem") {
                    hits_srv.fetch_add(1, Ordering::SeqCst);
                }
                let body = r#"{"redeemed":true}"#;
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(resp.as_bytes());
                let _ = stream.flush();
            }
        });
        (hits, url)
    }

    /// A stub peer broker that captures the body of the `/peer/earn` it is
    /// sent and answers 200. It records before it replies, so the body is
    /// readable as soon as the (synchronous) earn RPC returns.
    ///
    /// Reads until `Content-Length` bytes of body have arrived rather than
    /// taking one `read()` as the whole request: a single read is not a
    /// message boundary, and on a loaded runner the headers land in one
    /// segment and the body in the next. Taken as-is that captured an empty
    /// body, which parsed as "EOF while parsing a value" rather than as the
    /// assertion the test is about.
    fn spawn_earn_capturing_peer() -> (Arc<Mutex<Option<String>>>, String, String) {
        use std::io::{Read, Write};
        let listener = reserve_port();
        let addr = listener.local_addr().unwrap();
        let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
        let sink = Arc::clone(&captured);
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let mut stream = match stream {
                    Ok(s) => s,
                    Err(_) => continue,
                };
                let mut raw: Vec<u8> = Vec::new();
                let mut chunk = [0u8; 4096];
                // Headers first, then exactly as much body as they declare.
                let body = loop {
                    let n = match stream.read(&mut chunk) {
                        Ok(0) | Err(_) => break None,
                        Ok(n) => n,
                    };
                    raw.extend_from_slice(&chunk[..n]);
                    let text = String::from_utf8_lossy(&raw).to_string();
                    let Some(split) = text.find("\r\n\r\n") else {
                        continue; // headers still incomplete
                    };
                    let (head, rest) = text.split_at(split + 4);
                    let want: usize = head
                        .lines()
                        .find_map(|l| {
                            l.strip_prefix("Content-Length:")
                                .or_else(|| l.strip_prefix("content-length:"))
                        })
                        .and_then(|v| v.trim().parse().ok())
                        .unwrap_or(0);
                    if rest.len() >= want {
                        break Some((head.to_string(), rest.to_string()));
                    }
                };
                if let Some((head, body)) = body {
                    if head.contains("/peer/earn") && !body.is_empty() {
                        *sink.lock().unwrap() = Some(body);
                    }
                }
                let body = r#"{"status":"ok","balance_after":1.0}"#;
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(resp.as_bytes());
                let _ = stream.flush();
            }
        });
        (
            captured,
            format!("{}:{}", addr.ip(), addr.port()),
            format!("http://{}:{}", addr.ip(), addr.port()),
        )
    }

    /// Same shape as `state_with_seeded_peer_api`, but the peer is a live stub
    /// rather than a closed port, so the earn RPC actually reaches something.
    fn state_with_live_peer(peer_addr: &str, peer_url: &str) -> Arc<BrokerState> {
        let config = BrokerConfig {
            api_url: Some("http://127.0.0.1:1".into()),
            api_key: Some("k".into()),
            ..Default::default()
        };
        let mut st = BrokerState::with_config(config);
        st.peer_manager = PeerManager::new(
            Some("10.13.13.2"),
            &[peer_addr.to_string()],
            9000,
            "k".to_string(),
            true,
        );
        st.peer_manager.set_peer_fingerprint(peer_url, PEER_FP);
        let st = Arc::new(st);
        st.ledger
            .authoritative_balances
            .insert("u1".to_string(), 100.0);
        st.ledger.local_credits.insert("u1".to_string(), 100.0);
        assert!(st.is_billing_enabled());
        st
    }

    /// The payout RPC must name the worker the way the executor's own hub
    /// knows it — `Worker.name`, which `sync_workers_via_api` registers and a
    /// peer's `/workers` advertises — not `Worker.id`, a UUID this registry
    /// mints fresh on every registration and that means nothing anywhere else.
    ///
    /// `handle_peer_earn` stores what it is given: straight into the WAL and
    /// into `BufferedTransaction.worker_name`, which `flush::flush_to_api`
    /// sends to the hub AS `worker_id`. So a UUID here makes the executor's
    /// own earnings unattributable — the same failure as #272, on the leg
    /// where someone is being paid.
    #[test]
    fn the_payout_rpc_names_the_worker_the_executor_registered() {
        let (captured, peer_addr, peer_url) = spawn_earn_capturing_peer();
        let st = state_with_live_peer(&peer_addr, &peer_url);

        run_commit(&st, &worker(Some(PEER_FP)));

        let body = captured
            .lock()
            .unwrap()
            .clone()
            .expect("the resolvable-executor arm must send a /peer/earn");
        let sent: serde_json::Value =
            serde_json::from_str(&body).expect("the earn body must be JSON");
        assert_eq!(
            sent["worker_id"], "worker-exec",
            "the payout must carry the worker's registered name, not its \
             ephemeral id; body was {body}"
        );
    }

    /// The `Some` arm must fire the dashboard voucher redeem — the THIRD money
    /// leg, which authoritatively credits the platform-house commission.
    /// Deleting the redeem block from the `Some` arm must fail this test.
    #[test]
    fn some_arm_redeems_the_voucher_exactly_once() {
        use std::sync::atomic::Ordering;
        let (hits, api_url) = spawn_redeem_stub();
        let st = state_with_seeded_peer_api(&api_url);
        run_commit_with_nonce(&st, &worker(Some(PEER_FP)), "nonce-abc");
        assert_eq!(
            hits.load(Ordering::SeqCst),
            1,
            "the resolvable-executor arm must redeem the voucher exactly once \
             (all three money legs fire together)"
        );
    }

    /// The `None` arm must redeem NOTHING: crediting the platform its commission
    /// with no offsetting executor earn would leave credits unaccounted and the
    /// requester overcharged.
    #[test]
    fn none_arm_redeems_nothing() {
        use std::sync::atomic::Ordering;
        let (hits, api_url) = spawn_redeem_stub();
        let st = state_with_seeded_peer_api(&api_url);
        // Unstamped worker → executor_fp returns None → the pay-nobody arm.
        run_commit_with_nonce(&st, &worker(None), "nonce-abc");
        assert_eq!(
            hits.load(Ordering::SeqCst),
            0,
            "the unresolvable-executor arm must redeem nothing"
        );
        // ...and the requester is still made whole for the FULL actual_cost.
        assert_eq!(bal(&st, "u1"), Some(100.0));
    }

    fn bal(st: &Arc<BrokerState>, uid: &str) -> Option<f64> {
        st.ledger.authoritative_balances.get(uid).map(|v| *v)
    }

    #[test]
    fn unstamped_worker_takes_full_refund_arm_via_commit_credits() {
        let st = state_with_seeded_peer();
        run_commit(&st, &worker(None));

        // None arm: local_commit refunded the 6.0 unspent hold (90 → 96), then
        // the arm refunded the FULL actual_cost 4.0 (96 → 100). Requester is
        // exactly whole.
        assert_eq!(
            bal(&st, "u1"),
            Some(100.0),
            "unstamped executor must leave the requester whole (full refund)"
        );
        // Pay-nobody: the platform-house commission leg must NOT have fired.
        assert_eq!(
            bal(&st, "platform-house"),
            None,
            "None arm credited the platform commission — a money leg escaped the Some arm"
        );
        assert_eq!(
            st.ledger.local_credits.get("platform-house").map(|v| *v),
            None
        );
    }

    #[test]
    fn stamped_resolvable_worker_takes_payout_arm_via_commit_credits() {
        let st = state_with_seeded_peer();
        run_commit(&st, &worker(Some(PEER_FP)));

        // Some arm: platform-house authoritatively credited its 0.4 commission.
        assert_eq!(
            bal(&st, "platform-house"),
            Some(0.4),
            "stamped, resolvable executor must credit the platform commission"
        );
        // The executor `earn` RPC cannot succeed (closed port), so `payout` 3.6
        // is refunded and the requester nets exactly -commission: 100 - 0.4.
        let got = bal(&st, "u1").unwrap();
        assert!(
            (got - 99.6).abs() < 1e-9,
            "requester should net -commission on the payout arm; got {got}"
        );
    }

    // ── #272: the hub must see the worker's stable NAME, never its ─────────
    // ephemeral per-registration UUID (`Worker.id`). `sync_workers_via_api`
    // registers workers with the hub keyed by `worker.name`
    // (`src/broker/ledger.rs`), so anything published to
    // `/api/broker/transaction` under `worker.id` can never be attributed —
    // the two identifiers never coincide, and `worker.id` is minted fresh on
    // every registration so there is nothing to backfill after the fact.
    //
    // `worker()` above deliberately gives id "wid" and name "worker-exec": a
    // test that only checked "worker_id is non-empty" wouldn't catch a
    // regression back to `.id`, since both are non-empty strings.

    /// Captures the raw request line + body of the first request landing on
    /// a fresh loopback listener that responds 200 to anything. Good enough
    /// to inspect exactly one dashboard POST (`/api/broker/transaction`)
    /// without pulling in a full HTTP mock crate.
    fn capture_one_request(listener: std::net::TcpListener) -> Arc<Mutex<Option<String>>> {
        use std::io::{Read, Write};
        let captured = Arc::new(Mutex::new(None));
        let seen = Arc::clone(&captured);
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut raw = Vec::new();
                let mut buf = [0u8; 4096];
                loop {
                    let n = stream.read(&mut buf).unwrap_or(0);
                    if n == 0 {
                        break;
                    }
                    raw.extend_from_slice(&buf[..n]);
                    let text = String::from_utf8_lossy(&raw);
                    if let Some(hdr_end) = text.find("\r\n\r\n") {
                        let want: usize = text
                            .lines()
                            .find_map(|l| {
                                l.to_ascii_lowercase()
                                    .strip_prefix("content-length:")
                                    .map(|v| v.trim().parse().unwrap_or(0))
                            })
                            .unwrap_or(0);
                        if raw.len() >= hdr_end + 4 + want {
                            break;
                        }
                    }
                }
                *seen.lock().unwrap() = Some(String::from_utf8_lossy(&raw).to_string());
                let body = "{}";
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = stream.write_all(resp.as_bytes());
            }
        });
        captured
    }

    fn wait_for_capture(captured: &Arc<Mutex<Option<String>>>) -> serde_json::Value {
        for _ in 0..300 {
            if let Some(raw) = captured.lock().unwrap().clone() {
                let body = raw.split("\r\n\r\n").nth(1).unwrap_or("");
                return serde_json::from_str(body)
                    .unwrap_or_else(|e| panic!("captured body {body:?} was not JSON: {e}"));
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        panic!("the mock hub never received the dashboard POST");
    }

    /// `commit_credits`'s `is_local == true` arm (a self-owned job, no P2P
    /// settlement) hands the row to the batched `tx_buffer` rather than
    /// POSTing it from the hot path -- that synchronous POST cost a full
    /// dashboard round trip per request and was removed. The #272 invariant is
    /// unchanged and still checked end-to-end here, against the batch the
    /// buffer actually delivers: the hub must see the worker's stable NAME,
    /// never its ephemeral registry id.
    #[test]
    fn is_local_commit_publishes_the_workers_name_not_its_ephemeral_id() {
        let listener = reserve_port();
        let api_url = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        let captured = capture_one_request(listener);

        let config = BrokerConfig {
            api_url: Some(api_url),
            api_key: Some("k".into()),
            ..Default::default()
        };
        let st = Arc::new(BrokerState::with_config(config));
        let w = worker(None);

        super::commit_credits(
            &st,
            &Authority::Standalone,
            true, // is_local
            "res-local-1",
            0.0,
            100.0,
            "req-local-1",
            "u1",
            &w,
            250.0,
            0.0,
            "",
        );

        // Nothing may have gone out on the hot path...
        assert!(
            captured.lock().unwrap().is_none(),
            "commit_credits must not POST to the dashboard from the /execute hot path"
        );

        // ...but the row must be queued, and the batch the buffer delivers
        // must still carry the stable name and the idempotency key.
        let api_url = st.config.api_url.clone().unwrap();
        let api_key = st.config.api_key.clone().unwrap();
        assert_eq!(
            st.tx_buffer.flush_to_api(&api_url, &api_key, &st.wal),
            1,
            "the local commit must be queued for batched delivery"
        );

        let batch = wait_for_capture(&captured);
        let body = &batch[0];
        assert_eq!(
            body["worker_id"], "worker-exec",
            "the hub must see the worker's stable name, body: {body}"
        );
        assert_ne!(
            body["worker_id"], "wid",
            "must not leak the ephemeral registry id to the hub, body: {body}"
        );
        assert_eq!(
            body["request_id"], "req-local-1",
            "the idempotency key must reach the hub too, body: {body}"
        );
    }

    /// A billed `/execute` that finished is not settled until the hub has
    /// the debit. Its WAL entry has to stay replayable until the flush that
    /// delivers the row (which retires it), not be marked Committed the
    /// moment the in-memory commit returns: zc-worker-i9-2 was SIGKILLed on
    /// 2026-10-02 with two such debits still queued, and replay recovered the
    /// owner's earns for them but not the requester's 0.010565 zkcr.
    #[test]
    fn a_finished_execute_owes_its_debit_until_the_hub_has_it() {
        let st = state_with_seeded_peer();
        let (reservation_id, _) = st.ledger.local_reserve("u1", 10.0, "ref").unwrap();
        st.wal
            .append(&crate::broker::wal::WalEntry {
                request_id: "req-owed".to_string(),
                user_id: "u1".to_string(),
                reservation_id: reservation_id.clone(),
                estimated_cost: 10.0,
                actual_cost: None,
                worker_id: "wid".to_string(),
                worker_name: Some("worker-exec".to_string()),
                duration_ms: None,
                timestamp: chrono::Utc::now(),
                status: WalStatus::Reserved,
                voucher_nonce: None,
            })
            .unwrap();
        let w = worker(None);
        let p = PreparedForward {
            worker_uri: w.uri.clone(),
            body: Vec::new(),
            request_id: "req-owed".to_string(),
            reason: "test".to_string(),
            tx_num: 1,
            effective_timeout: 5.0,
            user_id: "u1".to_string(),
            authority: Authority::Local,
            reservation_id,
            balance_before: 100.0,
            worker: w,
            is_local: false,
            reservation_amount: 10.0,
            instance_action: None,
            instance_id: None,
            start: std::time::Instant::now(),
            commission_c: 0.0,
            voucher_task_nonce: String::new(),
            phases: super::Phases::new(std::time::Instant::now()),
            trace: false,
        };
        let reply = WorkerReply {
            status: 200,
            headers: Vec::new(),
            body: Vec::new(),
        };
        let _ = super::execute_finish(&st, false, p, Ok(reply));

        let _ = st.wal.flush_buffer();
        let owed: Vec<_> = st
            .wal
            .read_uncommitted()
            .unwrap()
            .into_iter()
            .filter(|e| e.request_id == "req-owed")
            .collect();
        assert_eq!(owed.len(), 1, "the debit is still owed to the hub");
        assert_eq!(
            owed[0].status,
            WalStatus::Executed,
            "and replay would commit it"
        );
    }

    /// `execute_finish`'s timeout arm bills partial wall-clock time on a
    /// worker that timed out. Covers both the `Authority::Peer` (no
    /// resolvable client → falls back to the local ledger) and
    /// `Authority::Standalone` branches, which each call
    /// `ledger.publish_transaction` directly with `&p.worker.id` before the
    /// fix.
    fn run_timeout(st: &Arc<BrokerState>, w: Worker, authority: Authority) {
        let p = PreparedForward {
            worker_uri: w.uri.clone(),
            body: Vec::new(),
            request_id: "req-timeout-1".to_string(),
            reason: "Best price: 0.001000 credits".to_string(),
            tx_num: 1,
            effective_timeout: 1.0,
            user_id: "u1".to_string(),
            authority,
            reservation_id: "res-timeout-1".to_string(),
            balance_before: 100.0,
            worker: w,
            is_local: false,
            reservation_amount: 10.0,
            instance_action: None,
            instance_id: None,
            start: std::time::Instant::now(),
            commission_c: 0.0,
            voucher_task_nonce: String::new(),
            phases: super::Phases::new(std::time::Instant::now()),
            trace: false,
        };
        let _ = super::execute_finish(st, false, p, Err("Request timed out".to_string()));
    }

    #[test]
    fn timeout_billing_via_standalone_authority_publishes_the_workers_name() {
        let listener = reserve_port();
        let api_url = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        let captured = capture_one_request(listener);
        let config = BrokerConfig {
            api_url: Some(api_url),
            api_key: Some("k".into()),
            ..Default::default()
        };
        let st = Arc::new(BrokerState::with_config(config));

        run_timeout(&st, worker(None), Authority::Standalone);

        let body = wait_for_capture(&captured);
        assert_eq!(body["worker_id"], "worker-exec", "body: {body}");
        assert_ne!(body["worker_id"], "wid", "body: {body}");
        assert_eq!(body["request_id"], "req-timeout-1", "body: {body}");
    }

    #[test]
    fn timeout_billing_via_unresolvable_peer_authority_publishes_the_workers_name() {
        let listener = reserve_port();
        let api_url = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
        let captured = capture_one_request(listener);
        let config = BrokerConfig {
            api_url: Some(api_url),
            api_key: Some("k".into()),
            ..Default::default()
        };
        let st = Arc::new(BrokerState::with_config(config));

        // No client registered for this URL: `client.commit` is never
        // reachable, so this exercises the same `ledger.commit` +
        // `publish_transaction` fallback as a resolvable-but-unreachable peer.
        run_timeout(
            &st,
            worker(None),
            Authority::Peer("http://127.0.0.1:1".to_string()),
        );

        let body = wait_for_capture(&captured);
        assert_eq!(body["worker_id"], "worker-exec", "body: {body}");
        assert_ne!(body["worker_id"], "wid", "body: {body}");
        assert_eq!(body["request_id"], "req-timeout-1", "body: {body}");
    }
}

/// Spec 2026-09-13-macos-widget §13: which price does billing read?
///
/// FINDING (confirmed by Step 2; rewrite for branch B if it fails): billing reads the per-worker
/// `worker.pricing.price_per_hour`; `BrokerPrice` (`state.price`) only feeds
/// `GET /price`, `/price/set` and the signed `/peer/advert`. Task 4 therefore
/// applies hub prices to `Worker.pricing` (branch A).
#[cfg(test)]
mod billing_price_pin_tests {
    use super::{execute_offer_locally, reserve_offer};
    use crate::broker::worker::test_registration;
    use crate::broker::{task_board, BrokerState};

    /// A worker that takes `delay_ms` to answer, so a job has a duration to bill.
    ///
    /// Built on `integration_tests::bind_loopback_http`, the shared bind-with-retry
    /// helper rather than another hand-rolled `tiny_http` server, so every test
    /// module reuses the one loopback-bind implementation.
    pub(super) fn slow_mock_worker(delay_ms: u64) -> u16 {
        let (server, port) = crate::integration_tests::integration::bind_loopback_http();
        std::thread::spawn(move || {
            for req in server.incoming_requests() {
                std::thread::sleep(std::time::Duration::from_millis(delay_ms));
                let _ = req.respond(tiny_http::Response::from_data(b"ok".to_vec()));
            }
        });
        port
    }

    pub(super) fn state_with_local_worker(name: &str, port: u16, price: f64) -> BrokerState {
        let state = BrokerState::new();
        state.workers.register(test_registration(
            name,
            format!("http://127.0.0.1:{port}"),
            price,
        ));
        state
    }

    /// No budget cap, so any worker price is selectable.
    pub(super) fn pin_offer(task_id: &str) -> task_board::TaskOffer {
        serde_json::from_str(&format!(
            r#"{{"task_id":"{task_id}","payload_b64":"","max_price_per_hour":1000000000.0,"estimated_duration_secs":10.0,"timeout_secs":10.0,"requester_user_id":"u","source_broker":"n"}}"#
        ))
        .unwrap()
    }

    #[test]
    fn billing_reads_the_worker_price_not_the_broker_price() {
        let port = slow_mock_worker(200);
        // 3600 credits/hour == 1 credit/second on the worker…
        let state = state_with_local_worker("pin-w0", port, 3600.0);
        // …and 0 on the broker. If billing read BrokerPrice, every cost would
        // collapse to min_charge (0.001).
        state.price.set(0.0);

        let accept = reserve_offer(&state, &pin_offer("pin-reserve")).unwrap();
        assert!(
            (accept.estimated_cost - 10.0).abs() < 1e-9,
            "estimate must use the worker price (10 s at 1 cr/s), got {}",
            accept.estimated_cost
        );
        assert_eq!(accept.price_per_hour, 3600.0);

        let result = execute_offer_locally(&state, &pin_offer("pin-exec")).unwrap();
        assert!(
            result.actual_cost >= 0.15,
            "a ~200 ms job at 1 cr/s must cost >= 0.15, got {} (BrokerPrice would give 0.001)",
            result.actual_cost
        );
        assert_eq!(result.price_per_hour, 3600.0);
    }

    /// A hub that answers every `sync-workers` call with `reply` and hands each
    /// request body to the test. Built on the shared `bind_loopback_http`
    /// rather than a new hand-rolled `tiny_http` server.
    fn mock_sync_hub(reply: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
        let (server, port) = crate::integration_tests::integration::bind_loopback_http();
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            for mut req in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(req.as_reader(), &mut body);
                let _ = tx.send(body);
                let _ = req.respond(tiny_http::Response::from_string(reply).with_header(
                    tiny_http::Header::from_bytes("Content-Type", "application/json").unwrap(),
                ));
            }
        });
        (format!("http://127.0.0.1:{port}"), rx)
    }

    /// Spec §6.6 invariant: a job on worker X is billed at the hub's effective
    /// price for X once a sync has carried it, and sync keeps reporting X's own price.
    #[test]
    fn hub_price_from_sync_reply_is_what_a_job_is_billed() {
        use crate::broker::ledger::Ledger;
        let port = slow_mock_worker(200);
        let state = state_with_local_worker("pin-w1", port, 3600.0);
        let (hub, bodies) = mock_sync_hub(
            r#"{"success":true,"synced":1,"failed":0,"errors":[],"prices":{"pin-w1":7200.0}}"#,
        );

        let sync = || {
            Ledger::sync_workers_via_api(
                "u1",
                &state.workers.list(),
                &hub,
                "zk_u1_test",
                Some("n"),
                None,
                Some("pk"),
            )
            .unwrap()
        };

        let outcome = sync();
        assert_eq!(outcome.prices.get("pin-w1"), Some(&7200.0));
        assert_eq!(state.workers.apply_hub_prices(&outcome.prices), 1);
        let sent: serde_json::Value = serde_json::from_str(&bodies.recv().unwrap()).unwrap();
        assert_eq!(
            sent[0]["price_per_hour"], 3600.0,
            "first sync reports the worker's own price"
        );

        let result = execute_offer_locally(&state, &pin_offer("hub-exec")).unwrap();
        assert_eq!(result.price_per_hour, 7200.0);
        assert!(
            result.actual_cost >= 0.3,
            "~200 ms at 2 cr/s must cost >= 0.3, got {}",
            result.actual_cost
        );

        sync();
        let sent: serde_json::Value = serde_json::from_str(&bodies.recv().unwrap()).unwrap();
        assert_eq!(
            sent[0]["price_per_hour"], 3600.0,
            "sync keeps reporting the non-override price"
        );
    }
}

/// `POST /route` (contract zc#345 §4): the real router's filtering and
/// strategy ranking, previewed without executing, reserving, billing or
/// mutating anything.
#[cfg(test)]
mod route_dry_run_endpoint_tests {
    use super::*;
    use crate::broker::worker::test_registration;
    use tiny_http::Method;

    fn post_json(path: &str, body: serde_json::Value) -> BrokerRequest {
        BrokerRequest {
            method: Method::Post,
            path: path.to_string(),
            query: String::new(),
            headers: vec![],
            body: serde_json::to_vec(&body).unwrap(),
            peer_addr: None,
        }
    }

    fn get(path: &str) -> BrokerRequest {
        BrokerRequest {
            method: Method::Get,
            path: path.to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: None,
        }
    }

    #[test]
    fn route_picks_the_cheapest_worker_and_ranks_the_rest() {
        let state = Arc::new(BrokerState::new());
        state.workers.register(test_registration(
            "dearer",
            "http://127.0.0.1:3960".to_string(),
            5.0,
        ));
        state.workers.register(test_registration(
            "cheap",
            "http://127.0.0.1:3961".to_string(),
            1.0,
        ));

        let resp = handle(
            state.clone(),
            &post_json(
                "/route",
                serde_json::json!({"strategy": "best_price", "estimated_duration_secs": 3600.0}),
            ),
            false,
        );
        assert_eq!(resp.status, 200, "{}", String::from_utf8_lossy(&resp.body));
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(body["strategy"], "best_price");
        assert_eq!(body["candidates"].as_array().unwrap().len(), 2);
        assert!(body["excluded"].as_array().unwrap().is_empty());
        // Find the registered worker id for "cheap" to compare.
        let cheap_id = state
            .workers
            .list()
            .iter()
            .find(|w| w.name == "cheap")
            .unwrap()
            .id
            .clone();
        assert_eq!(body["chosen"]["worker_id"], cheap_id);
        assert_eq!(body["candidates"][0]["worker_id"], cheap_id);
    }

    #[test]
    fn route_surfaces_the_atelier_runner_tag() {
        let state = Arc::new(BrokerState::new());
        let mut reg = test_registration("runner-w", "http://127.0.0.1:3960".to_string(), 1.0);
        reg.tags = vec!["atelier-runner=http://127.0.0.1:9100".to_string()];
        state.workers.register(reg);

        let resp = handle(
            state.clone(),
            &post_json("/route", serde_json::json!({})),
            false,
        );
        assert_eq!(resp.status, 200);
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(body["chosen"]["atelier_runner"], "http://127.0.0.1:9100");
        assert_eq!(
            body["candidates"][0]["atelier_runner"],
            "http://127.0.0.1:9100"
        );
    }

    #[test]
    fn route_min_vram_gb_excludes_and_404s_when_nothing_is_eligible() {
        let state = Arc::new(BrokerState::new());
        let mut small = test_registration("small-vram", "http://127.0.0.1:3960".to_string(), 1.0);
        small.hardware.gpu_vram_gb = Some(8);
        small.resources.gpus_total = 1;
        small.resources.gpus_available = 1;
        state.workers.register(small);

        let resp = handle(
            state.clone(),
            &post_json("/route", serde_json::json!({"gpus": 1, "min_vram_gb": 80})),
            false,
        );
        assert_eq!(resp.status, 404, "{}", String::from_utf8_lossy(&resp.body));
        let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        assert_eq!(body["code"], "NO_CAPACITY");
        let excluded = body["excluded"].as_array().unwrap();
        assert_eq!(excluded.len(), 1);
        assert!(excluded[0]["reason"]
            .as_str()
            .unwrap()
            .contains("min_vram_gb 80"));
    }

    #[test]
    fn repeated_route_calls_leave_worker_state_and_routing_unchanged() {
        let state = Arc::new(BrokerState::new());
        for i in 0..4 {
            state.workers.register(test_registration(
                &format!("w{i}"),
                format!("http://127.0.0.1:{}", 3960 + i),
                0.001,
            ));
        }
        let body = serde_json::json!({"strategy": "round_robin"});

        for _ in 0..30 {
            let resp = handle(state.clone(), &post_json("/route", body.clone()), false);
            assert_eq!(resp.status, 200);
        }

        // No in-flight counters moved, no quota consumed: every worker is
        // still listed with zero active requests.
        let list = handle(state.clone(), &get("/workers"), false);
        let list: serde_json::Value = serde_json::from_slice(&list.body).unwrap();
        for w in list["workers"].as_array().unwrap() {
            assert_eq!(w["active_requests"], 0);
        }

        // And /execute's own round-robin sequence is exactly what it would be
        // on a broker that had never served a single /route call: the first
        // two unchecked selections must land on two DIFFERENT workers, which
        // only holds if the cursor still starts at 0.
        let d1 = state
            .router
            .select_worker_no_checks(
                &state.workers,
                &router::ResourceRequirements {
                    strategy: router::RoutingStrategy::RoundRobin,
                    ..Default::default()
                },
                None,
            )
            .unwrap();
        let d2 = state
            .router
            .select_worker_no_checks(
                &state.workers,
                &router::ResourceRequirements {
                    strategy: router::RoutingStrategy::RoundRobin,
                    ..Default::default()
                },
                None,
            )
            .unwrap();
        assert_ne!(
            d1.worker.id, d2.worker.id,
            "round-robin must still alternate after 30 /route calls"
        );
    }
}

/// `POST /workers/{id}/drain` (spec 2026-09-13-macos-widget §6.6): loopback-only,
/// marks the worker `Draining`, 404 on an unknown id.
#[cfg(test)]
mod drain_route_tests {
    use super::*;
    use crate::broker::worker::test_registration;
    use tiny_http::Method;

    fn post(path: &str, peer: Option<std::net::SocketAddr>) -> BrokerRequest {
        BrokerRequest {
            method: Method::Post,
            path: path.to_string(),
            query: String::new(),
            headers: vec![],
            body: vec![],
            peer_addr: peer,
        }
    }

    #[test]
    fn drain_is_loopback_only_and_marks_the_worker_draining() {
        let state = Arc::new(BrokerState::new());
        let w = state.workers.register(test_registration(
            "fp-w0",
            "http://127.0.0.1:3960".to_string(),
            3.6,
        ));
        let path = format!("/workers/{}/drain", w.id);

        let remote: std::net::SocketAddr = "10.13.13.9:5555".parse().unwrap();
        assert_eq!(
            handle(state.clone(), &post(&path, Some(remote)), false).status,
            403
        );
        assert_eq!(
            state.workers.get(&w.id).unwrap().status,
            WorkerStatus::Healthy
        );

        let ok = handle(state.clone(), &post(&path, None), false);
        assert_eq!(ok.status, 200, "{}", String::from_utf8_lossy(&ok.body));
        let body: serde_json::Value = serde_json::from_slice(&ok.body).unwrap();
        assert_eq!(body["status"], "draining");
        assert_eq!(
            state.workers.get(&w.id).unwrap().status,
            WorkerStatus::Draining
        );

        let list = handle(
            state.clone(),
            &BrokerRequest {
                method: Method::Get,
                ..post("/workers", None)
            },
            false,
        );
        let list: serde_json::Value = serde_json::from_slice(&list.body).unwrap();
        assert_eq!(list["workers"][0]["status"], "draining");

        assert_eq!(
            handle(state, &post("/workers/nope/drain", None), false).status,
            404
        );
    }
}

/// A P2P task offer forwarded to a local worker must count toward
/// `active_requests` while it is in flight, exactly like `/execute` does —
/// otherwise a draining worker in the middle of a P2P job reports 0 active
/// requests and the agent sends SIGTERM before the job finishes (spec §6.5).
#[cfg(test)]
mod p2p_active_requests_tests {
    use super::billing_price_pin_tests::{pin_offer, slow_mock_worker, state_with_local_worker};
    use super::*;

    #[test]
    fn a_slow_p2p_offer_holds_active_requests_at_one_until_it_completes() {
        let port = slow_mock_worker(200);
        let state = Arc::new(state_with_local_worker("fp-w0", port, 3.6));
        let worker_id = state.workers.list()[0].id.clone();

        let state_for_thread = state.clone();
        let handle_thread = std::thread::spawn(move || {
            execute_offer_locally(&state_for_thread, &pin_offer("p2p-active"))
        });

        // Give the offer time to reach the worker (which sleeps 200ms) before
        // asserting the in-flight count.
        std::thread::sleep(std::time::Duration::from_millis(50));
        let mid = state.workers.get(&worker_id).unwrap();
        assert_eq!(
            mid.active_requests, 1,
            "a P2P offer in flight must be counted, exactly like /execute"
        );

        handle_thread.join().unwrap().unwrap();
        let after = state.workers.get(&worker_id).unwrap();
        assert_eq!(
            after.active_requests, 0,
            "released once the offer completes"
        );
    }
}

/// A reserved P2P offer pins its worker until the commit (which runs on that
/// exact worker), a cancel, or the reservation's expiry. `GET /workers`
/// counts it as activity for that whole window, so a drain can't read a
/// reserved-but-uncommitted worker as idle and have the agent stop it.
#[cfg(test)]
mod reservation_activity_tests {
    use super::billing_price_pin_tests::{pin_offer, slow_mock_worker, state_with_local_worker};
    use super::*;
    use tiny_http::Method;

    #[test]
    fn inflight_guard_cancels_a_running_bench() {
        use crate::bench_node::run::{run, RunCtx, RunOpts, RunOutcome};
        use std::sync::atomic::Ordering::SeqCst;
        let state = Arc::new(state_with_local_worker("bench-w0", 1, 3600.0));
        assert!(!state.bench_cancel.load(SeqCst));
        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let dir = std::env::temp_dir().join(format!("zc-bench-inflight-{}", std::process::id()));
        let runner = {
            let (cancel, state) = (state.bench_cancel.clone(), state.clone());
            std::thread::spawn(move || {
                let progress = |_: &str| {
                    let _ = started_tx.send(());
                    std::thread::sleep(std::time::Duration::from_millis(300));
                };
                let mut submit = |_: &crate::bench_node::report::SignedReport| Ok(());
                run(
                    &RunOpts {
                        save_as: crate::bench_node::run::SubmitState::Pending,
                        budget: std::time::Duration::from_secs(60),
                        no_gpu: true,
                        state_dir: dir,
                        hub_url: None,
                        peers: vec![],
                    },
                    &mut RunCtx {
                        key: &state.node_key,
                        cancel,
                        progress: &progress,
                        submit: Some(&mut submit),
                    },
                )
            })
        };
        started_rx.recv().unwrap();
        let first = crate::broker::InflightGuard::new(&state);
        assert!(matches!(runner.join().unwrap(), RunOutcome::Cancelled));
        assert_eq!(state.inflight.load(SeqCst), 1);
        // Only the 0 -> 1 transition cancels.
        state.bench_cancel.store(false, SeqCst);
        let second = crate::broker::InflightGuard::new(&state);
        assert!(!state.bench_cancel.load(SeqCst));
        assert_eq!(state.inflight.load(SeqCst), 2);
        drop(first);
        drop(second);
        assert_eq!(state.inflight.load(SeqCst), 0);
        assert!(state.last_busy.load(SeqCst) > 0);
    }

    fn listed_active_requests(state: &Arc<BrokerState>) -> u64 {
        let resp = handle(
            state.clone(),
            &BrokerRequest {
                method: Method::Get,
                path: "/workers".to_string(),
                query: String::new(),
                headers: vec![],
                body: vec![],
                peer_addr: None,
            },
            false,
        );
        let list: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
        list["workers"][0]["active_requests"].as_u64().unwrap()
    }

    #[test]
    fn a_reserved_offer_counts_as_activity_until_commit_cancel_or_expiry() {
        let port = slow_mock_worker(0);
        let state = Arc::new(state_with_local_worker("fp-w0", port, 3.6));
        assert_eq!(listed_active_requests(&state), 0);

        reserve_offer(&state, &pin_offer("r-commit")).unwrap();
        assert_eq!(
            listed_active_requests(&state),
            1,
            "reserved, not yet committed"
        );
        let pending = take_committed(&state, "r-commit").unwrap();
        let worker = state.workers.get(&pending.worker_id).unwrap();
        run_offer_on(&state, &pending.offer, &worker, false).unwrap();
        assert_eq!(
            listed_active_requests(&state),
            0,
            "released once the commit ran"
        );

        reserve_offer(&state, &pin_offer("r-cancel")).unwrap();
        assert_eq!(listed_active_requests(&state), 1);
        cancel_offer(&state, "r-cancel");
        assert_eq!(listed_active_requests(&state), 0, "released by a cancel");

        reserve_offer(&state, &pin_offer("r-expire")).unwrap();
        assert_eq!(listed_active_requests(&state), 1);
        std::thread::sleep(std::time::Duration::from_millis(5));
        sweep_expired_offers(&state, std::time::Duration::ZERO);
        assert_eq!(
            listed_active_requests(&state),
            0,
            "released once the reservation expired"
        );
    }
}

/// `GET /workers` end to end: the estimate is opt-in via `?estimate=1`, and
/// distinguishes "never measured" from "measured" the way the field-level
/// unit tests already pin, but exercised through the real route + query
/// parsing rather than by calling `worker_to_info` directly.
#[cfg(test)]
mod workers_route_estimate_tests {
    use super::billing_price_pin_tests::{slow_mock_worker, state_with_local_worker};
    use super::*;
    use tiny_http::Method;

    fn get_workers(state: &Arc<BrokerState>, query: &str) -> serde_json::Value {
        let resp = handle(
            state.clone(),
            &BrokerRequest {
                method: Method::Get,
                path: "/workers".to_string(),
                query: query.to_string(),
                headers: vec![],
                body: vec![],
                peer_addr: None,
            },
            false,
        );
        serde_json::from_slice(&resp.body).unwrap()
    }

    #[test]
    fn plain_workers_request_carries_no_estimate_field() {
        let port = slow_mock_worker(0);
        let state = Arc::new(state_with_local_worker("fp-w0", port, 3.6));
        let list = get_workers(&state, "");
        assert!(
            list["workers"][0].get("estimate").is_none(),
            "no ?estimate= means no field at all: {list}"
        );
    }

    #[test]
    fn estimate_query_param_reports_never_measured_as_null_not_zero() {
        let port = slow_mock_worker(0);
        let state = Arc::new(state_with_local_worker("fp-w0", port, 3.6));
        let list = get_workers(&state, "estimate=1");
        let est = &list["workers"][0]["estimate"];
        assert_eq!(est["observations"], 0.0);
        assert!(
            est["median_service_ms"].is_null(),
            "never measured must be null, not 0: {list}"
        );
    }

    #[test]
    fn estimate_query_param_reports_the_posterior_once_measured() {
        let port = slow_mock_worker(0);
        let state = Arc::new(state_with_local_worker("fp-w0", port, 3.6));
        let worker_id = state.workers.list()[0].id.clone();
        state.workers.record_request(&worker_id, 42.0, true);

        let list = get_workers(&state, "estimate=1");
        let est = &list["workers"][0]["estimate"];
        assert_eq!(est["observations"], 1.0);
        let median = est["median_service_ms"].as_f64().expect("one observation");
        assert!((median - 42.0).abs() < 1e-9, "got {median}");
    }
}

/// The zc↔hub earnings contract (spec 2026-09-13-macos-widget §5.3/§6.6): a
/// provider's earnings are the rows booked as `earn-{request_id}` with
/// dashboard type `credit_purchase`. The hub's summary query depends on both.
///
/// These tests pin all three sites that book an earn row —
/// `settle_own_provider_payout`, `handle_peer_earn`, `settle_self_payout` —
/// plus the flush mapping (asserted at the payload level in
/// `flush::earn_credit_purchase_payload_tests`, and here as the pure
/// function). A refund's `{id}-earn-refund` id must NOT collide with the
/// `earn-` prefix the hub's summary query keys off of.
#[cfg(test)]
mod earn_prefix_contract_tests {
    use super::*;
    use crate::broker::flush::dashboard_type;
    use crate::broker::worker::test_registration;
    use tiny_http::Method;

    /// A broker state configured with `owner`, deterministic (no env
    /// dependence) and without a dashboard configured unless `api_configured`.
    fn owner_state(owner: Option<&str>, api_configured: bool) -> Arc<BrokerState> {
        Arc::new(BrokerState::with_config(crate::broker::BrokerConfig {
            owner_user_id: owner.map(|s| s.to_string()),
            api_url: api_configured.then(|| "http://127.0.0.1:1".to_string()),
            api_key: api_configured.then(|| "k".to_string()),
            peer_key: None,
            enable_p2p: false,
            ..crate::broker::BrokerConfig::default()
        }))
    }

    #[test]
    fn peer_earn_books_an_earn_prefixed_credit_purchase_for_the_owner() {
        let state = Arc::new(BrokerState::with_config(crate::broker::BrokerConfig {
            peer_key: Some("pk".to_string()),
            enable_p2p: true,
            owner_user_id: Some("owner".to_string()),
            api_url: None,
            api_key: None,
            // A non-empty peer list skips the localhost broker probe in with_config.
            discovery: crate::broker::DiscoveryConfig {
                peers: vec!["127.0.0.1:1".to_string()],
                ..crate::broker::DiscoveryConfig::default()
            },
            ..crate::broker::BrokerConfig::default()
        }));
        let body = serde_json::json!({
            "amount": 1.5,
            "duration_ms": 10.0,
            "worker_id": "a1b2c3d4-w0",
            "requesting_user": "someone",
            "request_id": "r-42"
        });
        let req = BrokerRequest {
            method: Method::Post,
            path: "/peer/earn".to_string(),
            query: String::new(),
            headers: vec![("X-Peer-Key".to_string(), "pk".to_string())],
            body: body.to_string().into_bytes(),
            peer_addr: None,
        };

        let resp = handle(state.clone(), &req, false);
        assert_eq!(resp.status, 200, "{}", String::from_utf8_lossy(&resp.body));

        let queued = state.tx_buffer.pending_snapshot();
        let tx = queued
            .iter()
            .find(|t| t.request_id == "earn-r-42")
            .expect("the earn row must be queued under the earn- prefix");
        assert_eq!(tx.user_id, "owner");
        assert_eq!(dashboard_type(&tx.tx_type), "credit_purchase");
    }

    #[test]
    fn dashboard_types_are_stable() {
        assert_eq!(dashboard_type("commit"), "job_execution");
        assert_eq!(dashboard_type("cancel"), "job_execution");
        assert_eq!(dashboard_type("credit"), "credit_purchase");
        assert_eq!(dashboard_type("serve"), "serve");
    }

    /// Site 1 (`server.rs::settle_own_provider_payout`): a job served on a
    /// worker registered directly on THIS broker pays its own configured
    /// owner via the same `earn-{request_id}` / `credit` shape as the peer
    /// path, driven directly at the function — the smallest real unit that
    /// builds this earning transaction.
    #[test]
    fn settle_own_provider_payout_books_an_earn_prefixed_credit_for_the_owner() {
        let state = owner_state(Some("owner"), false);
        let worker = state.workers.register(test_registration(
            "w-own",
            "http://127.0.0.1:1".to_string(),
            3600.0,
        ));

        settle_own_provider_payout(&state, "requester", &worker, 10.0, 0.0, "", "r-own-1", 5.0);

        let queued = state.tx_buffer.pending_snapshot();
        let tx = queued
            .iter()
            .find(|t| t.request_id == "earn-r-own-1")
            .expect("the own-provider payout must be queued under the earn- prefix");
        assert_eq!(tx.user_id, "owner");
        assert_eq!(tx.tx_type, "credit");
        assert_eq!(dashboard_type(&tx.tx_type), "credit_purchase");
    }

    /// Site 3 (`server.rs::settle_self_payout`): a self-executed job (no
    /// peer round trip) pays the owner the same way. Billing must be
    /// enabled (api_url + api_key configured) for this function to run at
    /// all — it early-returns otherwise.
    #[test]
    fn settle_self_payout_books_an_earn_prefixed_credit_for_the_owner() {
        let state = owner_state(Some("owner"), true);
        let worker = state.workers.register(test_registration(
            "w-self",
            "http://127.0.0.1:1".to_string(),
            3600.0,
        ));

        settle_self_payout(&state, "requester", 10.0, 0.0, &worker, "r-self-1", 5.0);

        let queued = state.tx_buffer.pending_snapshot();
        let tx = queued
            .iter()
            .find(|t| t.request_id == "earn-r-self-1")
            .expect("the self-executed payout must be queued under the earn- prefix");
        assert_eq!(tx.user_id, "owner");
        assert_eq!(tx.tx_type, "credit");
        assert_eq!(dashboard_type(&tx.tx_type), "credit_purchase");
    }

    /// When there's no payee (no owner configured), the payout is
    /// refunded to the requester as `{request_id}-earn-refund` — that id
    /// must NOT start with `earn-`, or the hub's `LIKE 'earn-%'` earnings
    /// query would count a refund as a provider's earnings.
    #[test]
    fn settle_own_provider_payout_refund_id_does_not_start_with_earn_prefix() {
        let state = owner_state(None, true);
        let worker = state.workers.register(test_registration(
            "w-refund",
            "http://127.0.0.1:1".to_string(),
            3600.0,
        ));

        settle_own_provider_payout(
            &state,
            "requester",
            &worker,
            10.0,
            0.0,
            "",
            "r-refund-1",
            5.0,
        );

        let queued = state.tx_buffer.pending_snapshot();
        let tx = queued
            .iter()
            .find(|t| t.user_id == "requester")
            .expect("the no-owner refund must be queued");
        assert_eq!(tx.request_id, "r-refund-1-earn-refund");
        assert!(
            !tx.request_id.starts_with("earn-"),
            "a refund id must never start with `earn-`: {}",
            tx.request_id
        );
        assert_eq!(tx.tx_type, "refund");
    }

    /// The second refund site (`settle_executor_payout`, the path `earn_refund_amount`
    /// feeds): when the executor's broker can't be resolved as a registered
    /// peer, the payout is refunded to the requester the same way — same
    /// non-collision requirement.
    #[test]
    fn settle_executor_payout_refund_id_does_not_start_with_earn_prefix() {
        let state = owner_state(None, true);

        settle_executor_payout(
            &state,
            "requester",
            10.0,
            0.0,
            "http://127.0.0.1:2",
            WorkerName::reported("unreachable-worker"),
            "r-refund-2",
            5.0,
        );

        let queued = state.tx_buffer.pending_snapshot();
        let tx = queued
            .iter()
            .find(|t| t.user_id == "requester")
            .expect("the unreachable-executor refund must be queued");
        assert_eq!(tx.request_id, "r-refund-2-earn-refund");
        assert!(
            !tx.request_id.starts_with("earn-"),
            "a refund id must never start with `earn-`: {}",
            tx.request_id
        );
        assert_eq!(tx.tx_type, "refund");
    }

    /// The third refund site: `settle_self_payout`'s no-owner arm
    /// independently formats the same `{request_id}-earn-refund` id — a
    /// separate literal from the other two refund sites, so a mis-edit here
    /// specifically (e.g. `earn-{request_id}-refund`) is not caught by
    /// either of the other two refund tests above.
    #[test]
    fn settle_self_payout_refund_id_does_not_start_with_earn_prefix() {
        let state = owner_state(None, true);
        let worker = state.workers.register(test_registration(
            "w-self-refund",
            "http://127.0.0.1:1".to_string(),
            3600.0,
        ));

        settle_self_payout(&state, "requester", 10.0, 0.0, &worker, "r-refund-3", 5.0);

        let queued = state.tx_buffer.pending_snapshot();
        let tx = queued
            .iter()
            .find(|t| t.user_id == "requester")
            .expect("the self-executed no-owner refund must be queued");
        assert_eq!(tx.request_id, "r-refund-3-earn-refund");
        assert!(
            !tx.request_id.starts_with("earn-"),
            "a refund id must never start with `earn-`: {}",
            tx.request_id
        );
        assert_eq!(tx.tx_type, "refund");
    }
}

/// Choosing a worker for a peer's offer used to be its own hand-written
/// filter list and its own counter, sitting apart from the router the rest of
/// the broker uses. Rules the other paths honour were simply missing from it,
/// and nothing failed when they were: the job just ran somewhere it should
/// not have, or was refused by a broker perfectly able to run it.
#[cfg(test)]
mod offer_selection_tests {
    use super::{reserve_offer, BrokerState};
    use crate::broker::router::{ResourceRequirements, Router};
    use crate::broker::task_board;
    use crate::broker::worker::test_registration;

    fn offer(task_id: &str) -> task_board::TaskOffer {
        serde_json::from_str(&format!(
            r#"{{"task_id":"{task_id}","payload_b64":"","max_price_per_hour":100.0,"estimated_duration_secs":1.0,"timeout_secs":10.0,"requester_user_id":"u","source_broker":"n"}}"#
        ))
        .unwrap()
    }

    /// The same regression as `local_selection_follows_ownership_not_uri_spelling`,
    /// on the other path. A broker sharing a WireGuard sidecar's network
    /// namespace registers its OWN worker under a `zc://` handle that carries
    /// no IP, and locality follows ownership rather than the spelling of a
    /// URI. Direct execution has selected such a worker since that fix; an
    /// offer never saw it, so one broker would run its own jobs on a worker
    /// and reject its peers' in the same breath.
    #[test]
    fn an_offer_sees_the_same_local_workers_as_direct_execution() {
        let state = BrokerState::new();
        let mut reg = test_registration(
            "sidecar-w",
            "zc://worker-7fed13b4a701206f-3960".to_string(),
            1.0,
        );
        reg.explicit_local = true; // named in ZAKURO_WORKERS
        reg.source_node = None; // this broker registered it itself
        state.workers.register(reg);

        Router::new()
            .select_local_worker(&state.workers, None, &ResourceRequirements::default(), None)
            .expect("direct execution selects an owned worker");

        assert!(
            reserve_offer(&state, &offer("t-sidecar")).is_ok(),
            "an offer must see the worker direct execution just selected"
        );
    }

    /// The measured gain the adaptive policy was built for — +22% throughput,
    /// p50 −25% — reached one branch of one function. A broker taking work
    /// from its peers routed it by a counter, for no reason an operator could
    /// see. The policy is an argument of the one selection layer now, so
    /// switching it on switches it on for all of this broker's traffic.
    #[test]
    fn the_adaptive_policy_routes_a_peer_offer_too() {
        // Serialises the tests that toggle ZAKURO_ADAPTIVE_ROUTING.
        static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());

        let state = BrokerState::new();
        let fast = state.workers.register(test_registration(
            "fast",
            "http://127.0.0.1:3960".to_string(),
            1.0,
        ));
        let slow = state.workers.register(test_registration(
            "slow",
            "http://127.0.0.1:3961".to_string(),
            1.0,
        ));
        for _ in 0..40 {
            state.workers.record_request(&fast.id, 20.0, true);
            state.workers.record_request(&slow.id, 900.0, true);
        }

        let previous = std::env::var("ZAKURO_ADAPTIVE_ROUTING").ok();
        std::env::set_var("ZAKURO_ADAPTIVE_ROUTING", "1");
        let to_fast = (0..200)
            .filter(|i| {
                let task = format!("t-adaptive-{i}");
                let chosen = reserve_offer(&state, &offer(&task))
                    .map(|a| a.worker_name == "fast")
                    .unwrap_or(false);
                super::cancel_offer(&state, &task);
                chosen
            })
            .count();
        match previous {
            Some(v) => std::env::set_var("ZAKURO_ADAPTIVE_ROUTING", v),
            None => std::env::remove_var("ZAKURO_ADAPTIVE_ROUTING"),
        }

        assert!(
            to_fast > 150,
            "the 20 ms worker took {to_fast}/200 of the offers; a counter would give about 100"
        );
    }

    /// `TaskOffer` carries the tags the requester asked for, and the offer
    /// path never read them. A job that asked for `gpu` was accepted by, and
    /// ran on, a worker with no tags at all.
    #[test]
    fn an_offer_requiring_tags_is_not_given_to_a_worker_without_them() {
        let state = BrokerState::new();
        state.workers.register(test_registration(
            "untagged",
            "http://127.0.0.1:3960".to_string(),
            1.0,
        ));

        let mut want_gpu = offer("t-gpu");
        want_gpu.tags = vec!["gpu".to_string()];
        assert!(
            reserve_offer(&state, &want_gpu).is_err(),
            "no local worker carries the gpu tag"
        );
    }
}

/// #267: a `RoutingDecision`'s `reason` must reach the caller as a response
/// header, on every path that produces a decision — the ordinary local
/// route, the instance-affinity pinned-worker route, and the peer-offer
/// route.
#[cfg(test)]
mod decision_reason_header_tests {
    use super::*;
    use crate::broker::http_adapter::BrokerRequest;
    use crate::broker::peer::PeerManager;
    use crate::broker::worker::test_registration;
    use crate::broker::BrokerState;
    use std::sync::Arc;
    use tiny_http::Method;

    fn exec_req(headers: Vec<(String, String)>) -> BrokerRequest {
        BrokerRequest {
            method: Method::Post,
            path: "/execute".to_string(),
            query: String::new(),
            headers,
            body: b"payload".to_vec(),
            peer_addr: None,
        }
    }

    #[test]
    fn sanitize_reason_header_strips_newlines_and_bounds_length() {
        let raw = "Adaptive: expected 254ms\nX-Injected: evil";
        let safe = sanitize_reason_header(raw);
        assert!(
            !safe.contains('\n'),
            "must not carry a raw newline: {safe:?}"
        );
        assert!(!safe.contains('\r'), "must not carry a raw CR: {safe:?}");

        let long = "x".repeat(10_000);
        let safe_long = sanitize_reason_header(&long);
        assert!(
            safe_long.chars().count() <= REASON_HEADER_MAX_LEN,
            "must be bounded, got {} chars",
            safe_long.chars().count()
        );

        // A tiny_http header built from the sanitized value must always be
        // constructible — this is the actual safety property we need.
        assert!(Header::from_bytes(b"X-Zakuro-Reason", safe.as_bytes()).is_ok());
        assert!(Header::from_bytes(b"X-Zakuro-Reason", safe_long.as_bytes()).is_ok());
    }

    /// Ordinary local route (no billing, single worker): `execute_prepare`
    /// must thread the winning `RoutingDecision`'s reason into the prepared
    /// forward so `handle_execute` can put it on the wire.
    #[test]
    fn execute_prepare_threads_the_routing_reason_for_a_plain_local_worker() {
        let state = Arc::new(BrokerState::new());
        state.set_local_mode(true);
        state.workers.register(test_registration(
            "solo-worker",
            "http://127.0.0.1:3960".to_string(),
            0.001,
        ));

        let req = exec_req(vec![("X-Zakuro-User".to_string(), "u1".to_string())]);
        match execute_prepare(&state, &req, false, std::time::Instant::now(), &mut None) {
            Prepared::Forward(p) => {
                assert!(
                    !p.reason.is_empty(),
                    "the winning decision's reason must not be dropped"
                );
            }
            Prepared::Done(r) => panic!(
                "expected a forward, got a short-circuit response: {}",
                String::from_utf8_lossy(&r.body)
            ),
        }
    }

    /// Instance-affinity `call_method` skips the router entirely and pins to
    /// a specific worker — that decision has its own reason
    /// ("Instance affinity: pinned to …") which must reach the caller too.
    #[test]
    fn execute_prepare_threads_the_pinned_worker_reason() {
        let state = Arc::new(BrokerState::new());
        state.set_local_mode(true);
        let worker = state.workers.register(test_registration(
            "pinned-worker",
            "http://127.0.0.1:3960".to_string(),
            0.001,
        ));
        state
            .instance_registry
            .insert("inst-1".to_string(), worker.id.clone());

        let req = exec_req(vec![
            ("X-Zakuro-User".to_string(), "u1".to_string()),
            (
                "X-Zakuro-Instance-Action".to_string(),
                "call_method".to_string(),
            ),
            ("X-Zakuro-Instance-Id".to_string(), "inst-1".to_string()),
        ]);
        match execute_prepare(&state, &req, false, std::time::Instant::now(), &mut None) {
            Prepared::Forward(p) => {
                assert!(
                    p.reason.contains("pinned"),
                    "pinned-worker decision reason lost, got: {:?}",
                    p.reason
                );
            }
            Prepared::Done(r) => panic!(
                "expected a forward, got a short-circuit response: {}",
                String::from_utf8_lossy(&r.body)
            ),
        }
    }

    /// Drive one pinned instance call through prepare + finish with a canned
    /// worker reply; returns the state so the affinity table can be checked.
    fn pinned_call(action: &str, body: &[u8]) -> Arc<BrokerState> {
        let state = Arc::new(BrokerState::new());
        state.set_local_mode(true);
        let worker = state.workers.register(test_registration(
            "pinned-worker",
            "http://127.0.0.1:3960".to_string(),
            0.001,
        ));
        state
            .instance_registry
            .insert("inst-1".to_string(), worker.id.clone());
        let req = exec_req(vec![
            ("X-Zakuro-User".to_string(), "u1".to_string()),
            ("X-Zakuro-Instance-Action".to_string(), action.to_string()),
            ("X-Zakuro-Instance-Id".to_string(), "inst-1".to_string()),
        ]);
        let p = match execute_prepare(&state, &req, false, std::time::Instant::now(), &mut None) {
            Prepared::Forward(p) => p,
            Prepared::Done(r) => panic!("expected forward: {}", String::from_utf8_lossy(&r.body)),
        };
        state.workers.increment_active(&p.worker.id);
        let reply = WorkerReply {
            status: 200,
            headers: Vec::new(),
            body: body.to_vec(),
        };
        let _ = execute_finish(&state, false, p, Ok(reply));
        state
    }

    #[test]
    fn release_instance_drops_the_affinity_entry() {
        let state = pinned_call("release_instance", b"released");
        assert!(state.instance_registry.get("inst-1").is_none());
    }

    #[test]
    fn instance_not_found_reply_drops_the_affinity_entry() {
        let state = pinned_call(
            "call_method",
            b"ValueError: Instance not found: inst-1 (expired or evicted)",
        );
        assert!(state.instance_registry.get("inst-1").is_none());
    }

    #[test]
    fn successful_call_keeps_the_affinity_entry() {
        let state = pinned_call("call_method", b"ok");
        assert!(state.instance_registry.get("inst-1").is_some());
    }

    /// A stub peer that answers `/peer/tasks/offer` with a canned
    /// `TaskResult`, so `dispatch_to_peers` takes the winning-peer branch
    /// without needing a second real broker.
    fn spawn_stub_offer_peer(worker_name: &str) -> u16 {
        let server = Arc::new(tiny_http::Server::http("127.0.0.1:0").unwrap());
        let port = server.server_addr().to_ip().unwrap().port();
        let worker_name = worker_name.to_string();
        std::thread::spawn(move || {
            for req in server.incoming_requests() {
                let result = serde_json::json!({
                    "task_id": "t-1",
                    "payload_b64": "",
                    "duration_ms": 5.0,
                    "actual_cost": 0.0,
                    "worker_name": worker_name,
                    "worker_uri": "zc://worker-aaaa-0",
                    "price_per_hour": 0.0,
                    "executor_owner": "peer-owner",
                });
                let body = result.to_string();
                let resp = tiny_http::Response::from_data(body.into_bytes())
                    .with_status_code(200)
                    .with_header(
                        tiny_http::Header::from_bytes("Content-Type", "application/json").unwrap(),
                    );
                let _ = req.respond(resp);
            }
        });
        port
    }

    /// The peer-offer path (no local worker, dispatched to a peer broker)
    /// never goes through `RoutingDecision` at all — the reason belongs to
    /// this broker's OWN decision to dispatch remotely, not the peer's
    /// internal worker choice. It must still be present on the response.
    #[test]
    fn dispatch_to_peers_sets_a_reason_header_on_the_winning_response() {
        let port = spawn_stub_offer_peer("peer-worker-1");

        let mut state = BrokerState::new();
        state.peer_manager = PeerManager::new(
            Some("10.13.13.2"),
            &[format!("127.0.0.1:{port}")],
            9000,
            "k".to_string(),
            true,
        );
        let state = Arc::new(state);

        let offer: task_board::TaskOffer = serde_json::from_str(
            r#"{"task_id":"t-1","payload_b64":"","max_price_per_hour":100.0,"estimated_duration_secs":1.0,"timeout_secs":10.0,"requester_user_id":"u1","source_broker":"n","peer_key":"k"}"#,
        )
        .unwrap();

        let resp = dispatch_to_peers(
            &state,
            offer,
            std::time::Instant::now(),
            "u1",
            false,
            "t-1",
            1,
            false,
            0.0,
            None,
            0.0,
        );

        assert_eq!(
            resp.status,
            200,
            "body: {}",
            String::from_utf8_lossy(&resp.body)
        );
        let reason = resp
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("X-Zakuro-Reason"))
            .map(|(_, v)| v.clone());
        assert!(
            reason.is_some_and(|r| !r.is_empty()),
            "the peer-dispatch decision must carry a reason header too: {:?}",
            resp.headers
        );
    }
}

#[cfg(test)]
mod hot_path_latency_tests {
    use super::*;
    use crate::broker::worker::{
        HardwareInfo, ProviderType, Worker, WorkerPricing, WorkerRegistration, WorkerResources,
    };
    use crate::broker::Ledger;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    /// A stand-in dashboard that is simply slow, and counts what reached it.
    /// The delay is what a real hub round trip costs from a laptop: TCP +
    /// TLS + the hub's own work, ~800 ms against stg.
    fn slow_hub(delay: Duration) -> (String, Arc<AtomicU64>) {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let port = server.server_addr().to_ip().unwrap().port();
        let hits = Arc::new(AtomicU64::new(0));
        let seen = hits.clone();
        std::thread::spawn(move || {
            for mut req in server.incoming_requests() {
                let mut body = String::new();
                let _ = req.as_reader().read_to_string(&mut body);
                seen.fetch_add(1, Ordering::SeqCst);
                std::thread::sleep(delay);
                let _ = req.respond(tiny_http::Response::from_string("{}").with_status_code(200));
            }
        });
        (format!("http://127.0.0.1:{port}"), hits)
    }

    fn local_worker(state: &mut BrokerState) -> Worker {
        let w = state.workers.register(WorkerRegistration {
            name: "local-w0".to_string(),
            uri: "http://127.0.0.1:3960".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: true,
            provider_type: ProviderType::Specialized,
            served_models: vec![],
            price_per_mtok: 0.0,
        });
        let fp = state.node_key.fingerprint();
        state.workers.set_node_fp(&w.id, &fp);
        w
    }

    /// Settling a free, local job must not block the reply on a dashboard
    /// round trip.
    ///
    /// This is the `zc bench -s best_latency` report that prompted the fix:
    /// the broker logged 1-4 ms per `add(2, 3)` while the client measured
    /// ~800 ms, because `commit_credits` POSTed each transaction to
    /// `{api_url}/api/broker/transaction` synchronously, after `duration_ms`
    /// had already been taken. The delivery path for these rows is the
    /// 30 s-batched `tx_buffer`, which exists precisely so the hub is off the
    /// hot path -- the hot-path POST was pure duplicated latency.
    #[test]
    fn local_commit_does_not_block_on_the_dashboard() {
        let hub_delay = Duration::from_millis(800);
        let (hub_url, hits) = slow_hub(hub_delay);

        let mut raw = BrokerState::new();
        raw.config.api_url = Some(hub_url.clone());
        raw.config.api_key = Some("svc-key".to_string());
        raw.ledger = Ledger::new(Some(hub_url), Some("svc-key".to_string()));
        let worker = local_worker(&mut raw);
        let state = Arc::new(raw);

        let start = Instant::now();
        commit_credits(
            &state,
            &peer::Authority::Standalone,
            true, // is_local -- the free path a `zc bench` add(2,3) takes
            "",
            0.0,
            100.0,
            "req-hot-path-1",
            "bench-user",
            &worker,
            1.4,
            0.0,
            "",
        );
        let elapsed = start.elapsed();

        assert!(
            elapsed < hub_delay / 4,
            "settling a free local job blocked for {elapsed:?} on the dashboard \
             (hub delay {hub_delay:?}); it must hand off to tx_buffer and return. \
             This is the ~800 ms `zc bench` measured per add(2, 3)."
        );
        assert_eq!(
            hits.load(Ordering::SeqCst),
            0,
            "no dashboard POST may happen on the /execute hot path"
        );
    }

    /// A job sent to a peer must still teach the router something.
    ///
    /// `dispatch_to_peers` knows its executor only by the name the peer
    /// reports, so before the fix it recorded nothing at all: the worker's
    /// `total_requests` stayed 0, `best_latency` read it as "no measurement
    /// yet" forever, and the adaptive policy's posterior stayed empty. With
    /// every candidate tied at unmeasured, the first one won every decision --
    /// which is why `zc bench` pinned 100% of 300 requests to one remote
    /// worker while local workers sat idle.
    #[test]
    fn a_peer_dispatched_job_is_recorded_against_the_executor() {
        let mut raw = BrokerState::new();
        let w = local_worker(&mut raw);
        let state = Arc::new(raw);

        assert_eq!(
            state.workers.get(&w.id).unwrap().total_requests,
            0,
            "precondition: the worker starts unmeasured"
        );

        // Two in flight, as a real dispatch would have.
        state.workers.increment_active(&w.id);
        state.workers.increment_active(&w.id);

        assert!(
            state.workers.observe_latency_by_name(&w.name, 264.0, true),
            "the executor is in this broker's registry and must be found by name"
        );

        let after = state.workers.get(&w.id).unwrap();
        assert_eq!(
            after.total_requests, 1,
            "the peer round trip must count as a measurement"
        );
        assert!(
            after.avg_latency_ms > 0.0,
            "the measured latency must reach the router, got {}",
            after.avg_latency_ms
        );
        assert_eq!(
            after.active_requests, 2,
            "the peer path never took an in-flight slot, so it must not release one"
        );

        assert!(
            !state
                .workers
                .observe_latency_by_name("a-worker-we-never-registered", 10.0, true),
            "an unknown executor name is reported, not recorded"
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Batch execute
// ═══════════════════════════════════════════════════════════════════════════

/// What a prepared batch carries into its forwards.
struct BatchPrepared {
    batch_id: String,
    user_id: String,
    authority: Authority,
    /// Empty when the batch is free and nothing was held.
    reservation_id: String,
    is_free: bool,
    bill: crate::sched::bill::BatchBill,
    balance_before: f64,
    tx_num: u64,
    effective_timeout: f64,
    placements: Vec<BatchPlacement>,
    /// Tasks this broker will not run, answered as failures rather than
    /// silently dropped. See `handle_execute_batch` for why v1 places only on
    /// this broker's own workers.
    rejected: Vec<(u32, String)>,
    /// What only the broker knows, so the client can size its next batch.
    service_ms: f64,
    slots: usize,
    /// The ONE dashboard-verified commission rate for this batch, captured at
    /// mint time and threaded into settlement so the executor payout and the
    /// dashboard redeem cannot disagree.
    commission_c: f64,
    /// The minted voucher's nonce, redeemed once at settlement.
    voucher_task_nonce: String,
}

/// One task, and the worker that will run it.
struct BatchPlacement {
    id: u32,
    worker: Worker,
    worker_uri: String,
    payload: Vec<u8>,
}

/// Everything before the forwards: who is asking, what it will cost, and where
/// each task goes. Blocking — it reads balances and reserves credit — so the
/// route runs it on the blocking pool exactly as `/execute` runs
/// `execute_prepare`.
fn batch_prepare(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
    user_id: String,
    verbose: bool,
) -> Result<BatchPrepared, BrokerResponse> {
    use crate::sched::batch;

    let batch_id = uuid::Uuid::new_v4().to_string();
    let tx_num = REQUEST_COUNTER.fetch_add(1, Ordering::SeqCst) + 1;

    // `user_id` is established ONCE per request, by the caller, and shared by
    // every task: re-deriving it per task is what makes a batch no faster than
    // the requests it replaced.
    // A foreign requester's voucher is minted under THEIR credential.
    let requester_key = bearer_token(request.header("Authorization").as_deref());

    let requirements: ResourceRequirements = request
        .header("X-Zakuro-Requirements")
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default();
    if let Some(b) = requirements.budget_credits {
        if b <= 0.0 {
            return Err(error_response(
                "budget_credits must be positive",
                "BAD_REQUEST",
                400,
            ));
        }
    }

    let authority = state.peer_manager.determine_authority(&user_id);
    let balance_before = match &authority {
        Authority::Local => state.ledger.load_balance_if_needed(&user_id),
        Authority::Peer(url) => peer_balance(state, url, &user_id),
        Authority::Standalone => state.ledger.load_balance_if_needed(&user_id),
    };
    let _ = state.credits.get_or_create(&user_id, balance_before);

    let body = body_or_413(request)?;
    let tasks = batch::decode_request(body)
        .map_err(|e| error_response(&format!("Malformed batch: {:?}", e), "BAD_REQUEST", 400))?;

    // v1 places only on this broker's own workers. A per-task peer dispatch
    // would put a mesh round trip back INSIDE each element of the batch, which
    // is the exact cost batching exists to remove; the mesh case is what the
    // credit-based pipeline is for.
    let own_ip = super::discovery::get_mesh_ip().or_else(|| state.own_wireguard_ip.clone());
    let mut placements = Vec::with_capacity(tasks.len());
    let mut rejected = Vec::new();
    let mut estimates = Vec::with_capacity(tasks.len());
    for t in tasks {
        match choose_worker(state, verbose, |adaptive| {
            state.router.select_local_worker(
                &state.workers,
                own_ip.as_deref(),
                &requirements,
                adaptive,
            )
        }) {
            Ok(decision) => {
                estimates.push((
                    t.id,
                    decision
                        .worker
                        .pricing
                        .estimate_cost(requirements.estimated_duration_secs),
                ));
                placements.push(BatchPlacement {
                    id: t.id,
                    worker_uri: format!("{}/execute", decision.worker.uri.trim_end_matches('/')),
                    worker: decision.worker,
                    payload: t.payload,
                });
            }
            Err(e) => rejected.push((t.id, e.message)),
        }
    }

    let is_self_owned = state.config.owner_user_id.as_deref() == Some(&user_id);
    // Check locality rather than assume it. v1 places only through
    // `select_local_worker`, so this is `true` in practice today — but the
    // assumption was written as a literal, and a literal cannot notice when
    // the filter behind it changes or when peer placement arrives. Asking each
    // placement keeps the #297 rule true by construction: nothing is free
    // unless our own hardware ran every task in the batch.
    let self_executed = placements
        .iter()
        .all(|p| ran_on_our_hardware(state, &p.worker));
    let is_free = execution_is_free(state.is_billing_enabled(), is_self_owned, self_executed);

    // ONE reservation for the batch. Per task, each would be a round trip to
    // the authority broker — at fifty tasks, ninety-eight in place of two.
    let bill = crate::sched::bill::plan(
        if is_free { &[] } else { &estimates },
        requirements.budget_credits,
        balance_before,
    )
    .map_err(|_| {
        error_response(
            &format!(
                "Insufficient credits for a batch of {}: have {:.4}",
                placements.len(),
                balance_before
            ),
            "INSUFFICIENT_CREDITS",
            402,
        )
    })?;

    // ONE voucher for the batch, mirroring the one reservation. The endpoint
    // shipped (#322) without this: on any fleet with ZAKURO_REQUIRE_VOUCHER
    // set — which is every fleet that has ever measured a `voucher` phase —
    // every batch ran uncommissioned, bypassing the mint-and-redeem the
    // single-task path fails closed on.
    let (commission_c, voucher_task_nonce) = match voucher_need(
        is_free,
        voucher_required(),
        // Derived from the placements above rather than assumed, so peer
        // placement cannot silently mint the wrong thing.
        self_executed,
        redeems_here(&authority),
    ) {
        VoucherNeed::None => (0.0, String::new()),
        VoucherNeed::Refuse => {
            return Err(error_response(
                "Voucher required but this broker is not the settlement authority \
                 for the requester; refusing to run a batch uncommissioned",
                "VOUCHER_NON_LOCAL_AUTHORITY",
                503,
            ))
        }
        VoucherNeed::Mint => {
            mint_and_verify_remote_voucher(state, bill.reserved(), requester_key.as_deref())?
        }
    };

    let reservation_id = match is_free || bill.reserved() <= 0.0 {
        true => String::new(),
        false => reserve_credits(
            state,
            &authority,
            &user_id,
            bill.reserved(),
            &batch_id,
            verbose,
            tx_num,
            balance_before,
        )?,
    };
    if !reservation_id.is_empty() {
        let _ = state.wal.append(&WalEntry {
            request_id: batch_id.clone(),
            user_id: user_id.clone(),
            reservation_id: reservation_id.clone(),
            estimated_cost: bill.reserved(),
            actual_cost: None,
            worker_id: String::new(),
            worker_name: None,
            duration_ms: None,
            timestamp: chrono::Utc::now(),
            status: WalStatus::Reserved,
            voucher_nonce: nonce_opt(&voucher_task_nonce),
        });
    }

    let healthy = state.workers.healthy();
    let slots = healthy
        .iter()
        .filter(|w| state.is_local_worker(&w.uri))
        .count();
    let service_ms = median_service_ms(&healthy);

    Ok(BatchPrepared {
        batch_id,
        user_id,
        authority,
        reservation_id,
        is_free,
        bill,
        balance_before,
        tx_num,
        effective_timeout: requirements.timeout_secs,
        placements,
        rejected,
        service_ms,
        slots,
        commission_c,
        voucher_task_nonce,
    })
}

/// The middle of the measured service times, ignoring workers that have never
/// answered. Zero when nothing has been measured, which `batch_hint` reads as
/// "unknown" rather than "instant".
fn median_service_ms(workers: &[Worker]) -> f64 {
    let mut seen: Vec<f64> = workers
        .iter()
        .map(|w| w.avg_latency_ms)
        .filter(|ms| *ms > 0.0)
        .collect();
    if seen.is_empty() {
        return 0.0;
    }
    seen.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    seen[seen.len() / 2]
}

/// Record what each task cost, settle the batch once, and frame the replies.
///
/// Blocking: it commits credit. Runs on the blocking pool like
/// `execute_finish`.
///
/// **One commit for the batch.** Per task, each would be another round trip to
/// the authority broker — the cost batching exists to remove. That is exact for
/// the money: v1 places only on this broker's own workers, so every task's
/// executor payout goes to the same owner, and the total is the sum of what
/// actually ran, capped by what was reserved. It is coarse for *attribution* —
/// the transaction log names one of the batch's workers rather than each.
/// Per-worker attribution needs `commit_credits` to take a breakdown; it does
/// not change what anybody is paid.
fn batch_finish(
    state: &Arc<BrokerState>,
    mut p: BatchPrepared,
    results: Vec<(u32, Result<WorkerReply, String>, f64)>,
    verbose: bool,
) -> BrokerResponse {
    use crate::sched::batch::{encode_result, BatchResult, ResultStatus};

    let mut body = Vec::new();
    let mut ran_on: Option<Worker> = None;
    let mut total_ms = 0.0;
    let mut ran_ms: Vec<(usize, f64)> = Vec::new();

    for (id, outcome, elapsed_ms) in results {
        let placement = p.placements.iter().find(|pl| pl.id == id);
        match outcome {
            Ok(reply) => {
                if let Some(pl) = placement {
                    ran_ms.push((id as usize, elapsed_ms));
                    if !p.is_free {
                        p.bill
                            .record(id, pl.worker.pricing.estimate_cost(elapsed_ms / 1000.0));
                    }
                    ran_on.get_or_insert_with(|| pl.worker.clone());
                    state
                        .workers
                        .observe_latency_by_name(&pl.worker.name, elapsed_ms, false);
                }
                total_ms += elapsed_ms;
                body.extend_from_slice(&encode_result(&BatchResult {
                    id,
                    status: ResultStatus::Ok,
                    body: reply.body,
                }));
            }
            // A failed task costs nothing: `bill` was never told about it, so
            // it settles as if it had not run, which is what happened.
            Err(e) => body.extend_from_slice(&encode_result(&BatchResult {
                id,
                status: ResultStatus::Failed,
                body: e.into_bytes(),
            })),
        }
    }
    for (id, why) in &p.rejected {
        body.extend_from_slice(&encode_result(&BatchResult {
            id: *id,
            status: ResultStatus::Failed,
            body: why.clone().into_bytes(),
        }));
    }

    let trust_evidence =
        crate::sched::bill::trust_metadata(ran_ms.iter().filter_map(|(id, ms)| {
            p.placements
                .iter()
                .find(|pl| pl.id as usize == *id)
                .map(|pl| (pl.payload.as_slice(), *ms))
        }));
    let spent = p.bill.settle();
    let mut remaining = p.balance_before;
    if !p.reservation_id.is_empty() {
        if let Some(worker) = ran_on.as_ref() {
            remaining = commit_credits(
                state,
                &p.authority,
                p.is_free,
                &p.reservation_id,
                spent,
                p.balance_before,
                &p.batch_id,
                &p.user_id,
                worker,
                total_ms,
                p.commission_c,
                &p.voucher_task_nonce,
            );
        }
        let _ = state.wal.update_status(
            &p.batch_id,
            WalStatus::Executed,
            Some(spent),
            Some(total_ms),
        );
    }
    // Real-job evidence for the hub's node-trust check. After commit_credits:
    // it only attaches to a row that was actually queued (see attach_metadata).
    state.tx_buffer.attach_metadata(&p.batch_id, trust_evidence);
    log_transaction(
        state,
        verbose,
        p.tx_num,
        &p.user_id,
        "EXECUTE_BATCH",
        spent,
        remaining,
        ran_on.as_ref().map(|w| w.name.as_str()),
        total_ms,
        "OK",
    );

    let mut resp = BrokerResponse {
        status: 200,
        headers: Vec::new(),
        body,
    };
    resp.headers.extend([
        header_or("Content-Type", "application/octet-stream"),
        header_or("X-Zakuro-Batch-Id", &p.batch_id),
        header_or("X-Zakuro-Cost", &super::mesh_batch::credits(spent)),
        header_or(
            "X-Zakuro-Credits-Remaining",
            &super::mesh_batch::credits(remaining),
        ),
        // What only the broker knows. The CLIENT sizes the next batch, because
        // sizing needs the round trip and the client is the one that timed it.
        header_or("X-Zakuro-Service-Ms", &format!("{:.3}", p.service_ms)),
        header_or("X-Zakuro-Slots", &p.slots.to_string()),
    ]);
    // What this node calls itself, so a mesh-placed reply can name it.
    if let Some(name) = state.config.node_name.as_deref() {
        resp.headers.push(header_or("X-Zakuro-Node-Name", name));
    }
    // Which worker ran it, as `/execute` says: the one the batch's charge was
    // settled against (`ran_on`, the first worker that answered). Absent when
    // no task ran, so a client reads "unknown" rather than a guess.
    if let Some(w) = ran_on.as_ref() {
        resp.headers.push(header_or("X-Zakuro-Worker", &w.name));
    }
    resp
}

/// `POST /execute/batch`. With `X-Zakuro-Placement: mesh` the broker places
/// the batch across the mesh itself (`handle_mesh_batch`); without it, v1:
/// this broker's own workers only — what a client that pinned a node expects
/// when it posts to that node's broker.
async fn handle_execute_batch(
    state: Arc<BrokerState>,
    request: BrokerRequest,
    verbose: bool,
) -> BrokerResponse {
    use super::mesh_batch::{MESH, PLACEMENT_HEADER};
    // Refuse an unauthenticated batch BEFORE taking the guard: an anonymous
    // request must not cancel a benchmark. The handlers below take `state` by
    // value, so the guard holds its own handle.
    // Authenticated exactly once; the resolved identity travels down to the
    // handlers rather than each re-deriving it from the headers.
    // In remote mode this can be a blocking hub round trip (#384), so it must
    // not run on a runtime thread.
    let (request, identified) = if state.ledger.validates_keys_with_hub() {
        let st = state.clone();
        match tokio::task::spawn_blocking(move || {
            let r = identify(&st, &request);
            (request, r)
        })
        .await
        {
            Ok(pair) => pair,
            Err(_) => {
                return error_response("handler panicked", "INTERNAL", 500);
            }
        }
    } else {
        let r = identify(&state, &request);
        (request, r)
    };
    let user_id = match identified {
        Ok(u) => u,
        Err(resp) => return resp,
    };
    let _inflight = super::InflightHold::new(&state);
    if request.header(PLACEMENT_HEADER).as_deref() == Some(MESH) {
        return handle_mesh_batch(state, request, user_id, verbose).await;
    }
    execute_batch_here(state, request, user_id, verbose).await
}

/// An unpinned batch: split it across the nodes the router finds eligible,
/// run this broker's share in-process on the v1 path, send each peer its
/// share as one sub-batch (in parallel, carrying the caller's own auth so
/// that node bills the caller), and merge the replies. Sub-batches never
/// carry the placement header, so a peer never fans out again; this broker
/// reserves and settles nothing for a peer's share.
async fn handle_mesh_batch(
    state: Arc<BrokerState>,
    request: BrokerRequest,
    user_id: String,
    verbose: bool,
) -> BrokerResponse {
    use super::mesh_batch::{self, ShareReply, Target, MESH, PLACEMENT_HEADER};
    use crate::sched::batch;

    // `user_id` was established by `handle_execute_batch` before anything
    // leaves this machine: an unauthenticated mesh batch is refused there, not
    // fanned out to every peer to be refused there.

    let body = match body_or_413(&request) {
        Ok(b) => b.to_vec(),
        Err(resp) => return resp,
    };
    let tasks = match batch::decode_request(&body) {
        Ok(t) => t,
        Err(e) => return error_response(&format!("Malformed batch: {:?}", e), "BAD_REQUEST", 400),
    };
    let raw_requirements = request.header("X-Zakuro-Requirements");
    let requirements: ResourceRequirements = raw_requirements
        .as_deref()
        .and_then(|s| serde_json::from_str(s).ok())
        .unwrap_or_default();
    if let Some(b) = requirements.budget_credits {
        if b <= 0.0 {
            return error_response("budget_credits must be positive", "BAD_REQUEST", 400);
        }
    }

    if let Some(e) = router::tags_unsatisfied(&state.workers.healthy(), &requirements.tags) {
        return error_response(&e.message, &e.code, 503);
    }

    let own_fp = state.node_key.fingerprint().to_string();
    let mut why_unplaced = "no eligible worker on the mesh for these requirements".to_string();
    let groups = match state.router.route_dry_run(&state.workers, &requirements) {
        Ok(run) => {
            let groups = mesh_batch::group_by_node(
                run.candidates.iter().map(|c| &c.worker),
                &own_fp,
                // The same rule the own share runs with (`select_local_worker`
                // vetoes a worker that arrived by peer sync), so a task counted
                // against our capacity finds a worker here.
                |w| ran_on_our_hardware(&state, w) && w.source_node.is_none(),
                |fp| state.peer_manager.get_url_for_fingerprint(fp),
            );
            let placed: usize = groups.iter().map(|g| g.workers).sum();
            if placed < run.candidates.len() {
                eprintln!(
                    "  [MESH_BATCH] {} eligible worker(s) left out: no address for their node",
                    run.candidates.len() - placed
                );
            }
            groups
        }
        Err(e) => {
            why_unplaced = format!("no eligible worker on the mesh: {}", e.message);
            Vec::new()
        }
    };
    let counts = mesh_batch::allocate(
        &groups.iter().map(|g| g.workers).collect::<Vec<_>>(),
        tasks.len(),
    );

    let total = tasks.len();
    let mut remaining_tasks = tasks.into_iter();
    let mut shares = Vec::new();
    for (group, k) in groups.into_iter().zip(counts) {
        let chunk: Vec<batch::BatchTask> = remaining_tasks.by_ref().take(k).collect();
        if !chunk.is_empty() {
            shares.push((group, chunk));
        }
    }
    let unplaced: Vec<u32> = remaining_tasks.map(|t| t.id).collect();

    let auth: Vec<(String, String)> = ["Authorization", "X-Zakuro-User"]
        .iter()
        .filter_map(|h| request.header(h).map(|v| (h.to_string(), v)))
        .collect();
    let share_timeout =
        mesh_batch::share_timeout_secs(requirements.timeout_secs, DEFAULT_FORWARD_TIMEOUT_SECS);

    // At most this many shares in flight at once; the rest wait their turn.
    const MAX_PARALLEL_SHARES: usize = 16;
    let permits = Arc::new(tokio::sync::Semaphore::new(MAX_PARALLEL_SHARES));
    let mut pending = Vec::new();
    for (group, chunk) in shares {
        let ids: Vec<u32> = chunk.iter().map(|t| t.id).collect();
        let sub_body = batch::encode_request(&chunk);
        let st = state.clone();
        let user_id = user_id.clone();
        let mut headers = auth.clone();
        // A budget is the caller's cap for the whole batch: each share
        // carries its proportion, so it cannot be spent once per node.
        if let Some(r) =
            mesh_batch::share_requirements(raw_requirements.as_deref(), chunk.len(), total)
        {
            headers.push(("X-Zakuro-Requirements".to_string(), r));
        }
        let peer_addr = request.peer_addr;
        let permits = permits.clone();
        let target = group.target.clone();
        let handle = tokio::spawn(async move {
            let _permit = permits.acquire_owned().await;
            match target {
                Target::Own => {
                    let sub = BrokerRequest {
                        method: Method::Post,
                        path: "/execute/batch".into(),
                        query: String::new(),
                        headers,
                        body: sub_body,
                        peer_addr,
                    };
                    let r = execute_batch_here(st, sub, user_id, verbose).await;
                    Ok(ShareReply {
                        status: r.status,
                        headers: r.headers,
                        body: r.body,
                    })
                }
                Target::Peer { url } => {
                    post_share(&st, &url, &headers, sub_body, share_timeout).await
                }
            }
        });
        pending.push((group, ids, handle));
    }
    // Every share answers, even one whose task panicked (`await_share`).
    let mut outcomes = Vec::new();
    for (group, ids, handle) in pending {
        outcomes.push(mesh_batch::await_share(group, ids, handle).await);
    }

    let merged = mesh_batch::merge(outcomes);
    let mut out = merged.body;
    out.extend(mesh_batch::failed_frames(&unplaced, &why_unplaced));
    let mut resp = BrokerResponse {
        status: 200,
        headers: Vec::new(),
        body: out,
    };
    resp.headers.extend([
        header_or("Content-Type", "application/octet-stream"),
        header_or("X-Zakuro-Batch-Id", &uuid::Uuid::new_v4().to_string()),
        header_or("X-Zakuro-Cost", &mesh_batch::credits(merged.cost)),
        header_or(
            "X-Zakuro-Charges",
            &serde_json::to_string(&merged.charges).unwrap_or_else(|_| "[]".into()),
        ),
        header_or(PLACEMENT_HEADER, MESH),
    ]);
    resp
}

/// One peer's share: `POST {peer}/execute/batch` with the caller's headers,
/// over the mesh client when the peer is not on this machine, waiting as
/// long as the share's tasks may run (`share_timeout_secs`).
async fn post_share(
    state: &Arc<BrokerState>,
    peer_url: &str,
    headers: &[(String, String)],
    body: Vec<u8>,
    timeout_secs: f64,
) -> Result<super::mesh_batch::ShareReply, String> {
    let target = format!("{}/execute/batch", peer_url.trim_end_matches('/'));
    let client = pick_forward_client(&state.async_http, state.async_http_mesh.as_ref(), &target);
    let mut req = client
        .post(&target)
        .header("Content-Type", "application/octet-stream")
        .timeout(std::time::Duration::from_secs_f64(timeout_secs))
        .body(body);
    for (k, v) in headers {
        req = req.header(k.as_str(), v.as_str());
    }
    let resp = req.send().await.map_err(|e| e.to_string())?;
    let status = resp.status().as_u16();
    let headers = resp
        .headers()
        .iter()
        .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
        .collect();
    let body = resp.bytes().await.map_err(|e| e.to_string())?.to_vec();
    Ok(super::mesh_batch::ShareReply {
        status,
        headers,
        body,
    })
}

/// `POST /execute/batch` on this broker's own workers — v1, unchanged.
/// Many tasks, one round trip, one reservation.
async fn execute_batch_here(
    state: Arc<BrokerState>,
    request: BrokerRequest,
    user_id: String,
    verbose: bool,
) -> BrokerResponse {
    let st = state.clone();
    let prepared =
        match tokio::task::spawn_blocking(move || batch_prepare(&st, &request, user_id, verbose))
            .await
        {
            Ok(Ok(p)) => p,
            Ok(Err(resp)) => return resp,
            Err(_) => return error_response("handler panicked", "INTERNAL", 500),
        };

    // Every task in flight at once: they are on this broker's own workers, and
    // holding them back would serialise a batch behind its slowest member.
    // `join_next` yields in COMPLETION order, which is the order the frames go
    // out in.
    let mut set = tokio::task::JoinSet::new();
    for pl in &prepared.placements {
        let state = state.clone();
        let uri = pl.worker_uri.clone();
        let payload = pl.payload.clone();
        let worker_id = pl.worker.id.clone();
        let id = pl.id;
        let request_id = format!("{}-{}", prepared.batch_id, id);
        let timeout = prepared.effective_timeout;
        set.spawn(async move {
            state.workers.increment_active(&worker_id);
            let started = Instant::now();
            let out = forward_to_worker_async(
                pick_forward_client(&state.async_http, state.async_http_mesh.as_ref(), &uri),
                &uri,
                payload,
                &request_id,
                timeout,
            )
            .await;
            state.workers.decrement_active(&worker_id);
            (id, out, started.elapsed().as_secs_f64() * 1000.0)
        });
    }
    let mut results = Vec::with_capacity(prepared.placements.len());
    while let Some(joined) = set.join_next().await {
        match joined {
            Ok(r) => results.push(r),
            Err(_) => continue,
        }
    }

    let st = state.clone();
    match tokio::task::spawn_blocking(move || batch_finish(&st, prepared, results, verbose)).await {
        Ok(r) => r,
        Err(_) => error_response("handler panicked", "INTERNAL", 500),
    }
}

/// Every paid path takes the inflight guard (so it cancels a running
/// benchmark), and takes it only after the caller is authenticated (so an
/// anonymous request cannot).
#[cfg(test)]
mod inflight_paid_paths_tests {
    use super::billing_price_pin_tests::{pin_offer, slow_mock_worker, state_with_local_worker};
    use super::*;
    use std::sync::atomic::Ordering::SeqCst;
    use tiny_http::Method;

    fn anonymous_post(path: &str) -> BrokerRequest {
        BrokerRequest {
            method: Method::Post,
            path: path.to_string(),
            query: String::new(),
            headers: vec![],
            body: b"{}".to_vec(),
            peer_addr: None,
        }
    }

    #[test]
    fn a_peer_offer_cancels_a_running_benchmark_and_holds_inflight_until_done() {
        let port = slow_mock_worker(300);
        let state = Arc::new(state_with_local_worker("fp-w0", port, 3.6));
        assert!(!state.bench_cancel.load(SeqCst));
        let st = state.clone();
        let t =
            std::thread::spawn(move || execute_offer_locally(&st, &pin_offer("inflight-offer")));
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert_eq!(state.inflight.load(SeqCst), 1, "offer is paid work");
        assert!(state.bench_cancel.load(SeqCst), "offer cancels the bench");
        t.join().unwrap().unwrap();
        assert_eq!(state.inflight.load(SeqCst), 0);
        assert!(state.last_busy.load(SeqCst) > 0, "holds the next run off");
    }

    #[test]
    fn unauthenticated_paid_requests_never_cancel_a_benchmark() {
        let state = Arc::new(state_with_local_worker("fp-w0", 1, 3.6));
        state.set_local_mode(false);
        state.last_busy.store(1, SeqCst);
        for path in ["/execute", "/infer"] {
            let resp = handle(state.clone(), &anonymous_post(path), false);
            assert_eq!(resp.status, 401, "{path}");
            assert!(
                !state.bench_cancel.load(SeqCst),
                "{path} cancelled the bench"
            );
            assert_eq!(state.last_busy.load(SeqCst), 1, "{path} touched last_busy");
        }
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let resp = rt.block_on(handle_execute_batch(
            state.clone(),
            anonymous_post("/execute/batch"),
            false,
        ));
        assert_eq!(resp.status, 401);
        assert!(
            !state.bench_cancel.load(SeqCst),
            "batch cancelled the bench"
        );
        assert_eq!(state.last_busy.load(SeqCst), 1);
    }

    #[test]
    fn an_authenticated_batch_authenticates_once() {
        let state = Arc::new(state_with_local_worker("fp-w0", 1, 3.6));
        state.set_local_mode(false);
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        for (token, mesh) in [("zk_once_v1_aa", false), ("zk_once_mesh_bb", true)] {
            let mut req = anonymous_post("/execute/batch");
            req.headers
                .push(("Authorization".into(), format!("Bearer {token}")));
            if mesh {
                req.headers
                    .push(("X-Zakuro-Placement".into(), "mesh".into()));
            }
            // The body is not a batch: the request fails after authentication.
            let resp = rt.block_on(handle_execute_batch(state.clone(), req, false));
            assert_eq!(resp.status, 400, "mesh={mesh}");
            assert_eq!(auth_count_hook::count(token), 1, "mesh={mesh}");
        }
    }

    #[test]
    fn an_authenticated_infer_takes_the_guard() {
        // Local mode: keyless is authenticated. The body is invalid, so the
        // request fails after the guard was taken and released.
        let state = Arc::new(state_with_local_worker("fp-w0", 1, 3.6));
        state.set_local_mode(true);
        let resp = handle(state.clone(), &anonymous_post("/infer"), false);
        assert_eq!(resp.status, 400);
        assert!(
            state.bench_cancel.load(SeqCst),
            "/infer must cancel the bench"
        );
        assert_eq!(state.inflight.load(SeqCst), 0);
    }
}

/// #384: in remote mode the user a request is billed to comes from the hub,
/// not from the shape of the Bearer key. Every key-resolving entry point
/// (`/execute`, `/execute/batch`, `/me`, the bearer-authenticated routes) is
/// driven here against a local mock hub.
#[cfg(test)]
mod hub_validated_keys_tests {
    use super::billing_price_pin_tests::state_with_local_worker;
    use super::*;
    use crate::broker::key_auth::test_hub::spawn;
    use crate::broker::Ledger;
    use std::sync::atomic::Ordering::SeqCst;
    use tiny_http::Method;

    const VICTIM: &str = "9000000001";

    fn post(path: &str, key: &str) -> BrokerRequest {
        BrokerRequest {
            method: Method::Post,
            path: path.to_string(),
            query: String::new(),
            headers: vec![("Authorization".into(), format!("Bearer {key}"))],
            body: b"{}".to_vec(),
            peer_addr: None,
        }
    }

    fn remote_state(hub_url: &str) -> Arc<BrokerState> {
        let mut raw = state_with_local_worker("fp-w0", 1, 3.6);
        raw.ledger = Ledger::new(Some(hub_url.to_string()), Some("svc-key".to_string()));
        raw.set_local_mode(false);
        raw.ledger.local_credits.insert(VICTIM.to_string(), 100.0);
        Arc::new(raw)
    }

    fn victim_untouched(state: &BrokerState) {
        assert_eq!(
            state.ledger.local_credits.get(VICTIM).map(|v| *v),
            Some(100.0),
            "nothing may be reserved or billed for the uid a forged key names"
        );
    }

    fn batch(state: &Arc<BrokerState>, key: &str) -> BrokerResponse {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(handle_execute_batch(
                state.clone(),
                post("/execute/batch", key),
                false,
            ))
    }

    #[test]
    fn forged_key_with_a_real_uid_is_401_on_every_billing_entry_point() {
        let real = format!("zk_{VICTIM}_realsecret");
        let forged = format!("zk_{VICTIM}_forgedsecret");
        let hub = spawn(vec![(Box::leak(real.into_boxed_str()), VICTIM)]);
        let state = remote_state(&hub.url);

        for path in ["/execute", "/me"] {
            let method = if path == "/me" {
                Method::Get
            } else {
                Method::Post
            };
            let mut req = post(path, &forged);
            req.method = method;
            let resp = handle(state.clone(), &req, false);
            assert_eq!(resp.status, 401, "{path}");
            victim_untouched(&state);
        }
        assert_eq!(batch(&state, &forged).status, 401, "/execute/batch");
        victim_untouched(&state);
        assert_eq!(
            state
                .workers
                .list()
                .iter()
                .map(|w| w.total_requests)
                .sum::<u64>(),
            0,
            "no work may have been dispatched"
        );
    }

    #[test]
    fn unreachable_hub_is_503_not_the_keys_shape() {
        let state = remote_state("http://127.0.0.1:1");
        let key = format!("zk_{VICTIM}_whatever");
        assert_eq!(
            handle(state.clone(), &post("/execute", &key), false).status,
            503
        );
        assert_eq!(batch(&state, &key).status, 503);
        victim_untouched(&state);
    }

    #[test]
    fn a_key_the_hub_confirms_is_identified_once_then_served_from_cache() {
        let key = format!("zk_{VICTIM}_realsecret");
        let hub = spawn(vec![(Box::leak(key.clone().into_boxed_str()), VICTIM)]);
        let state = remote_state(&hub.url);
        let req = post("/execute", &key);
        assert_eq!(
            authenticated_user(&state, &req).ok().flatten().as_deref(),
            Some(VICTIM)
        );
        assert_eq!(
            authenticated_user(&state, &req).ok().flatten().as_deref(),
            Some(VICTIM)
        );
        assert_eq!(hub.hits.load(SeqCst), 1);
    }

    #[test]
    fn a_valid_key_passes_authentication_on_the_batch_route() {
        let key = format!("zk_{VICTIM}_realsecret");
        let hub = spawn(vec![(Box::leak(key.clone().into_boxed_str()), VICTIM)]);
        let state = remote_state(&hub.url);
        // `{}` is not a batch: it fails with 400 AFTER authentication.
        assert_eq!(batch(&state, &key).status, 400);
    }
}

/// The shared peer-offer executor (zc#423): the core both HTTP and QUIC offers
/// run through once their gates pass.
#[cfg(test)]
mod peer_offer_core_tests {
    use super::billing_price_pin_tests::{pin_offer, slow_mock_worker, state_with_local_worker};
    use super::{execute_feed_offer, run_peer_offer, PeerOfferOutcome};
    use crate::broker::task_board;

    fn vouched(task_id: &str, nonce: &str) -> task_board::TaskOffer {
        task_board::TaskOffer {
            voucher_signed_json: format!(
                r#"{{"v":1,"requester_user":"u","budget_credits":1000000.0,"task_nonce":"{nonce}","exp":9999999999}}"#
            ),
            voucher_sig: "unchecked-here".into(),
            ..pin_offer(task_id)
        }
    }

    /// With vouchers not required nothing is claimed, so an unarmed broker
    /// keeps running repeated offers exactly as before.
    #[test]
    fn unarmed_brokers_claim_no_voucher() {
        let state = state_with_local_worker("core-w0", slow_mock_worker(0), 1.0);
        for id in ["a", "b"] {
            assert!(matches!(
                run_peer_offer(&state, &vouched(id, "n1"), false),
                Ok(PeerOfferOutcome::Executed(_))
            ));
        }
        assert!(state.claimed_voucher_nonces.is_empty());
    }

    /// Armed: the nonce is taken once; a second offer under it is refused
    /// with the gate's wording, and a different nonce still runs.
    #[test]
    fn armed_brokers_refuse_a_second_offer_under_one_voucher() {
        let state = state_with_local_worker("core-w1", slow_mock_worker(0), 1.0);
        assert!(run_peer_offer(&state, &vouched("a", "n1"), true).is_ok());
        let rej = run_peer_offer(&state, &vouched("b", "n1"), true).unwrap_err();
        assert_eq!(rej.task_id, "b");
        assert!(
            rej.reason.starts_with("voucher check failed"),
            "{}",
            rej.reason
        );
        assert!(run_peer_offer(&state, &vouched("c", "n2"), true).is_ok());
    }

    /// A claim lapses with its voucher: an expired nonce is pruned on the next
    /// claim (the voucher gate already refuses an expired voucher).
    #[test]
    fn claims_are_pruned_once_their_voucher_expires() {
        let state = state_with_local_worker("core-w2", slow_mock_worker(0), 1.0);
        state.claimed_voucher_nonces.insert("old".into(), 1);
        assert!(run_peer_offer(&state, &vouched("a", "n1"), true).is_ok());
        assert!(!state.claimed_voucher_nonces.contains_key("old"));
        assert!(state.claimed_voucher_nonces.contains_key("n1"));
    }

    /// The task feed has no commit message: it refuses a two-phase offer
    /// without reserving a worker or claiming its voucher.
    #[test]
    fn the_task_feed_refuses_two_phase_offers_without_reserving() {
        let state = state_with_local_worker("core-w3", slow_mock_worker(0), 1.0);
        let offer = task_board::TaskOffer {
            two_phase: true,
            ..vouched("a", "n1")
        };
        let rej = execute_feed_offer(&state, &offer, true).unwrap_err();
        assert!(rej.reason.contains("two-phase"), "{}", rej.reason);
        assert!(state.pending_offers.is_empty());
        assert!(state.claimed_voucher_nonces.is_empty());
        assert!(execute_feed_offer(&state, &vouched("b", "n1"), true).is_ok());
    }
}

/// zc#426: which `/peer/*` routes skip the node-signature gate. Outbound
/// callers may leave exactly these unsigned (`peer::NODE_SIG_EXEMPT_ROUTES`);
/// this pins the client's list to what the server actually does.
#[cfg(test)]
mod peer_route_gate_tests {
    use super::{handle, BrokerRequest, BrokerState};
    use crate::broker::peer::NODE_SIG_EXEMPT_ROUTES;
    use crate::broker::BrokerConfig;
    use std::sync::Arc;
    use tiny_http::Method;

    /// Every `/peer/*` route in [`handle`]'s match, read from this file so a
    /// new route cannot be added without this test seeing it.
    fn routed_peer_paths() -> Vec<(String, String)> {
        let src = include_str!("server.rs");
        let mut out = Vec::new();
        for line in src.lines() {
            let t = line.trim_start();
            let Some(rest) = t.strip_prefix("(Method::") else {
                continue;
            };
            let Some((method, rest)) = rest.split_once(',') else {
                continue;
            };
            let path = match rest.trim_start().strip_prefix('"') {
                Some(r) => r.split('"').next().unwrap_or(""),
                // `(Method::Get, p) if p.starts_with("/peer/balance")`
                None => match rest.split_once("starts_with(\"") {
                    Some((_, r)) => r.split('"').next().unwrap_or(""),
                    None => continue,
                },
            };
            if path.starts_with("/peer/") {
                out.push((method.to_uppercase(), path.to_string()));
            }
        }
        out
    }

    #[test]
    fn peer_routes_exempt_from_node_sig_match_the_client_list() {
        let st = BrokerState::with_config(BrokerConfig {
            enable_p2p: true,
            peer_key: Some("k".into()),
            ..Default::default()
        });
        st.enforce_node_sig_override.set(true).unwrap();
        let st = Arc::new(st);

        let routes = routed_peer_paths();
        assert!(routes.len() >= 13, "route scan found too few: {routes:?}");
        for (method, path) in &routes {
            let req = BrokerRequest {
                method: if method == "POST" {
                    Method::Post
                } else {
                    Method::Get
                },
                path: path.clone(),
                query: String::new(),
                headers: vec![
                    ("X-Peer-Key".into(), "k".into()),
                    ("Content-Type".into(), "application/json".into()),
                ],
                body: b"{}".to_vec(),
                peer_addr: Some("127.0.0.1:1".parse().unwrap()),
            };
            let resp = handle(st.clone(), &req, false);
            let exempt = NODE_SIG_EXEMPT_ROUTES.contains(&path.as_str());
            assert_eq!(
                resp.status == 401,
                !exempt,
                "{method} {path}: unsigned request under an armed gate answered {} \
                 (exempt list says exempt={exempt}): {}",
                resp.status,
                String::from_utf8_lossy(&resp.body)
            );
        }
    }
}