zc2 0.0.29

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
//! 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,
    ledger, node_identity,
    peer::{self, Authority},
    recovery,
    router::{ResourceRequirements, RoutingDecision},
    stats::{StatsResponse, TaskOfferRecord, TransactionRecord, TransactionStatus, WorkerStats},
    task_board,
    wal::{WalEntry, WalStatus},
    worker::{self, ModelResolveError, Worker, WorkerHeartbeat, 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())
    }
}

/// 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>,
    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>,
}

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

/// 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)
}

/// 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(), "UNAUTHORIZED", 401)),
            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,
) -> 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(),
        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()),
    }
}

/// 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()
}

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),

        // 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" },
                }),
                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="));
            // 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);
                    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)
                        }
                    },
                }
            }
        }

        // 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
                    .iter()
                    .map(|entry| {
                        serde_json::json!({
                            "instance_id": entry.key().clone(),
                            "worker_id": entry.value().clone(),
                        })
                    })
                    .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,
                                        "",
                                        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(), "UNAUTHORIZED", 401),
                    },
                    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)
}

/// 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) {
    if !voucher_required() || offer.voucher_signed_json.is_empty() {
        return;
    }
    let nonce = match serde_json::from_str::<serde_json::Value>(&offer.voucher_signed_json) {
        Ok(v) => v
            .get("task_nonce")
            .and_then(|n| n.as_str())
            .map(|s| s.to_string()),
        Err(_) => None,
    };
    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> {
    if !voucher_required() {
        return Ok(());
    }
    let pubkey = state
        .dash_voucher_pubkey
        .read()
        .ok()
        .and_then(|g| g.clone())
        .ok_or("no dashboard voucher pubkey cached yet")?;
    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);
    super::voucher::verify_voucher_now(
        &pubkey,
        &offer.voucher_signed_json,
        &offer.voucher_sig,
        price_estimate,
    )
    .map(|_| ())
}

/// 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.
fn node_sig_gate(state: &Arc<BrokerState>, request: &BrokerRequest) -> Option<BrokerResponse> {
    let enforce = std::env::var("ZAKURO_ENFORCE_NODE_SIG")
        .map(|v| v == "1" || v == "true")
        .unwrap_or(false);
    match check_node_sig(
        &state.node_roster,
        &state.node_sig_guard,
        request,
        node_identity::now_secs(),
    ) {
        Ok(_) => None,
        Err(e) => {
            if enforce {
                Some(error_response(
                    &format!("node signature check failed: {e}"),
                    "UNAUTHORIZED",
                    401,
                ))
            } 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
                    );
                }
                None
            }
        }
    }
}

/// 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,
}

/// A single entry in the `/brokers` listing: a key-derived, IP-free peer id.
#[derive(serde::Serialize)]
struct BrokersResponse {
    #[serde(rename = "self")]
    self_id: String,
    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);
            Some((fp_id, reachable))
        })
        .fold(Vec::<BrokerEntry>::new(), |mut acc, (fp_id, reachable)| {
            if seen.insert(fp_id.clone()) {
                acc.push(BrokerEntry {
                    id: fp_id,
                    reachable,
                });
            } else if reachable {
                if let Some(e) = acc.iter_mut().find(|e| e.id == fp_id) {
                    e.reachable = true;
                }
            }
            acc
        });

    json_response(
        &BrokersResponse {
            self_id: state.node_key.node_uri(),
            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.
fn infer_authenticate(
    state: &Arc<BrokerState>,
    request: &BrokerRequest,
) -> Result<Option<String>, BrokerResponse> {
    let bearer = request
        .header("Authorization")
        .and_then(|a| a.strip_prefix("Bearer ").map(|t| t.trim().to_string()))
        .filter(|t| !t.is_empty());

    if let Some(token) = bearer {
        state
            .ledger
            .resolve_user_from_api_key(&token)
            .map(Some)
            .map_err(|e| error_response(&e.to_string(), "UNAUTHORIZED", 401))
    } 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,
        ))
    }
}

/// 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(),
                    duration_ms: Some(duration_ms),
                    timestamp: chrono::Utc::now(),
                    status: WalStatus::Earned,
                });
            }
            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,
            });
        }
        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,
                });
            }
        }
    }
    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 infer_authenticate(state, request) {
        Ok(uid) => uid,
        Err(resp) => return resp,
    };

    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.
            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)
                        }
                    };
                    // 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,
                    });
                    // ── 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,
                                    &worker.id,
                                    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);
                                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,
                                });
                                0.0
                            }
                        }
                    }
                }
                None => 0.0,
            };
            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,
            )
        }
        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);
    }

    #[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())
        .map(|w| worker_to_info(w, &state.workers, &state.node_key, 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(),
    };

    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(),
            duration_ms: Some(req.duration_ms),
            timestamp: chrono::Utc::now(),
            status: WalStatus::Earned,
        });
    }

    // 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,
    });
    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,
    };

    json_response(&identity, 200)
}

/// Select a matching local worker for an offer (same filters as one-phase
/// execution), round-robin. None when no local worker matches.
fn select_local_worker_for_offer(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
) -> Option<Worker> {
    // NOTE: `offer.target_worker` is intentionally NOT consulted here. Worker
    // selection is this broker's private authority — a client (or a peer
    // relaying a client's request) never names a worker directly. See
    // docs/superpowers/specs/2026-07-11-zc-key-derived-identity-amendment.md
    // "Routing addendum".
    let local_workers: Vec<Worker> = state
        .workers
        .healthy()
        .into_iter()
        .filter(|w| state.is_local_worker(&w.uri))
        .filter(|w| w.pricing.price_per_hour <= offer.max_price_per_hour)
        .filter(|w| {
            offer
                .worker_type
                .as_ref()
                .is_none_or(|wt| w.worker_type.as_str() == wt.as_str())
        })
        .collect();
    if local_workers.is_empty() {
        return None;
    }
    let idx = (REQUEST_COUNTER.fetch_add(1, Ordering::SeqCst) as usize) % local_workers.len();
    Some(local_workers[idx].clone())
}

/// 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 =
        select_local_worker_for_offer(state, offer).ok_or_else(|| task_board::TaskReject {
            task_id: offer.task_id.clone(),
            reason: "No matching local worker".to_string(),
        })?;
    if !state.workers.try_reserve_quota(&worker.id) {
        return Err(task_board::TaskReject {
            task_id: offer.task_id.clone(),
            reason: "Worker quota exhausted".to_string(),
        });
    }
    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);
    }
}

/// 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. Used by HTTP peer offer and by subscription client.
pub fn execute_offer_locally(
    state: &BrokerState,
    offer: &task_board::TaskOffer,
) -> Result<task_board::TaskResult, task_board::TaskReject> {
    let worker =
        select_local_worker_for_offer(state, offer).ok_or_else(|| task_board::TaskReject {
            task_id: offer.task_id.clone(),
            reason: "No matching local worker".to_string(),
        })?;
    run_offer_on(state, offer, &worker)
}

/// 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,
) -> 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);

    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);
            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),
    };

    // 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 select_local_worker_for_offer).

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

    if offer.two_phase {
        // Two-phase: RESERVE a worker slot and return an accept; do NOT execute
        // until a commit arrives. A cancel (or TTL sweep) releases the slot.
        match reserve_offer(&state, &offer) {
            Ok(accept) => json_response(&accept, 200),
            Err(reject) => json_response(&reject, 404),
        }
    } else {
        // One-phase (legacy / non-capable peers): execute immediately.
        match execute_offer_locally(&state, &offer) {
            Ok(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) {
                Ok(result) => json_response(&result, 200),
                Err(reject) => json_response(&reject, 404),
            },
            None => 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> {
    if effective_timeout > 0.0 {
        agent
            .post(worker_uri)
            .config()
            .timeout_global(Some(std::time::Duration::from_secs_f64(
                effective_timeout + 5.0,
            )))
            .build()
            .header("Content-Type", "application/octet-stream")
            .header("X-Zakuro-Request-Id", request_id)
            .header(
                "X-Zakuro-Timeout-Secs",
                &format!("{:.1}", effective_timeout),
            )
            .send(body)
    } else {
        agent
            .post(worker_uri)
            .header("Content-Type", "application/octet-stream")
            .header("X-Zakuro-Request-Id", request_id)
            .send(body)
    }
}

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

async fn forward_to_worker_async(
    client: &reqwest::Client,
    worker_uri: &str,
    body: Vec<u8>,
    request_id: &str,
    effective_timeout: f64,
) -> Result<WorkerReply, String> {
    let mut req = client
        .post(worker_uri)
        .header("Content-Type", "application/octet-stream")
        .header("X-Zakuro-Request-Id", request_id)
        .body(body);
    if effective_timeout > 0.0 {
        req = req
            .header("X-Zakuro-Timeout-Secs", format!("{:.1}", effective_timeout))
            .timeout(std::time::Duration::from_secs_f64(effective_timeout + 5.0));
    }
    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 {
    use std::io::Read as _;
    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,
    }
}

/// 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,
    p: PreparedForward,
    forward: Result<WorkerReply, String>,
) -> BrokerResponse {
    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: mark as committed
            if !p.is_local {
                let _ = state.wal.update_status(
                    &p.request_id,
                    WalStatus::Committed,
                    Some(actual_cost),
                    Some(duration_ms),
                );
            }

            // 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());
                }
            }

            // 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"),
            ];
            let mut resp = BrokerResponse {
                status: 200,
                headers: Vec::new(),
                body: response_body,
            };
            resp.headers.extend(headers);
            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,
                            });
                        }
                        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(
                                &p.request_id,
                                &p.user_id,
                                "commit",
                                timeout_cost,
                                p.balance_before - timeout_cost,
                                &p.worker.id,
                                duration_ms,
                                state.config.node_name.as_deref(),
                            );
                        }
                        Authority::Standalone => {
                            let _ = state.ledger.commit(&p.reservation_id, timeout_cost);
                            state.ledger.publish_transaction(
                                &p.request_id,
                                &p.user_id,
                                "commit",
                                timeout_cost,
                                p.balance_before - timeout_cost,
                                &p.worker.id,
                                duration_ms,
                                state.config.node_name.as_deref(),
                            );
                        }
                    }
                    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(
                    &state.http_client,
                    &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()
                        };

                        if !p.is_local {
                            let _ = state.wal.update_status(
                                &p.request_id,
                                WalStatus::Executed,
                                Some(actual_cost),
                                Some(retry_duration_ms),
                            );
                            let _ = state.wal.update_status(
                                &p.request_id,
                                WalStatus::Committed,
                                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,
                        });

                        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)),
                        ];
                        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,
    });
    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_name: &str,
    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_name,
            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_name.to_string(),
            duration_ms,
            source_node: state.config.node_name.clone(),
            worker_name: Some(executor_worker_name.to_string()),
            worker_uri: None,
            price_per_hour: 0.0,
        });
    }
}

/// 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())
}

#[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 {
        state.ledger.publish_transaction(
            request_id,
            user_id,
            "commit",
            0.0,
            balance_before,
            &worker.id,
            duration_ms,
            state.config.node_name.as_deref(),
        );
        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,
            });
        }
        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,
            });
            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.
            // Self-executed for a foreign requester: the executor is this very
            // broker, so pay the owner here and redeem — no peer hop to resolve.
            if executor_is_self(state, worker) {
                settle_self_payout(
                    state,
                    user_id,
                    actual_cost,
                    commission_c,
                    worker,
                    request_id,
                    duration_ms,
                );
                redeem_task_nonce(state, voucher_task_nonce, actual_cost);
                return balance;
            }
            let exec_fp = executor_fp(worker);
            match exec_fp.and_then(|fp| state.peer_manager.get_url_for_fingerprint(fp)) {
                Some(peer_url) => {
                    settle_executor_payout(
                        state,
                        user_id,
                        actual_cost,
                        commission_c,
                        &peer_url,
                        &worker.id,
                        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}"),
                            }
                        }
                    }
                }
                None => {
                    // 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,
                        });
                    }
                }
            }
            balance
        }
        peer::Authority::Peer(url) => {
            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,
                        });
                        Some(resp.balance_after)
                    }
                    Err(e) => {
                        eprintln!(
                            "  [P2P] Peer commit failed ({}), falling back to local: {}",
                            url, e
                        );
                        None
                    }
                }
            } else {
                None
            };
            match peer_balance {
                Some(b) => b,
                None => {
                    state.ledger.publish_transaction(
                        request_id,
                        user_id,
                        "commit",
                        actual_cost,
                        balance_before - actual_cost,
                        &worker.id,
                        duration_ms,
                        state.config.node_name.as_deref(),
                    );
                    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
                        }
                    }
                }
            }
        }
        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,
            });
            // P2P off (single broker, billing on): a foreign requester's job on
            // this node's worker still pays the owner and the platform.
            if executor_is_self(state, worker) {
                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
        }
    }
}

/// 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,
        });
        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(),
        duration_ms: Some(duration_ms),
        timestamp: chrono::Utc::now(),
        status: WalStatus::Earned,
    });
    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,
    });
    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)
    }
}

/// 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();

    // ── 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();
    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).
    if let Some(ref qt) = 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;
    if winning_peer.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);
                });
                let deadline = peer_dispatch_deadline(offer.timeout_secs);
                if let Ok(Ok(result)) = rx.recv_timeout(deadline) {
                    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).
    let broadcast_peer_urls = broadcast_targets(&peer_urls, 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 peer_quic_port = state_c.peer_manager.get_quic_port(&peer_url);
                let (offer_result, transport_used) =
                    if let (Some(ref qt), p) = (&quic_c, peer_quic_port) {
                        if p > 0 {
                            (quic_offer(qt, &peer_url, p, &offer_c), "quic".to_string())
                        } else if let Some(client) = state_c.peer_manager.get_client(&peer_url) {
                            (client.offer_task(&offer_c), "http".to_string())
                        } else {
                            (Err("peer unreachable".into()), String::new())
                        }
                    } else if let Some(client) = state_c.peer_manager.get_client(&peer_url) {
                        (client.offer_task(&offer_c), "http".to_string())
                    } else {
                        (Err("peer unreachable".into()), String::new())
                    };
                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.
        let deadline = peer_dispatch_deadline(offer.timeout_secs);
        let dispatch_start = Instant::now();
        for _ in 0..broadcast_peer_urls.len() {
            let remaining = deadline.saturating_sub(dispatch_start.elapsed());
            match rx.recv_timeout(remaining) {
                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;

        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,
            });
        }

        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,
                &result.worker_name,
                request_id,
                duration_ms,
            );
        }

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

        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()),
        ];
        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)
}

/// 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,
}

/// 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_pubkey = state
        .dash_voucher_pubkey
        .read()
        .ok()
        .and_then(|g| g.clone())
        .ok_or_else(|| {
            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_pubkey, &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
}

/// 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) -> Prepared {
    let start = Instant::now();
    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");

    // Resolve user ID: prefer a Bearer token, else fall back to X-Zakuro-User.
    // A non-empty Bearer token must validate; an empty/whitespace token (e.g. a
    // client that built `Authorization: Bearer ` from an empty env var) is
    // treated as no token and falls through to the keyless path below.
    let bearer = request
        .header("Authorization")
        .and_then(|a| a.strip_prefix("Bearer ").map(|t| t.trim().to_string()))
        .filter(|t| !t.is_empty());

    // Kept for voucher minting: a foreign requester's voucher is minted under
    // THEIR credential (see `mint_and_verify_voucher`).
    let requester_key: Option<String> = bearer.clone();
    let user_id = if let Some(token) = bearer {
        match state.ledger.resolve_user_from_api_key(&token) {
            Ok(uid) => uid,
            Err(e) => return Prepared::Done(error_response(&e.to_string(), "UNAUTHORIZED", 401)),
        }
    } else if state.is_local_mode() {
        // No Bearer token: trust the X-Zakuro-User header only in local mode,
        // where execution is single-node and free. Remote mode ALWAYS requires a
        // Bearer token, independent of whether billing is enabled — auth must not
        // be coupled to billing state (audit M2). An authenticated user on a
        // billing-disabled remote broker still executes free: the credit-check
        // gate below is separately skipped when billing is off.
        request
            .header("X-Zakuro-User")
            .unwrap_or_else(|| "anonymous".to_string())
    } else {
        // Remote mode: require an API key whether or not billing is enabled.
        return Prepared::Done(error_response(
            "API key required. Set Authorization: Bearer <key>",
            "UNAUTHORIZED",
            401,
        ));
    };

    // 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,
            ));
        }
    }

    // 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) => {
            // Non-authoritative: ask peer, fall back to local
            if let Some(client) = state.peer_manager.get_client(url) {
                client
                    .get_balance(&user_id)
                    .unwrap_or_else(|_| state.ledger.get_balance(&user_id))
            } else {
                state.ledger.get_balance(&user_id)
            }
        }
        Authority::Standalone => state.ledger.load_balance_if_needed(&user_id),
    };

    // 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 instance_action.as_deref() == Some("call_method") {
        if let Some(ref iid) = instance_id {
            if let Some(worker_id) = state.instance_registry.get(iid) {
                state.workers.get(worker_id.value())
            } 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 state
            .router
            .select_worker_no_checks(&state.workers, &requirements)
        {
            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());
            state
                .router
                .select_local_worker(&state.workers, live_ts_ip.as_deref(), &requirements)
                .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(),
                };
                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 state.router.select_worker(
            &state.workers,
            &state.credits,
            &user_id,
            balance_before,
            &requirements,
        ) {
            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" => 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 is_local = !state.is_billing_enabled() || is_self_owned;
    let self_executed =
        executor_is_self(state, &routing.worker) || state.is_local_worker(&routing.worker.uri);

    // 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`).
    //
    // Only `Authority::Local` settles commission here (`commit_credits`'s
    // `Authority::Local` branch is the sole redeem/settle site). For
    // `Authority::Peer`/`Standalone` this broker is NOT the settlement
    // authority, so minting a voucher would consume a dashboard nonce that is
    // never redeemed and the job would run uncommissioned. Fail-closed: reject
    // such a remote job under `voucher_required()` rather than mint-and-waste
    // or run for free. A mint or verification failure likewise REJECTS.
    //
    // A SELF-EXECUTED job (this broker's own worker) is settled right here on
    // every authority path — there is no remote executor to pay, the owner is
    // credited on this ledger — so it is minted (under the requester's own
    // credential) and redeemed here regardless of `authority`.
    let (commission_c, voucher_task_nonce): (f64, String) = if !is_local && voucher_required() {
        if self_executed || matches!(authority, Authority::Local) {
            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),
            }
        } else {
            return Prepared::Done(error_response(
                "Voucher required for remote dispatch but this broker is not the \
                 settlement authority for the requester; refusing to run uncommissioned",
                "VOUCHER_NON_LOCAL_AUTHORITY",
                503,
            ));
        }
    } else {
        (0.0, String::new())
    };

    // 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(),
            duration_ms: None,
            timestamp: chrono::Utc::now(),
            status: WalStatus::Reserved,
        });
    }

    // 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());

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

    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,
    })
}

fn handle_execute(
    state: Arc<BrokerState>,
    request: &BrokerRequest,
    verbose: bool,
) -> BrokerResponse {
    let p = match execute_prepare(&state, request, verbose) {
        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(
        &state.http_client,
        &p.worker_uri,
        &p.body,
        &p.request_id,
        p.effective_timeout,
    )
    .map(into_worker_reply)
    .map_err(|e| e.to_string());

    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,
        //   * 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.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()
            // ── 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 breq = BrokerRequest::from_axum(req, Some(peer)).await;
                            // Phase 1: auth, routing, WAL reserve — synchronous/blocking.
                            let prepared =
                                if inline_execute {
                                    execute_prepare(&state, &breq, verbose)
                                } else {
                                    let st = state.clone();
                                    match tokio::task::spawn_blocking(move || {
                                        execute_prepare(&st, &breq, verbose)
                                    })
                                    .await
                                    {
                                        Ok(p) => p,
                                        Err(_) => return BrokerResponse::json_bytes(
                                            br#"{"error":"handler panicked","code":"INTERNAL"}"#
                                                .to_vec(),
                                            500,
                                        )
                                        .into_response(),
                                    }
                                };
                            let 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(
                                &state.async_http,
                                &p.worker_uri,
                                p.body.clone(),
                                &p.request_id,
                                p.effective_timeout,
                            )
                            .await;
                            // 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 broker server
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.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. Can be disabled
    // (ZAKURO_DISABLE_QUIC=1) to force the HTTP offer path in environments where
    // UDP/QUIC between nodes is blocked or unreliable.
    let quic_disabled = std::env::var("ZAKURO_DISABLE_QUIC")
        .map(|v| v == "1" || v == "true")
        .unwrap_or(false);
    if state.peer_manager.is_enabled() && !quic_disabled {
        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_offer_locally),
                );
            }
            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();
        });
    }

    // 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.
                        let endpoint =
                            mesh_endpoint_for(crate::vpn::native::mesh_ip(), 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 zakuro0 address - registering without a mesh endpoint"
                            ),
                            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}");
                        }
                        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 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 tick registered while this peer was
                                    // still unreachable (below).
                                    if state_clone
                                        .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 tick after the
                                    // configured peer answers a probe.
                                    state_clone
                                        .peer_manager
                                        .register_roster_peer(rp.url.clone());
                                    keep.insert(rp.url.clone());
                                }

                                // Peers are now 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.
                                let evicted =
                                    state_clone.peer_manager.retain_roster_peers(&keep);
                                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(pk) => {
                                if let Ok(mut w) = state_clone.dash_voucher_pubkey.write() {
                                    *w = Some(pk);
                                }
                            }
                            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(|_, worker_id| !unhealthy_ids.contains(worker_id));
                }

                // Flush transaction buffer every tick — regardless of P2P mode.
                // Both P2P (local_reserve path) and Standalone (reserve path) queue to tx_buffer;
                // without this flush non-P2P billing transactions would be silently lost.
                if let (Some(ref api_url), Some(ref api_key)) =
                    (&state_clone.config.api_url, &state_clone.config.api_key)
                {
                    state_clone
                        .tx_buffer
                        .flush_to_api(api_url, api_key, &state_clone.wal);
                }
                // 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);
                    }
                }
            }

            // Graceful shutdown: flush remaining transactions (always, not just in P2P mode)
            if let (Some(ref api_url), Some(ref api_key)) =
                (&state_clone.config.api_url, &state_clone.config.api_key)
            {
                eprintln!("  [FLUSH] Shutdown: flushing remaining transactions...");
                state_clone
                    .tx_buffer
                    .flush_to_api(api_url, api_key, &state_clone.wal);
            }
            if let Err(e) = state_clone.wal.flush_buffer() {
                eprintln!("  [WAL] flush_buffer failed: {}", e);
            }
        })
        .expect("failed to spawn zc-cleanup thread");

    // 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 = detect_discovery_mode(&discovery_config.subnet);

        // 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 cleanup thread may still be mid-sleep before
    // it notices and runs the graceful-shutdown flush block — so join it
    // here rather than letting `main()` exit out from under it and lose
    // buffered transactions.
    let serve_result = serve_axum(state, bind_host, bind_port, verbose, running);
    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);
    }
}

#[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);
        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);
        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);
        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);
        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);
        assert_eq!(ci.node.as_deref(), Some(key.node_uri().as_str()));
    }

    #[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\""));
    }

    /// 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()]
        );
    }
}

#[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 = Some(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() = Some(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"));
    }
}

/// 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());
    }

    #[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)
            .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");
    }

    /// 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
    }

    /// The SECOND producer (`quic.rs::handle_stream`) cannot be driven by a unit
    /// test: it is parameterized on concrete `quinn::SendStream`/`RecvStream`
    /// rather than a trait, so exercising it needs a live QUIC endpoint pair
    /// (TLS config, certs, connection handshake) that does not exist in this
    /// suite. This is a TEXTUAL guard, strictly weaker than the behavioural one
    /// above — it detects the specific reviewer-demonstrated regression
    /// (`worker.uri` back in the mesh-facing handle) but cannot prove the
    /// emitted value in general. Replace it with a real driving test if a QUIC
    /// harness ever lands.
    #[test]
    fn quic_producer_emits_identity_not_worker_uri() {
        let src = include_str!("quic.rs");
        assert!(
            src.contains("let wuri = worker.zc_uri();"),
            "quic.rs producer must derive its mesh-facing handle from Worker::zc_uri()"
        );
        assert!(
            !src.contains("let wuri = worker.uri"),
            "quic.rs producer must not put the dialable worker.uri on the wire"
        );
        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;

    /// 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)
    }

    /// 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}"
        );
    }
}

/// 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 /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;

    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).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"
        );
    }
}

/// 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",
            "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");
    }
}