ghostlink-core 1.17.0

Core runtime primitives for Ghostlink, including planning, routing, health monitoring, and transport logic for distributed inference workloads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
//! Distributed inference runtime scaffolding.
//!
//! This module provides lightweight execution planning primitives that bridge
//! placement plans to token-step pipeline schedules across heterogeneous devices.

use crate::circuit_breaker::CircuitBreaker;
use crate::planning::LayerAssignment;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::io::{self, Read, Write};
use std::io::{BufReader, BufWriter};
use std::net::{Shutdown as TcpShutdown, SocketAddr, TcpListener, TcpStream};
use std::path::PathBuf;
use std::slice;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use std::time::Instant;

#[cfg(unix)]
#[cfg(unix)]
use std::net::Shutdown as UnixSocketShutdown;
#[cfg(unix)]
use std::os::unix::net::{UnixListener, UnixStream};

/// Execution target selected for a pipeline stage.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeviceKind {
    Npu,
    Gpu,
    Cpu,
}

impl DeviceKind {
    /// Human-friendly label.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Npu => "NPU",
            Self::Gpu => "GPU",
            Self::Cpu => "CPU",
        }
    }
}

/// Placement of one contiguous layer range onto a node and device.
#[derive(Clone, Debug, PartialEq)]
pub struct StagePlacement {
    pub node_id: String,
    pub start_layer: usize,
    pub end_layer: usize,
    pub device: DeviceKind,
    /// Estimated compute latency for one micro-batch token step.
    pub est_latency_ms: f32,
}

impl StagePlacement {
    pub fn num_layers(&self) -> usize {
        self.end_layer.saturating_sub(self.start_layer)
    }
}

/// Pipeline execution plan for one model.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PipelinePlan {
    pub stages: Vec<StagePlacement>,
}

impl PipelinePlan {
    /// Build a pipeline plan from layer assignments and a node/device map.
    pub fn from_assignments(
        assignments: &[LayerAssignment],
        device_by_node: &std::collections::HashMap<String, DeviceKind>,
    ) -> Self {
        Self::from_assignments_with_measured(assignments, device_by_node, &Default::default())
    }

    /// Build a pipeline plan using measured latencies from cluster metrics if available.
    pub fn from_assignments_with_measured(
        assignments: &[LayerAssignment],
        device_by_node: &std::collections::HashMap<String, DeviceKind>,
        cluster: &crate::cluster::ClusterState,
    ) -> Self {
        let stages = assignments
            .iter()
            .map(|assignment| {
                let device = device_by_node
                    .get(&assignment.node_id)
                    .copied()
                    .unwrap_or(DeviceKind::Cpu);

                // Use measured latency if available (converted from us to ms per layer)
                let per_layer_cost_ms =
                    if let Some(metrics) = cluster.get_metrics(&assignment.node_id) {
                        if metrics.latency_samples > 0 && assignment.num_layers > 0 {
                            (metrics.avg_latency_us / 1000.0) / assignment.num_layers as f32
                        } else {
                            Self::default_cost_for_device(device)
                        }
                    } else {
                        Self::default_cost_for_device(device)
                    };

                StagePlacement {
                    node_id: assignment.node_id.clone(),
                    start_layer: assignment.start_layer,
                    end_layer: assignment.end_layer,
                    device,
                    est_latency_ms: per_layer_cost_ms * assignment.num_layers as f32,
                }
            })
            .collect();

        Self { stages }
    }

    fn default_cost_for_device(device: DeviceKind) -> f32 {
        match device {
            DeviceKind::Npu => 0.42,
            DeviceKind::Gpu => 0.55,
            DeviceKind::Cpu => 1.25,
        }
    }

    /// Return aggregate token-step latency estimate for one micro-batch.
    pub fn est_step_latency_ms(&self) -> f32 {
        self.stages.iter().map(|s| s.est_latency_ms).sum()
    }

    pub fn summary(&self) -> String {
        let mut out = String::from("Pipeline Plan\n");
        out.push_str("============\n");

        for (idx, stage) in self.stages.iter().enumerate() {
            out.push_str(&format!(
                "Stage {}: {} layers {}-{} on {} ({:.2} ms)\n",
                idx,
                stage.node_id,
                stage.start_layer,
                stage.end_layer,
                stage.device.as_str(),
                stage.est_latency_ms
            ));
        }

        out.push_str(&format!(
            "Estimated per-token step latency: {:.2} ms\n",
            self.est_step_latency_ms()
        ));
        out
    }
}

fn run_stage_compute(payload: &mut [f32], stage: &StagePlacement) {
    let base_rounds = stage.num_layers().max(1) / 4 + 1;
    let rounds = match stage.device {
        DeviceKind::Npu => base_rounds,
        DeviceKind::Gpu => base_rounds * 2,
        DeviceKind::Cpu => base_rounds * 3,
    };

    let alpha = match stage.device {
        DeviceKind::Npu => 1.001_f32,
        DeviceKind::Gpu => 1.003_f32,
        DeviceKind::Cpu => 1.005_f32,
    };

    for _ in 0..rounds {
        for value in payload.iter_mut() {
            *value = ((*value * alpha) + 0.125).sin();
        }
    }
}

/// Per-stage runtime telemetry captured from real in-process execution.
#[derive(Clone, Debug, PartialEq)]
pub struct StageExecutionStats {
    pub stage_idx: usize,
    pub processed_batches: usize,
    pub avg_compute_ms: f32,
    pub avg_recv_wait_ms: f32,
    pub avg_send_wait_ms: f32,
    pub avg_bridge_write_ms: f32,
    pub avg_bridge_read_ms: f32,
}

/// Aggregate runtime execution output.
#[derive(Clone, Debug, PartialEq)]
pub struct ExecutionResult {
    pub token_count: usize,
    pub micro_batch: usize,
    pub batch_count: usize,
    pub stage_count: usize,
    pub total_time_ms: f32,
    pub throughput_tokens_per_sec: f32,
    pub avg_token_latency_ms: f32,
    pub p95_token_latency_ms: f32,
    pub p99_token_latency_ms: f32,
    /// One entry per token, in completion order — the raw samples P95/P99
    /// are computed from. Exposed (rather than kept purely internal) so
    /// callers such as `ghost-link flow` can dump the real per-token
    /// latency distribution for a histogram, not just precomputed
    /// percentiles.
    pub token_latencies_ms: Vec<f32>,
    pub stage_stats: Vec<StageExecutionStats>,
}

/// Transport protocol selection for inter-stage bridges.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TransportKind {
    /// Standard TCP transport (works across machines).
    #[default]
    Tcp,
    /// Unix domain socket transport (loopback/local only, lower overhead).
    /// Supported on Linux, macOS, and Windows 10 build 1803+.
    Unix,
}

/// Unified transport listener wrapping platform-specific socket types.
#[derive(Debug)]
pub enum BridgeListener {
    Tcp(TcpListener),
    #[cfg(unix)]
    Unix(UnixListener),
}

impl BridgeListener {
    /// Accept an incoming connection. Returns the connected stream (peer addr discarded).
    pub fn accept(&self) -> io::Result<BridgeStream> {
        match self {
            BridgeListener::Tcp(l) => l.accept().map(|(s, _)| BridgeStream::Tcp(s)),
            #[cfg(unix)]
            BridgeListener::Unix(l) => l.accept().map(|(s, _)| BridgeStream::Unix(s)),
        }
    }
}

/// Unified transport stream wrapping platform-specific socket types.
pub enum BridgeStream {
    Tcp(TcpStream),
    #[cfg(unix)]
    Unix(UnixStream),
}

impl Read for BridgeStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            BridgeStream::Tcp(s) => s.read(buf),
            #[cfg(unix)]
            BridgeStream::Unix(s) => s.read(buf),
        }
    }
}

impl Write for BridgeStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            BridgeStream::Tcp(s) => s.write(buf),
            #[cfg(unix)]
            BridgeStream::Unix(s) => s.write(buf),
        }
    }
    fn flush(&mut self) -> io::Result<()> {
        match self {
            BridgeStream::Tcp(s) => s.flush(),
            #[cfg(unix)]
            BridgeStream::Unix(s) => s.flush(),
        }
    }
}

impl BridgeStream {
    /// Set TCP_NODELAY (no-op for Unix domain sockets).
    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        match self {
            BridgeStream::Tcp(s) => s.set_nodelay(nodelay),
            #[cfg(unix)]
            BridgeStream::Unix(_) => Ok(()),
        }
    }

    /// Set socket send buffer size (SO_SNDBUF). No-op on platforms without support.
    pub fn set_send_buffer_size(&self, _size: usize) -> io::Result<()> {
        match self {
            BridgeStream::Tcp(_s) => {
                // Platform-specific socket buffer tuning would go here
                // Omitted for portability - most OSes auto-tune well
                Ok(())
            }
            #[cfg(unix)]
            BridgeStream::Unix(_) => Ok(()),
        }
    }

    /// Set socket receive buffer size (SO_RCVBUF). No-op on platforms without support.
    pub fn set_recv_buffer_size(&self, _size: usize) -> io::Result<()> {
        match self {
            BridgeStream::Tcp(_s) => {
                // Platform-specific socket buffer tuning would go here
                // Omitted for portability - most OSes auto-tune well
                Ok(())
            }
            #[cfg(unix)]
            BridgeStream::Unix(_) => Ok(()),
        }
    }

    /// Shut down the write half of the connection.
    pub fn shutdown_write(&self) -> io::Result<()> {
        match self {
            BridgeStream::Tcp(s) => s.shutdown(TcpShutdown::Write),
            #[cfg(unix)]
            BridgeStream::Unix(s) => s.shutdown(UnixSocketShutdown::Write),
        }
    }
}

/// Unified transport address for TCP or Unix domain sockets.
#[derive(Clone, Debug)]
pub enum BridgeAddr {
    Tcp(SocketAddr),
    Unix(PathBuf),
}

/// Build a collision-free Unix socket path for an inter-stage bridge.
///
/// Paths must be unique per process AND per pipeline: a fixed name like
/// `ghostlink-bridge-0.sock` lets two concurrent pipelines delete each
/// other's live sockets and cross-connect their streams, which surfaces
/// as garbled frames (auth failures / bogus payload lengths) far from
/// the cause. PID plus a process-wide counter guarantees uniqueness;
/// callers still remove stale files defensively before binding.
#[cfg(unix)]
fn unique_bridge_socket_path(source_stage: usize) -> std::path::PathBuf {
    use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
    static BRIDGE_SOCKET_SEQ: AtomicU64 = AtomicU64::new(0);
    let seq = BRIDGE_SOCKET_SEQ.fetch_add(1, AtomicOrdering::Relaxed);
    let mut p = std::env::temp_dir();
    p.push(format!(
        "ghostlink-bridge-{}-{}-{}.sock",
        std::process::id(),
        seq,
        source_stage
    ));
    p
}

impl BridgeAddr {
    /// Connect to the address (with a timeout for TCP, instant for Unix).
    fn connect(&self, timeout: Duration) -> io::Result<BridgeStream> {
        match self {
            BridgeAddr::Tcp(addr) => {
                TcpStream::connect_timeout(addr, timeout).map(BridgeStream::Tcp)
            }
            #[cfg(unix)]
            BridgeAddr::Unix(path) => UnixStream::connect(path).map(BridgeStream::Unix),
            #[cfg(not(unix))]
            BridgeAddr::Unix(_) => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "Unix domain sockets require a Unix platform",
            )),
        }
    }
}

/// Runtime controls for TCP/Unix transport execution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TcpTransportConfig {
    pub max_inflight_batches: usize,
    pub reconnect_attempts: usize,
    pub reconnect_backoff_ms: u64,
    /// Per-batch HMAC-SHA256 auth token (legacy, use `auth_session_token` for performance).
    pub auth_token: Option<String>,
    /// Session-level auth token. Does a one-time HMAC handshake at connection setup,
    /// then verifies a lightweight monotonic sequence counter per batch. Much faster
    /// than per-batch HMAC while maintaining connection-level security.
    pub auth_session_token: Option<String>,
    pub use_mtls: bool,
    pub cert_chain_path: Option<String>,
    /// Transport protocol: `Tcp` (LAN) or `Unix` (loopback/local, lower overhead).
    pub transport: TransportKind,
    /// Socket send buffer size (SO_SNDBUF). 0 = system default.
    pub send_buffer_size: usize,
    /// Socket receive buffer size (SO_RCVBUF). 0 = system default.
    pub recv_buffer_size: usize,
    /// Use vectored I/O (writev/readv) for zero-copy header+payload writes.
    pub use_vectored_io: bool,
    /// Synthetic `f32` elements per token in the benchmark/demo payload these
    /// pipeline-execution paths generate — they move a stand-in payload
    /// through the real transport rather than real model activations (see
    /// `ghost-link::main`'s `flow` command). Defaults to 16 elements (64
    /// bytes/token), matching the historical hardcoded value so every
    /// existing caller keeps identical behavior; the `flow` CLI raises this
    /// to reflect a real FP16/BF16 hidden-state size (e.g. 4096 × 2 bytes ÷
    /// 4 bytes/f32 = 2048 elements/token for a 7B-class model).
    pub elems_per_token: usize,
}

impl Default for TcpTransportConfig {
    fn default() -> Self {
        Self {
            max_inflight_batches: 512,
            reconnect_attempts: 3,
            reconnect_backoff_ms: 25,
            auth_token: None,
            auth_session_token: None,
            use_mtls: false,
            cert_chain_path: None,
            transport: TransportKind::Tcp,
            send_buffer_size: 256 * 1024, // 256 KB
            recv_buffer_size: 256 * 1024, // 256 KB
            use_vectored_io: true,
            elems_per_token: 16,
        }
    }
}

/// Result of a one-time session auth handshake. Shared between reader and writer threads.
#[derive(Clone, Debug)]
struct SessionAuth {
    session_id: u64,
    seq: Arc<AtomicU64>,
    peer_seq: Arc<AtomicU64>,
}

impl ExecutionResult {
    pub fn summary(&self) -> String {
        let mut out = String::from("Execution Runtime\n");
        out.push_str("=================\n");
        out.push_str(&format!(
            "Tokens: {} | Micro-batch: {} | Batches: {} | Stages: {}\n",
            self.token_count, self.micro_batch, self.batch_count, self.stage_count
        ));
        out.push_str(&format!(
            "Measured wall-clock time: {:.2} ms\n",
            self.total_time_ms
        ));
        out.push_str(&format!(
            "Throughput: {:.2} tokens/sec\n",
            self.throughput_tokens_per_sec
        ));
        out.push_str(&format!(
            "Avg token latency: {:.2} ms | P95: {:.2} ms | P99: {:.2} ms\n",
            self.avg_token_latency_ms, self.p95_token_latency_ms, self.p99_token_latency_ms
        ));

        for stage in &self.stage_stats {
            out.push_str(&format!(
                "Stage {} batches={} compute={:.2} ms recv-wait={:.2} ms send-wait={:.2} ms bridge-write={:.2} ms bridge-read={:.2} ms\n",
                stage.stage_idx,
                stage.processed_batches,
                stage.avg_compute_ms,
                stage.avg_recv_wait_ms,
                stage.avg_send_wait_ms,
                stage.avg_bridge_write_ms,
                stage.avg_bridge_read_ms
            ));
        }

        out
    }
}

/// One scheduled operation in steady-state token generation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TokenStep {
    pub token_idx: usize,
    pub stage_idx: usize,
}

/// Generate a simple steady-state pipeline schedule preview.
///
/// For each token, all stages execute in order; this preview is useful for
/// verifying stage count and queue depth wiring before integrating transport.
pub fn build_token_schedule(stage_count: usize, token_count: usize) -> Vec<TokenStep> {
    let mut schedule = Vec::with_capacity(stage_count.saturating_mul(token_count));
    for token_idx in 0..token_count {
        for stage_idx in 0..stage_count {
            schedule.push(TokenStep {
                token_idx,
                stage_idx,
            });
        }
    }
    schedule
}

/// Execute pipeline stages with real channel/thread wiring for `token_count` tokens.
///
/// `micro_batch` controls how many tokens are packaged per batch. Values below
/// 1 are clamped to 1.
pub fn execute_pipeline(
    plan: &PipelinePlan,
    token_count: usize,
    micro_batch: usize,
) -> Result<ExecutionResult, String> {
    execute_pipeline_with_rebalance(plan, token_count, micro_batch, None)
}

pub fn execute_pipeline_with_rebalance(
    plan: &PipelinePlan,
    token_count: usize,
    micro_batch: usize,
    rebalance: Option<&crate::planning::RebalanceTrigger>,
) -> Result<ExecutionResult, String> {
    execute_pipeline_with_rebalance_and_measured(
        plan,
        token_count,
        micro_batch,
        rebalance,
        None,
        None,
    )
}

pub fn execute_pipeline_with_rebalance_and_measured(
    plan: &PipelinePlan,
    token_count: usize,
    micro_batch: usize,
    rebalance: Option<&crate::planning::RebalanceTrigger>,
    cluster: Option<&crate::cluster::ClusterState>,
    placement_context: Option<&crate::planning::PlacementPlan>,
) -> Result<ExecutionResult, String> {
    let stage_count = plan.stages.len();
    let micro_batch = micro_batch.max(1);
    let batch_count = token_count.div_ceil(micro_batch);
    if stage_count == 0 || token_count == 0 {
        return Ok(ExecutionResult {
            token_count,
            micro_batch,
            batch_count,
            stage_count,
            total_time_ms: 0.0,
            throughput_tokens_per_sec: 0.0,
            avg_token_latency_ms: 0.0,
            p95_token_latency_ms: 0.0,
            p99_token_latency_ms: 0.0,
            token_latencies_ms: Vec::new(),
            stage_stats: Vec::new(),
        });
    }

    #[derive(Debug)]
    struct BatchWork {
        tokens_in_batch: usize,
        started_at: Instant,
        payload: Vec<f32>,
    }

    #[derive(Debug)]
    struct StageAccumulator {
        stage_idx: usize,
        processed_batches: usize,
        total_compute_ms: f32,
        total_recv_wait_ms: f32,
        total_send_wait_ms: f32,
    }

    use crate::ring::{RingConfig, SpscRingBuffer};
    use std::sync::Arc;

    // Use zero-copy SPSC ring buffers for high-throughput in-memory execution.
    // Use default RingConfig (4095 capacity, 2867 backpressure threshold) for maximum batching.
    let ring_cfg = RingConfig::default();

    let mut rings = Vec::with_capacity(stage_count + 1);
    for _ in 0..=stage_count {
        rings.push(Arc::new(SpscRingBuffer::<BatchWork>::new(ring_cfg)));
    }

    // Return ring for recycling payload vectors to reduce allocation churn.
    let recycler_ring = Arc::new(SpscRingBuffer::<Vec<f32>>::new(ring_cfg));

    let mut stage_handles = Vec::with_capacity(stage_count);
    for stage_idx in 0..stage_count {
        let stage = plan.stages[stage_idx].clone();
        let rx_ring = Arc::clone(&rings[stage_idx]);
        let tx_ring = Arc::clone(&rings[stage_idx + 1]);

        let handle = thread::spawn(move || {
            let mut total_compute_ms = 0.0_f32;
            let mut total_recv_wait_ms = 0.0_f32;
            let mut total_send_wait_ms = 0.0_f32;

            // Fixed batch count avoids OS scheduler rendezvous — each stage spins
            // on wait_for_data() / wait_for_space() with exponential backoff, staying
            // hot on its core.
            for _ in 0..batch_count {
                let recv_start = Instant::now();
                rx_ring.wait_for_data();
                let mut batch = rx_ring.pop().unwrap();
                total_recv_wait_ms += recv_start.elapsed().as_secs_f32() * 1000.0;

                let compute_start = Instant::now();
                run_stage_compute(&mut batch.payload, &stage);
                total_compute_ms += compute_start.elapsed().as_secs_f32() * 1000.0;

                let send_start = Instant::now();
                tx_ring.wait_for_space();
                let _ = tx_ring.push(batch);
                total_send_wait_ms += send_start.elapsed().as_secs_f32() * 1000.0;
            }

            StageAccumulator {
                stage_idx,
                processed_batches: batch_count,
                total_compute_ms,
                total_recv_wait_ms,
                total_send_wait_ms,
            }
        });

        stage_handles.push(handle);
    }

    let completion_ring = Arc::clone(&rings[stage_count]);
    let entry_ring = Arc::clone(&rings[0]);
    // Clear rings vector so strong_count can drop once threads finish
    drop(rings);

    let recycler_ring_c = Arc::clone(&recycler_ring);
    let latencies_handle = thread::spawn(move || {
        let mut latencies = Vec::with_capacity(token_count);
        for _ in 0..batch_count {
            completion_ring.wait_for_data();
            if let Some(done_batch) = completion_ring.pop() {
                let batch_latency_ms = done_batch.started_at.elapsed().as_secs_f32() * 1000.0;
                for _ in 0..done_batch.tokens_in_batch {
                    latencies.push(batch_latency_ms);
                }
                recycler_ring_c.wait_for_space();
                let _ = recycler_ring_c.push(done_batch.payload);
            }
        }
        latencies
    });

    let exec_start = Instant::now();
    for batch_idx in 0..batch_count {
        let batch_start_token = batch_idx * micro_batch;
        let tokens_in_batch = (token_count - batch_start_token).min(micro_batch);
        let payload_len = (tokens_in_batch.max(1) * 16).max(32);

        let mut payload = recycler_ring
            .pop()
            .unwrap_or_else(|| Vec::with_capacity(payload_len));
        payload.resize(payload_len, 0.0);
        for (idx, val) in payload.iter_mut().enumerate() {
            *val = (batch_idx as f32 * 0.01) + (idx as f32 * 0.0001);
        }

        // Evaluate dynamic rebalance trigger during execution
        if let (Some(trigger), Some(cluster_state), Some(placement)) =
            (rebalance, cluster, placement_context)
        {
            // Check for rebalance every 25th batch to allow stability between checks
            if batch_idx % 25 == 0 && batch_idx > 0 {
                if let Some(migration) = trigger.evaluate(cluster_state, placement) {
                    tracing::info!(
                        "Dynamic Runtime: Rebalance Triggered! Moving layers {:?} from {} to {}",
                        migration.layers,
                        migration.source_node,
                        migration.target_node
                    );
                    for step in migration.generate_handoff_plan() {
                        tracing::info!("  -> {}", step);
                    }
                }
            }
        }

        entry_ring.wait_for_space();
        let _ = entry_ring.push(BatchWork {
            tokens_in_batch,
            started_at: Instant::now(),
            payload,
        });
    }
    // Drop entry ring to signal completion to stage threads
    drop(entry_ring);

    let token_latencies = latencies_handle.join().unwrap_or_default();
    let total_time_ms = exec_start.elapsed().as_secs_f32() * 1000.0;

    let mut stage_stats = Vec::with_capacity(stage_count);
    for handle in stage_handles {
        if let Ok(stats) = handle.join() {
            let divisor = stats.processed_batches.max(1) as f32;
            let avg_compute_ms = stats.total_compute_ms / divisor;

            // Feedback loop: update cluster state with actual compute latency
            if let Some(cluster_state) = cluster {
                if let Some(stage) = plan.stages.get(stats.stage_idx) {
                    cluster_state.get_metrics_mut(&stage.node_id, |m| {
                        // Convert ms back to us for ClusterState (avg_latency_us)
                        m.record_latency(avg_compute_ms * 1000.0);
                    });
                }
            }

            stage_stats.push(StageExecutionStats {
                stage_idx: stats.stage_idx,
                processed_batches: stats.processed_batches,
                avg_compute_ms,
                avg_recv_wait_ms: stats.total_recv_wait_ms / divisor,
                avg_send_wait_ms: stats.total_send_wait_ms / divisor,
                avg_bridge_write_ms: 0.0,
                avg_bridge_read_ms: 0.0,
            });
        }
    }
    stage_stats.sort_by_key(|s| s.stage_idx);

    let throughput_tokens_per_sec = if total_time_ms > 0.0 {
        token_count as f32 / (total_time_ms / 1000.0)
    } else {
        0.0
    };

    let avg_token_latency_ms = if token_latencies.is_empty() {
        0.0
    } else {
        token_latencies.iter().sum::<f32>() / token_latencies.len() as f32
    };

    let mut sorted = token_latencies.clone();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let p95_idx = (sorted.len().saturating_sub(1) as f32 * 0.95).round() as usize;
    let p95_token_latency_ms = sorted.get(p95_idx).copied().unwrap_or(0.0);
    let p99_idx = (sorted.len().saturating_sub(1) as f32 * 0.99).round() as usize;
    let p99_token_latency_ms = sorted.get(p99_idx).copied().unwrap_or(0.0);

    Ok(ExecutionResult {
        token_count,
        micro_batch,
        batch_count,
        stage_count,
        total_time_ms,
        throughput_tokens_per_sec,
        avg_token_latency_ms,
        p95_token_latency_ms,
        p99_token_latency_ms,
        token_latencies_ms: token_latencies,
        stage_stats,
    })
}

#[derive(Debug, Clone)]
pub struct TransportBatch {
    pub batch_id: usize,
    pub tokens_in_batch: usize,
    pub payload: Vec<f32>,
}

fn auth_tag(
    source_stage: usize,
    batch_id: usize,
    tokens_in_batch: usize,
    payload: &[f32],
    token: &str,
) -> [u8; 32] {
    let mut mac = Hmac::<Sha256>::new_from_slice(token.as_bytes())
        .expect("HMAC key setup for transport auth failed");
    mac.update(&(source_stage as u32).to_le_bytes());
    mac.update(&(batch_id as u64).to_le_bytes());
    mac.update(&(tokens_in_batch as u32).to_le_bytes());
    mac.update(&(payload.len() as u32).to_le_bytes());
    let payload_bytes = payload_as_le_bytes(payload);
    mac.update(payload_bytes.as_ref());
    mac.finalize().into_bytes().into()
}

fn payload_as_le_bytes(payload: &[f32]) -> std::borrow::Cow<'_, [u8]> {
    if cfg!(target_endian = "little") {
        // SAFETY: f32 is POD; casting [f32] to its contiguous byte representation is valid.
        let bytes = unsafe {
            slice::from_raw_parts(
                payload.as_ptr() as *const u8,
                std::mem::size_of_val(payload),
            )
        };
        std::borrow::Cow::Borrowed(bytes)
    } else {
        let mut bytes = Vec::with_capacity(payload.len() * 4);
        for value in payload {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
        std::borrow::Cow::Owned(bytes)
    }
}

fn write_transport_batch(
    writer: &mut impl Write,
    batch: &TransportBatch,
    source_stage: usize,
    token: Option<&str>,
    frame_buf: &mut Vec<u8>,
) -> io::Result<()> {
    _write_transport_batch_inner(writer, batch, source_stage, token, None, frame_buf)
}

fn write_transport_batch_session(
    writer: &mut impl Write,
    batch: &TransportBatch,
    source_stage: usize,
    session: &SessionAuth,
    frame_buf: &mut Vec<u8>,
) -> io::Result<()> {
    _write_transport_batch_inner(writer, batch, source_stage, None, Some(session), frame_buf)
}

fn _write_transport_batch_inner(
    writer: &mut impl Write,
    batch: &TransportBatch,
    source_stage: usize,
    token: Option<&str>,
    session: Option<&SessionAuth>,
    frame_buf: &mut Vec<u8>,
) -> io::Result<()> {
    let batch_id = batch.batch_id as u64;
    let tokens = batch.tokens_in_batch as u32;
    let payload_len = batch.payload.len() as u32;
    let source_stage_u16 = source_stage as u16;

    frame_buf.clear();
    let header_size = if session.is_some() {
        // source_stage(2) + batch_id(8) + tokens(4) + payload_len(4) + tag_present(1) + session_id(8) + generation(8)
        2 + 8 + 4 + 4 + 1 + 8 + 8
    } else if token.is_some() {
        // legacy HMAC: 2 + 8 + 4 + 4 + 1 + 32
        2 + 8 + 4 + 4 + 1 + 32
    } else {
        2 + 8 + 4 + 4 + 1
    };
    // Reserve space ONLY for the header to avoid large intermediate allocation/capacity checks.
    frame_buf.reserve(header_size);
    frame_buf.extend_from_slice(&source_stage_u16.to_le_bytes());
    frame_buf.extend_from_slice(&batch_id.to_le_bytes());
    frame_buf.extend_from_slice(&tokens.to_le_bytes());
    frame_buf.extend_from_slice(&payload_len.to_le_bytes());

    if let Some(s) = session {
        frame_buf.push(2); // session-level auth
        let gen = s.seq.fetch_add(1, Ordering::Relaxed);
        frame_buf.extend_from_slice(&s.session_id.to_le_bytes());
        frame_buf.extend_from_slice(&gen.to_le_bytes());
    } else if let Some(t) = token {
        frame_buf.push(1); // legacy HMAC present
        let tag = auth_tag(
            source_stage,
            batch.batch_id,
            batch.tokens_in_batch,
            &batch.payload,
            t,
        );
        frame_buf.extend_from_slice(&tag);
    } else {
        frame_buf.push(0); // No auth
    }

    // Zero-Copy Transport Optimization: By writing the header and the float payload
    // separately directly to the underlying BufWriter, we completely avoid copying
    // the entire multi-kilobyte/megabyte float slice payload into the intermediate
    // scratch frame_buf vector. This yields a massive reduction in memory bandwidth and CPU cycles.
    let payload_bytes = payload_as_le_bytes(&batch.payload);
    writer.write_all(frame_buf)?;
    writer.write_all(payload_bytes.as_ref())?;

    Ok(())
}

fn read_transport_batch(
    reader: &mut impl Read,
    expected_source_stage: usize,
    token: Option<&str>,
    payload_buf: &mut Vec<f32>,
) -> io::Result<Option<TransportBatch>> {
    _read_transport_batch_inner(reader, expected_source_stage, token, None, payload_buf)
}

fn read_transport_batch_session(
    reader: &mut impl Read,
    expected_source_stage: usize,
    session: &SessionAuth,
    payload_buf: &mut Vec<f32>,
) -> io::Result<Option<TransportBatch>> {
    _read_transport_batch_inner(
        reader,
        expected_source_stage,
        None,
        Some(session),
        payload_buf,
    )
}

fn _read_transport_batch_inner(
    reader: &mut impl Read,
    expected_source_stage: usize,
    token: Option<&str>,
    session: Option<&SessionAuth>,
    payload_buf: &mut Vec<f32>,
) -> io::Result<Option<TransportBatch>> {
    let mut source_stage_bytes = [0u8; 2];
    match reader.read_exact(&mut source_stage_bytes) {
        Ok(()) => {}
        Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
        Err(err) => return Err(err),
    }
    let source_stage = u16::from_le_bytes(source_stage_bytes) as usize;
    if source_stage != expected_source_stage {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "unexpected source stage in transport frame",
        ));
    }

    let mut batch_id_bytes = [0u8; 8];
    reader.read_exact(&mut batch_id_bytes)?;

    let mut tokens_bytes = [0u8; 4];
    reader.read_exact(&mut tokens_bytes)?;

    let mut payload_len_bytes = [0u8; 4];
    reader.read_exact(&mut payload_len_bytes)?;
    let payload_len = u32::from_le_bytes(payload_len_bytes) as usize;

    // Bound the wire-declared payload length BEFORE allocating. A corrupted or
    // cross-wired frame can otherwise declare up to u32::MAX elements (~17 GB
    // of f32), and the resulting failed allocation aborts the process (or gets
    // the backend OOM-killed on Linux) instead of surfacing an error.
    const MAX_WIRE_PAYLOAD_ELEMS: usize = 64 * 1024 * 1024; // 256 MB of f32
    if payload_len > MAX_WIRE_PAYLOAD_ELEMS {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "wire payload length {} exceeds maximum {} (corrupted or cross-wired frame?)",
                payload_len, MAX_WIRE_PAYLOAD_ELEMS
            ),
        ));
    }

    let mut tag_type_byte = [0u8; 1];
    reader.read_exact(&mut tag_type_byte)?;
    let tag_type = tag_type_byte[0];

    match tag_type {
        2 => {
            // Session-level auth: read session_id + generation
            let mut session_id_bytes = [0u8; 8];
            reader.read_exact(&mut session_id_bytes)?;
            let frame_session_id = u64::from_le_bytes(session_id_bytes);
            let mut gen_bytes = [0u8; 8];
            reader.read_exact(&mut gen_bytes)?;
            let generation = u64::from_le_bytes(gen_bytes);

            if session.is_none() {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "session auth required but no session established",
                ));
            }
            let s = session.unwrap();
            if frame_session_id != s.session_id {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "session auth: session_id mismatch",
                ));
            }
            let prev = s.peer_seq.fetch_max(generation, Ordering::AcqRel);
            if generation < prev {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "session auth: non-monotonic generation",
                ));
            }
        }
        1 => {
            // Legacy HMAC auth
            if token.is_none() {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "HMAC auth present but no token configured",
                ));
            }
            let mut received_tag = [0u8; 32];
            reader.read_exact(&mut received_tag)?;
            payload_buf.resize(payload_len, 0.0);
            _read_payload(reader, payload_buf, payload_len)?;

            let batch_id = u64::from_le_bytes(batch_id_bytes) as usize;
            let tokens_in_batch = u32::from_le_bytes(tokens_bytes) as usize;
            let expected_tag = auth_tag(
                source_stage,
                batch_id,
                tokens_in_batch,
                payload_buf,
                token.unwrap(),
            );
            if received_tag != expected_tag {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "transport auth tag mismatch",
                ));
            }
            return Ok(Some(TransportBatch {
                batch_id,
                tokens_in_batch,
                payload: payload_buf.clone(),
            }));
        }
        0 => {
            // No auth
            if token.is_some() || session.is_some() {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "transport authentication required but no auth present",
                ));
            }
        }
        _ => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "unknown transport auth type",
            ));
        }
    }

    // Common path: read payload after auth verification
    payload_buf.resize(payload_len, 0.0);
    _read_payload(reader, payload_buf, payload_len)?;

    let batch_id = u64::from_le_bytes(batch_id_bytes) as usize;
    let tokens_in_batch = u32::from_le_bytes(tokens_bytes) as usize;

    Ok(Some(TransportBatch {
        batch_id,
        tokens_in_batch,
        payload: payload_buf.clone(),
    }))
}

fn _read_payload(
    reader: &mut impl Read,
    payload_buf: &mut [f32],
    payload_len: usize,
) -> io::Result<()> {
    if payload_len == 0 {
        return Ok(());
    }
    if cfg!(target_endian = "little") {
        let payload_bytes = unsafe {
            slice::from_raw_parts_mut(
                payload_buf.as_mut_ptr() as *mut u8,
                payload_len * std::mem::size_of::<f32>(),
            )
        };
        reader.read_exact(payload_bytes)?;
    } else {
        let mut payload_bytes = vec![0u8; payload_len * 4];
        reader.read_exact(&mut payload_bytes)?;
        for (i, chunk) in payload_bytes.chunks_exact(4).enumerate() {
            payload_buf[i] = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
        }
    }
    Ok(())
}

/// Spawn a TCP transport bridge between pipeline stages.
///
/// In a multi-node deployment, the `bind_addr` and `connect_addr` can point to
/// different physical interfaces or remote hosts.
///
/// `circuit_breaker` is optional and persists failure history *across* calls
/// (unlike `config.reconnect_attempts`, which only bounds retries within this
/// one call) — pass `ClusterState::circuit_breaker_for(node_id)` for a real
/// remote node so a chronically-unreachable node fails fast on subsequent
/// pipeline runs instead of repeating the full connect/backoff sequence every
/// time. `None` (e.g. loopback benchmarking, where there's no real remote
/// failure mode to protect against) reproduces the prior always-retry behavior
/// exactly.
pub fn spawn_tcp_bridge(
    source_stage: usize,
    input_rx: mpsc::Receiver<TransportBatch>,
    output_tx: mpsc::SyncSender<TransportBatch>,
    config: TcpTransportConfig,
    listener: BridgeListener,
    addr: BridgeAddr,
    circuit_breaker: Option<CircuitBreaker>,
) -> thread::JoinHandle<BridgeAccumulator> {
    thread::spawn(move || {
        let client_stream = {
            let breaker_open = circuit_breaker
                .as_ref()
                .is_some_and(|breaker| !breaker.should_attempt());

            let mut connected = None;
            if breaker_open {
                tracing::warn!(
                    "Bridge: circuit breaker open for {:?}; skipping connection attempts",
                    addr
                );
            } else {
                let attempts = config.reconnect_attempts.max(1);
                for attempt in 0..attempts {
                    match addr.connect(Duration::from_secs(1)) {
                        Ok(stream) => {
                            connected = Some(stream);
                            break;
                        }
                        Err(e) => {
                            tracing::debug!(
                                "Bridge: Connection attempt {}/{} failed for {:?}: {}",
                                attempt + 1,
                                attempts,
                                addr,
                                e
                            );
                            thread::sleep(Duration::from_millis(config.reconnect_backoff_ms));
                        }
                    }
                }
            }

            match connected {
                Some(stream) => {
                    if let Some(breaker) = &circuit_breaker {
                        breaker.record_success();
                    }
                    stream
                }
                None => {
                    if let Some(breaker) = &circuit_breaker {
                        breaker.record_failure();
                    }
                    tracing::error!(
                        "Bridge: Exhausted retries for {:?}. Falling back to passthrough.",
                        addr
                    );
                    for batch in input_rx {
                        if output_tx.send(batch).is_err() {
                            break;
                        }
                    }
                    return BridgeAccumulator::default_with_stage(source_stage);
                }
            }
        };

        // Inter-stage frames are small and latency-sensitive. For TCP, Nagle's
        // algorithm would coalesce these and stall on peer delayed-ACKs (~40ms),
        // which compounds across hops and dominates multi-stage paths.
        if let Err(e) = client_stream.set_nodelay(true) {
            tracing::debug!("Bridge: failed to set TCP_NODELAY on client: {}", e);
        }

        let server_stream = match listener.accept() {
            Ok(stream) => {
                // Once the peer is connected the Unix socket file is no longer
                // needed; unlink immediately so unique per-pipeline socket
                // paths do not accumulate in the temp directory.
                #[cfg(unix)]
                if let BridgeAddr::Unix(path) = &addr {
                    let _ = std::fs::remove_file(path);
                }
                stream
            }
            Err(_) => {
                #[cfg(unix)]
                if let BridgeAddr::Unix(path) = &addr {
                    let _ = std::fs::remove_file(path);
                }
                for batch in input_rx {
                    if output_tx.send(batch).is_err() {
                        break;
                    }
                }
                return BridgeAccumulator::default_with_stage(source_stage);
            }
        };

        if let Err(e) = server_stream.set_nodelay(true) {
            tracing::debug!("Bridge: failed to set TCP_NODELAY on server: {}", e);
        }

        // Set socket buffer sizes for better throughput
        if let Err(e) = client_stream.set_send_buffer_size(config.send_buffer_size) {
            tracing::debug!("Bridge: failed to set SO_SNDBUF on client: {}", e);
        }
        if let Err(e) = client_stream.set_recv_buffer_size(config.recv_buffer_size) {
            tracing::debug!("Bridge: failed to set SO_RCVBUF on client: {}", e);
        }
        if let Err(e) = server_stream.set_send_buffer_size(config.send_buffer_size) {
            tracing::debug!("Bridge: failed to set SO_SNDBUF on server: {}", e);
        }
        if let Err(e) = server_stream.set_recv_buffer_size(config.recv_buffer_size) {
            tracing::debug!("Bridge: failed to set SO_RCVBUF on server: {}", e);
        }

        let session = config.auth_session_token.as_ref().map(|session_token| {
            // Derive a deterministic session_id from the token (no handshake round-trip).
            // The TCP connect/accept already authenticates this connection.
            // Use SHA-256 of the token (first 8 bytes) for cross-platform determinism.
            let token_hash = {
                let mut mac = Hmac::<Sha256>::new_from_slice(session_token.as_bytes())
                    .expect("HMAC key for session_id derivation");
                mac.update(b"session-id");
                mac.finalize().into_bytes()
            };
            let session_id = u64::from_le_bytes([
                token_hash[0],
                token_hash[1],
                token_hash[2],
                token_hash[3],
                token_hash[4],
                token_hash[5],
                token_hash[6],
                token_hash[7],
            ]);
            tracing::debug!(
                "TCP Bridge: session auth established, session_id={}",
                session_id
            );
            SessionAuth {
                session_id,
                seq: Arc::new(AtomicU64::new(0)),
                peer_seq: Arc::new(AtomicU64::new(0)),
            }
        });

        let use_session = session.clone();
        let writer_use_session = use_session.clone();
        let reader_use_session = use_session.clone();
        let writer_auth_token = if writer_use_session.is_some() {
            None
        } else {
            config
                .auth_session_token
                .clone()
                .or_else(|| config.auth_token.clone())
        };
        let reader_auth_token = if reader_use_session.is_some() {
            None
        } else {
            config
                .auth_session_token
                .clone()
                .or_else(|| config.auth_token.clone())
        };

        let writer = thread::spawn(move || {
            let mut writer = BufWriter::with_capacity(64 * 1024, client_stream);
            let mut processed_batches = 0usize;
            let mut total_write_ms = 0.0_f32;
            let mut frame_buf = Vec::with_capacity(64 * 1024);
            let write_result: Result<(), ()> = (|| {
                if let Some(ref s) = writer_use_session {
                    for batch in input_rx {
                        let write_start = Instant::now();
                        write_transport_batch_session(
                            &mut writer,
                            &batch,
                            source_stage,
                            s,
                            &mut frame_buf,
                        )
                        .map_err(|_| ())?;
                        // BufWriter only spills to the socket once its 64KB
                        // buffer fills — for the small, sub-buffer-size frames
                        // this bridge carries, that meant every batch sat in
                        // userspace until the whole input channel drained, so
                        // the receiver saw nothing until one final burst at
                        // stream end instead of the pipelined, per-batch
                        // delivery TCP_NODELAY above was set up to provide.
                        // Flushing per frame is what actually puts NODELAY to
                        // work for this latency-sensitive path.
                        writer.flush().map_err(|_| ())?;
                        total_write_ms += write_start.elapsed().as_secs_f32() * 1000.0;
                        processed_batches += 1;
                    }
                } else {
                    for batch in input_rx {
                        let write_start = Instant::now();
                        write_transport_batch(
                            &mut writer,
                            &batch,
                            source_stage,
                            writer_auth_token.as_deref(),
                            &mut frame_buf,
                        )
                        .map_err(|_| ())?;
                        writer.flush().map_err(|_| ())?;
                        total_write_ms += write_start.elapsed().as_secs_f32() * 1000.0;
                        processed_batches += 1;
                    }
                }
                Ok(())
            })();
            let _ = writer.flush();
            let _ = writer.get_ref().shutdown_write();
            let _ = write_result;
            (processed_batches, total_write_ms)
        });

        let mut reader = BufReader::with_capacity(64 * 1024, server_stream);
        let mut read_batches = 0usize;
        let mut total_read_ms = 0.0_f32;
        let mut payload_buf = Vec::with_capacity(16 * 1024);

        let _: Result<(), ()> = if let Some(ref s) = reader_use_session {
            loop {
                let read_start = Instant::now();
                match read_transport_batch_session(&mut reader, source_stage, s, &mut payload_buf) {
                    Ok(Some(batch)) => {
                        total_read_ms += read_start.elapsed().as_secs_f32() * 1000.0;
                        if output_tx.send(batch).is_err() {
                            break Ok(());
                        }
                        read_batches += 1;
                    }
                    Ok(None) => break Ok(()),
                    Err(_) => break Err(()),
                }
            }
        } else {
            loop {
                let read_start = Instant::now();
                match read_transport_batch(
                    &mut reader,
                    source_stage,
                    reader_auth_token.as_deref(),
                    &mut payload_buf,
                ) {
                    Ok(Some(batch)) => {
                        total_read_ms += read_start.elapsed().as_secs_f32() * 1000.0;
                        if output_tx.send(batch).is_err() {
                            break Ok(());
                        }
                        read_batches += 1;
                    }
                    Ok(None) => break Ok(()),
                    Err(_) => break Err(()),
                }
            }
        };

        let (write_batches, total_write_ms) = writer.join().unwrap_or((0, 0.0));
        BridgeAccumulator {
            source_stage,
            processed_batches: read_batches.max(write_batches),
            total_write_ms,
            total_read_ms,
        }
    })
}

#[derive(Debug)]
pub struct BridgeAccumulator {
    pub source_stage: usize,
    pub processed_batches: usize,
    pub total_write_ms: f32,
    pub total_read_ms: f32,
}

impl BridgeAccumulator {
    fn default_with_stage(source_stage: usize) -> Self {
        Self {
            source_stage,
            processed_batches: 0,
            total_write_ms: 0.0,
            total_read_ms: 0.0,
        }
    }
}

/// Execute pipeline stages distributed across the LAN using TCP transport.
pub fn execute_pipeline_distributed(
    plan: &PipelinePlan,
    token_count: usize,
    micro_batch: usize,
    config: TcpTransportConfig,
    cluster: &crate::cluster::ClusterState,
    placement_context: Option<&crate::planning::PlacementPlan>,
    rebalance: Option<&crate::planning::RebalanceTrigger>,
) -> Result<ExecutionResult, String> {
    let stage_count = plan.stages.len();
    let micro_batch = micro_batch.max(1);
    let batch_count = token_count.div_ceil(micro_batch);
    if stage_count == 0 || token_count == 0 {
        return Ok(ExecutionResult {
            token_count,
            micro_batch,
            batch_count,
            stage_count,
            total_time_ms: 0.0,
            throughput_tokens_per_sec: 0.0,
            avg_token_latency_ms: 0.0,
            p95_token_latency_ms: 0.0,
            p99_token_latency_ms: 0.0,
            token_latencies_ms: Vec::new(),
            stage_stats: Vec::new(),
        });
    }

    #[derive(Debug)]
    struct StageAccumulator {
        stage_idx: usize,
        processed_batches: usize,
        total_compute_ms: f32,
        total_recv_wait_ms: f32,
        total_send_wait_ms: f32,
    }

    let (entry_tx, entry_rx) = mpsc::channel::<TransportBatch>();
    let mut stage_inputs: Vec<Option<mpsc::Receiver<TransportBatch>>> =
        Vec::with_capacity(stage_count);
    stage_inputs.push(Some(entry_rx));
    let mut stage_outputs = Vec::with_capacity(stage_count);
    let mut bridge_handles = Vec::new();
    let bridge_capacity = config.max_inflight_batches.max(1);

    for source_stage_idx in 0..stage_count.saturating_sub(1) {
        let (bridge_in_tx, bridge_in_rx) = mpsc::sync_channel::<TransportBatch>(bridge_capacity);
        let (bridge_out_tx, bridge_out_rx) = mpsc::sync_channel::<TransportBatch>(bridge_capacity);
        stage_outputs.push(bridge_in_tx);
        stage_inputs.push(Some(bridge_out_rx));

        let source_stage_p = &plan.stages[source_stage_idx];
        let target_stage_p = &plan.stages[source_stage_idx + 1];
        let same_node = source_stage_p.node_id == target_stage_p.node_id;

        let (listener, addr) = if same_node && config.transport == TransportKind::Unix {
            #[cfg(unix)]
            {
                // Same-node with Unix transport: use Unix domain socket.
                let sock_path = unique_bridge_socket_path(source_stage_idx);
                let _ = std::fs::remove_file(&sock_path);
                let ulistener = UnixListener::bind(&sock_path).map_err(|e| {
                    format!("Failed to bind Unix socket at {}: {e}", sock_path.display())
                })?;
                let addr = BridgeAddr::Unix(sock_path);
                (BridgeListener::Unix(ulistener), addr)
            }
            #[cfg(not(unix))]
            return Err("Unix domain sockets require a Unix platform (Linux/macOS)".to_string());
        } else {
            // TCP transport for cross-node or when configured explicitly.
            let bind_ip = if let Some(m) = cluster.get_metrics(&target_stage_p.node_id) {
                m.ip_address
                    .map(|sa| sa.ip())
                    .unwrap_or_else(|| [127, 0, 0, 1].into())
            } else {
                [127, 0, 0, 1].into()
            };

            let tcp_listener = TcpListener::bind(SocketAddr::new(bind_ip, 0))
                .map_err(|e| format!("Failed to bind TCP listener on {bind_ip}: {e}"))?;
            let actual_addr = tcp_listener
                .local_addr()
                .map_err(|e| format!("failed to get TCP local addr: {e}"))?;

            // For connection, if it's the same node, use loopback.
            let connect_ip = if same_node {
                [127, 0, 0, 1].into()
            } else {
                actual_addr.ip()
            };
            let connect_addr = SocketAddr::new(connect_ip, actual_addr.port());
            (
                BridgeListener::Tcp(tcp_listener),
                BridgeAddr::Tcp(connect_addr),
            )
        };

        let breaker = Some(cluster.circuit_breaker_for(&target_stage_p.node_id));
        bridge_handles.push(spawn_tcp_bridge(
            source_stage_idx,
            bridge_in_rx,
            bridge_out_tx,
            config.clone(),
            listener,
            addr,
            breaker,
        ));
    }

    let (completion_tx, completion_rx) = mpsc::sync_channel::<TransportBatch>(bridge_capacity);
    stage_outputs.push(completion_tx);

    let mut stage_handles = Vec::with_capacity(stage_count);
    for stage_idx in 0..stage_count {
        let stage = plan.stages[stage_idx].clone();
        let rx = stage_inputs[stage_idx]
            .take()
            .expect("stage receiver should exist");
        let tx_next = stage_outputs[stage_idx].clone();

        let handle = thread::spawn(move || {
            let mut processed_batches = 0usize;
            let mut total_compute_ms = 0.0_f32;
            let mut total_recv_wait_ms = 0.0_f32;
            let mut total_send_wait_ms = 0.0_f32;

            loop {
                let recv_start = Instant::now();
                let Ok(mut batch) = rx.recv() else {
                    break;
                };
                total_recv_wait_ms += recv_start.elapsed().as_secs_f32() * 1000.0;

                let compute_start = Instant::now();
                run_stage_compute(&mut batch.payload, &stage);
                total_compute_ms += compute_start.elapsed().as_secs_f32() * 1000.0;

                let send_start = Instant::now();
                if tx_next.send(batch).is_err() {
                    break;
                }
                total_send_wait_ms += send_start.elapsed().as_secs_f32() * 1000.0;
                processed_batches += 1;
            }

            StageAccumulator {
                stage_idx,
                processed_batches,
                total_compute_ms,
                total_recv_wait_ms,
                total_send_wait_ms,
            }
        });

        stage_handles.push(handle);
    }

    drop(stage_outputs);

    let mut batch_started_at = vec![Instant::now(); batch_count];
    let exec_start = Instant::now();
    for (batch_idx, batch_started_slot) in batch_started_at.iter_mut().enumerate() {
        let batch_start_token = batch_idx * micro_batch;
        let tokens_in_batch = (token_count - batch_start_token).min(micro_batch);
        let payload_len = (tokens_in_batch.max(1) * config.elems_per_token.max(1)).max(32);
        let payload = (0..payload_len)
            .map(|idx| (batch_idx as f32 * 0.01) + (idx as f32 * 0.0001))
            .collect();

        *batch_started_slot = Instant::now();
        let _ = entry_tx.send(TransportBatch {
            batch_id: batch_idx,
            tokens_in_batch,
            payload,
        });
    }
    drop(entry_tx);

    let mut token_latencies = Vec::with_capacity(token_count);
    for _ in 0..batch_count {
        let Ok(done_batch) = completion_rx.recv() else {
            break;
        };
        let started_at = batch_started_at[done_batch.batch_id];
        let batch_latency_ms = started_at.elapsed().as_secs_f32() * 1000.0;
        for _ in 0..done_batch.tokens_in_batch {
            token_latencies.push(batch_latency_ms);
        }
    }

    // Evaluate dynamic rebalance trigger during execution
    if let (Some(trigger), Some(placement)) = (rebalance, placement_context) {
        if let Some(migration) = trigger.evaluate(cluster, placement) {
            tracing::info!(
                "Distributed Runtime: Rebalance Triggered! Moving layers {:?} from {} to {}",
                migration.layers,
                migration.source_node,
                migration.target_node
            );
        }
    }
    let total_time_ms = exec_start.elapsed().as_secs_f32() * 1000.0;

    let mut stage_stats = Vec::with_capacity(stage_count);
    for handle in stage_handles {
        if let Ok(stats) = handle.join() {
            let divisor = stats.processed_batches.max(1) as f32;
            let avg_compute_ms = stats.total_compute_ms / divisor;

            // Feedback loop: update cluster state with actual compute latency.
            if let Some(stage) = plan.stages.get(stats.stage_idx) {
                cluster.get_metrics_mut(&stage.node_id, |m| {
                    m.record_latency(avg_compute_ms * 1000.0);
                });
            }

            stage_stats.push(StageExecutionStats {
                stage_idx: stats.stage_idx,
                processed_batches: stats.processed_batches,
                avg_compute_ms,
                avg_recv_wait_ms: stats.total_recv_wait_ms / divisor,
                avg_send_wait_ms: stats.total_send_wait_ms / divisor,
                avg_bridge_write_ms: 0.0,
                avg_bridge_read_ms: 0.0,
            });
        }
    }

    let mut bridge_stats = Vec::with_capacity(bridge_handles.len());
    for handle in bridge_handles {
        if let Ok(stats) = handle.join() {
            bridge_stats.push(stats);
        }
    }

    for bridge in bridge_stats {
        if let Some(stage) = stage_stats
            .iter_mut()
            .find(|s| s.stage_idx == bridge.source_stage)
        {
            let divisor = bridge.processed_batches.max(1) as f32;
            stage.avg_bridge_write_ms = bridge.total_write_ms / divisor;
            stage.avg_bridge_read_ms = bridge.total_read_ms / divisor;
        }
    }

    stage_stats.sort_by_key(|s| s.stage_idx);

    let throughput_tokens_per_sec = if total_time_ms > 0.0 {
        token_count as f32 / (total_time_ms / 1000.0)
    } else {
        0.0
    };

    let avg_token_latency_ms = if token_latencies.is_empty() {
        0.0
    } else {
        token_latencies.iter().sum::<f32>() / token_latencies.len() as f32
    };

    let mut sorted = token_latencies.clone();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let p95_idx = ((sorted.len().saturating_sub(1)) as f32 * 0.95).round() as usize;
    let p95_token_latency_ms = sorted.get(p95_idx).copied().unwrap_or(0.0);
    let p99_idx = ((sorted.len().saturating_sub(1)) as f32 * 0.99).round() as usize;
    let p99_token_latency_ms = sorted.get(p99_idx).copied().unwrap_or(0.0);

    Ok(ExecutionResult {
        token_count,
        micro_batch,
        batch_count,
        stage_count,
        total_time_ms,
        throughput_tokens_per_sec,
        avg_token_latency_ms,
        p95_token_latency_ms,
        p99_token_latency_ms,
        token_latencies_ms: token_latencies,
        stage_stats,
    })
}

pub fn execute_pipeline_tcp_loopback(
    plan: &PipelinePlan,
    token_count: usize,
    micro_batch: usize,
) -> Result<ExecutionResult, String> {
    execute_pipeline_tcp_loopback_with_config(
        plan,
        token_count,
        micro_batch,
        TcpTransportConfig::default(),
    )
}

/// Execute pipeline stages with real TCP loopback transport bridges and explicit transport config.
pub fn execute_pipeline_tcp_loopback_with_config(
    plan: &PipelinePlan,
    token_count: usize,
    micro_batch: usize,
    config: TcpTransportConfig,
) -> Result<ExecutionResult, String> {
    let stage_count = plan.stages.len();
    let micro_batch = micro_batch.max(1);
    let batch_count = token_count.div_ceil(micro_batch);
    if stage_count == 0 || token_count == 0 {
        return Ok(ExecutionResult {
            token_count,
            micro_batch,
            batch_count,
            stage_count,
            total_time_ms: 0.0,
            throughput_tokens_per_sec: 0.0,
            avg_token_latency_ms: 0.0,
            p95_token_latency_ms: 0.0,
            p99_token_latency_ms: 0.0,
            token_latencies_ms: Vec::new(),
            stage_stats: Vec::new(),
        });
    }

    #[derive(Debug)]
    struct StageAccumulator {
        stage_idx: usize,
        processed_batches: usize,
        total_compute_ms: f32,
        total_recv_wait_ms: f32,
        total_send_wait_ms: f32,
    }

    let (entry_tx, entry_rx) = mpsc::channel::<TransportBatch>();
    let mut stage_inputs: Vec<Option<mpsc::Receiver<TransportBatch>>> =
        Vec::with_capacity(stage_count);
    stage_inputs.push(Some(entry_rx));
    let mut stage_outputs = Vec::with_capacity(stage_count);
    let mut bridge_handles = Vec::new();
    let bridge_capacity = config.max_inflight_batches.max(1);

    for source_stage in 0..stage_count.saturating_sub(1) {
        let (bridge_in_tx, bridge_in_rx) = mpsc::sync_channel::<TransportBatch>(bridge_capacity);
        let (bridge_out_tx, bridge_out_rx) = mpsc::sync_channel::<TransportBatch>(bridge_capacity);
        stage_outputs.push(bridge_in_tx);
        stage_inputs.push(Some(bridge_out_rx));

        let (listener, addr) = match config.transport {
            TransportKind::Tcp => {
                // For loopback execution, use distinct ports for each inter-stage bridge.
                let loopback = [127, 0, 0, 1].into();
                let bind_addr = SocketAddr::new(loopback, 0);
                let listener = TcpListener::bind(bind_addr)
                    .map_err(|e| format!("failed to bind TCP loopback listener: {e}"))?;
                let actual_addr = listener
                    .local_addr()
                    .map_err(|e| format!("failed to get TCP loopback addr: {e}"))?;
                (BridgeListener::Tcp(listener), BridgeAddr::Tcp(actual_addr))
            }
            #[cfg(unix)]
            TransportKind::Unix => {
                let sock_path = unique_bridge_socket_path(source_stage);
                let _ = std::fs::remove_file(&sock_path);
                let listener = UnixListener::bind(&sock_path).map_err(|e| {
                    format!("failed to bind Unix socket at {}: {e}", sock_path.display())
                })?;
                let addr = BridgeAddr::Unix(sock_path);
                (BridgeListener::Unix(listener), addr)
            }
            #[cfg(not(unix))]
            TransportKind::Unix => {
                return Err("Unix domain sockets require a Unix platform (Linux/macOS)".to_string());
            }
        };

        bridge_handles.push(spawn_tcp_bridge(
            source_stage,
            bridge_in_rx,
            bridge_out_tx,
            config.clone(),
            listener,
            addr,
            None, // loopback benchmarking: no real remote-node failure mode to track
        ));
    }

    let (completion_tx, completion_rx) = mpsc::sync_channel::<TransportBatch>(bridge_capacity);
    stage_outputs.push(completion_tx);

    let mut stage_handles = Vec::with_capacity(stage_count);
    for stage_idx in 0..stage_count {
        let stage = plan.stages[stage_idx].clone();
        let rx = stage_inputs[stage_idx]
            .take()
            .expect("stage receiver should exist");
        let tx_next = stage_outputs[stage_idx].clone();

        let handle = thread::spawn(move || {
            let mut processed_batches = 0usize;
            let mut total_compute_ms = 0.0_f32;
            let mut total_recv_wait_ms = 0.0_f32;
            let mut total_send_wait_ms = 0.0_f32;

            loop {
                let recv_start = Instant::now();
                let Ok(mut batch) = rx.recv() else {
                    break;
                };
                total_recv_wait_ms += recv_start.elapsed().as_secs_f32() * 1000.0;

                let compute_start = Instant::now();
                run_stage_compute(&mut batch.payload, &stage);
                total_compute_ms += compute_start.elapsed().as_secs_f32() * 1000.0;

                let send_start = Instant::now();
                if tx_next.send(batch).is_err() {
                    break;
                }
                total_send_wait_ms += send_start.elapsed().as_secs_f32() * 1000.0;
                processed_batches += 1;
            }

            StageAccumulator {
                stage_idx,
                processed_batches,
                total_compute_ms,
                total_recv_wait_ms,
                total_send_wait_ms,
            }
        });

        stage_handles.push(handle);
    }

    // Drop setup-time sender clones so channel closure can propagate and
    // stage/bridge threads can terminate once work is drained.
    drop(stage_outputs);

    let mut batch_started_at = vec![Instant::now(); batch_count];
    let exec_start = Instant::now();
    for (batch_idx, batch_started_slot) in batch_started_at.iter_mut().enumerate() {
        let batch_start_token = batch_idx * micro_batch;
        let tokens_in_batch = (token_count - batch_start_token).min(micro_batch);
        let payload_len = (tokens_in_batch.max(1) * config.elems_per_token.max(1)).max(32);
        let payload = (0..payload_len)
            .map(|idx| (batch_idx as f32 * 0.01) + (idx as f32 * 0.0001))
            .collect();

        *batch_started_slot = Instant::now();
        if entry_tx
            .send(TransportBatch {
                batch_id: batch_idx,
                tokens_in_batch,
                payload,
            })
            .is_err()
        {
            break;
        }
    }
    drop(entry_tx);

    let mut token_latencies = Vec::with_capacity(token_count);
    for _ in 0..batch_count {
        let Ok(done_batch) = completion_rx.recv() else {
            break;
        };

        let started_at = batch_started_at
            .get(done_batch.batch_id)
            .copied()
            .unwrap_or(exec_start);
        let batch_latency_ms = started_at.elapsed().as_secs_f32() * 1000.0;
        for _ in 0..done_batch.tokens_in_batch {
            token_latencies.push(batch_latency_ms);
        }
    }
    let total_time_ms = exec_start.elapsed().as_secs_f32() * 1000.0;

    let mut stage_stats = Vec::with_capacity(stage_count);
    for handle in stage_handles {
        if let Ok(stats) = handle.join() {
            let divisor = stats.processed_batches.max(1) as f32;
            stage_stats.push(StageExecutionStats {
                stage_idx: stats.stage_idx,
                processed_batches: stats.processed_batches,
                avg_compute_ms: stats.total_compute_ms / divisor,
                avg_recv_wait_ms: stats.total_recv_wait_ms / divisor,
                avg_send_wait_ms: stats.total_send_wait_ms / divisor,
                avg_bridge_write_ms: 0.0,
                avg_bridge_read_ms: 0.0,
            });
        }
    }

    let mut bridge_stats = Vec::with_capacity(bridge_handles.len());
    for handle in bridge_handles {
        if let Ok(stats) = handle.join() {
            bridge_stats.push(stats);
        }
    }

    for bridge in bridge_stats {
        if let Some(stage) = stage_stats
            .iter_mut()
            .find(|s| s.stage_idx == bridge.source_stage)
        {
            let divisor = bridge.processed_batches.max(1) as f32;
            stage.avg_bridge_write_ms = bridge.total_write_ms / divisor;
            stage.avg_bridge_read_ms = bridge.total_read_ms / divisor;
        }
    }

    stage_stats.sort_by_key(|s| s.stage_idx);

    let throughput_tokens_per_sec = if total_time_ms > 0.0 {
        token_count as f32 / (total_time_ms / 1000.0)
    } else {
        0.0
    };

    let avg_token_latency_ms = if token_latencies.is_empty() {
        0.0
    } else {
        token_latencies.iter().sum::<f32>() / token_latencies.len() as f32
    };

    let mut sorted = token_latencies.clone();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let p95_idx = ((sorted.len().saturating_sub(1)) as f32 * 0.95).round() as usize;
    let p95_token_latency_ms = sorted.get(p95_idx).copied().unwrap_or(0.0);
    let p99_idx = ((sorted.len().saturating_sub(1)) as f32 * 0.99).round() as usize;
    let p99_token_latency_ms = sorted.get(p99_idx).copied().unwrap_or(0.0);

    Ok(ExecutionResult {
        token_count,
        micro_batch,
        batch_count,
        stage_count,
        total_time_ms,
        throughput_tokens_per_sec,
        avg_token_latency_ms,
        p95_token_latency_ms,
        p99_token_latency_ms,
        token_latencies_ms: token_latencies,
        stage_stats,
    })
}

// --- Real remote-worker execution -----------------------------------------
//
// Everything above this point (`execute_pipeline_distributed`,
// `execute_pipeline_tcp_loopback_with_config`, ...) runs entirely within one
// process: every stage's TCP bridge both binds *and* connects to a local
// interface, so even in "TCP transport" mode there is no way to reach a
// genuinely separate machine — `bind()` only ever succeeds for addresses
// this host actually owns. The two functions below are the real thing: a
// worker process that binds and accepts on a second machine, and a
// coordinator function that *connects out* to it (`TcpStream::connect`, not
// `TcpListener::bind`) instead of simulating both ends locally.
//
// Scope is intentionally narrow (exactly one local stage + one remote
// stage, one connection, one-shot) to match `flow`'s existing local+remote
// 2-node model rather than building a general N-worker mesh. The "compute"
// on both ends is still `run_stage_compute`'s synthetic proxy workload
// (real CPU time, not real LLM inference) — what's genuinely new here is
// the *transport*: a real socket between two real OS processes, optionally
// on two real machines, not the numbers `run_stage_compute` produces.

/// A minimal wire handshake sent once when a coordinator connects to a
/// `run_stage_worker`: just enough for the worker to reconstruct the
/// `StagePlacement` it needs to call the same `run_stage_compute` the local
/// path uses, so timing is produced by identical code on both ends.
fn write_stage_handshake(writer: &mut impl Write, stage: &StagePlacement) -> Result<(), String> {
    let num_layers = stage.num_layers() as u32;
    let device_byte: u8 = match stage.device {
        DeviceKind::Npu => 0,
        DeviceKind::Gpu => 1,
        DeviceKind::Cpu => 2,
    };
    writer
        .write_all(&num_layers.to_le_bytes())
        .and_then(|_| writer.write_all(&[device_byte]))
        .map_err(|e| format!("failed to write stage handshake: {e}"))
}

fn read_stage_handshake(reader: &mut impl Read) -> Result<StagePlacement, String> {
    let mut layers_bytes = [0u8; 4];
    reader
        .read_exact(&mut layers_bytes)
        .map_err(|e| format!("failed to read stage handshake: {e}"))?;
    let num_layers = u32::from_le_bytes(layers_bytes) as usize;

    let mut device_byte = [0u8; 1];
    reader
        .read_exact(&mut device_byte)
        .map_err(|e| format!("failed to read stage handshake: {e}"))?;
    let device = match device_byte[0] {
        0 => DeviceKind::Npu,
        1 => DeviceKind::Gpu,
        _ => DeviceKind::Cpu,
    };

    Ok(StagePlacement {
        node_id: "remote".to_string(),
        start_layer: 0,
        end_layer: num_layers,
        device,
        est_latency_ms: 0.0,
    })
}

/// Summary a `stage-worker` process reports (to its own stdout, and back to
/// any caller driving it directly) once its one coordinator connection
/// closes.
#[derive(Clone, Debug, PartialEq)]
pub struct StageWorkerSummary {
    pub batches_processed: usize,
    pub avg_compute_ms: f32,
}

/// Runs as a real, separate OS process (see `ghost-link stage-worker`):
/// accepts exactly one coordinator connection on `listener`, reads the
/// stage handshake, then loops read-batch → compute → write-result until
/// the coordinator closes the connection. One-shot, matching how
/// `cluster-start`'s child `listen` processes already behave.
///
/// Takes an already-bound `TcpListener` rather than binding internally so
/// the caller controls exactly when/how the port is chosen — the CLI binds
/// the address the user passed on `--bind`, while tests bind `:0` to get a
/// real OS-assigned free port and can read it back via `local_addr()`
/// before this function (which blocks until a peer connects) is called.
pub fn run_stage_worker(
    listener: TcpListener,
    config: &TcpTransportConfig,
) -> Result<StageWorkerSummary, String> {
    let (mut stream, peer) = listener
        .accept()
        .map_err(|e| format!("failed to accept a connection: {e}"))?;
    let _ = stream.set_nodelay(true);

    let stage = read_stage_handshake(&mut stream)?;
    eprintln!(
        "[stage-worker] connection from {peer}; assigned {} layers on {}",
        stage.num_layers(),
        stage.device.as_str()
    );

    let mut frame_buf = Vec::new();
    let mut read_buf = Vec::new();
    let mut batches_processed = 0usize;
    let mut total_compute_ms = 0.0_f32;

    loop {
        let batch =
            match read_transport_batch(&mut stream, 0, config.auth_token.as_deref(), &mut read_buf)
            {
                Ok(Some(batch)) => batch,
                Ok(None) => break, // coordinator closed the connection cleanly
                Err(e) => return Err(format!("failed to read batch from coordinator: {e}")),
            };

        let mut payload = batch.payload;
        let compute_start = Instant::now();
        run_stage_compute(&mut payload, &stage);
        total_compute_ms += compute_start.elapsed().as_secs_f32() * 1000.0;

        let result = TransportBatch {
            batch_id: batch.batch_id,
            tokens_in_batch: batch.tokens_in_batch,
            payload,
        };
        write_transport_batch(
            &mut stream,
            &result,
            0,
            config.auth_token.as_deref(),
            &mut frame_buf,
        )
        .map_err(|e| format!("failed to write result batch to coordinator: {e}"))?;
        batches_processed += 1;
    }

    let avg_compute_ms = if batches_processed > 0 {
        total_compute_ms / batches_processed as f32
    } else {
        0.0
    };
    eprintln!(
        "[stage-worker] coordinator disconnected after {batches_processed} batch(es), avg compute {avg_compute_ms:.2} ms"
    );
    Ok(StageWorkerSummary {
        batches_processed,
        avg_compute_ms,
    })
}

/// Collapses every stage assigned to one node into a single logical
/// `StagePlacement` spanning that node's full layer range. The real layer
/// assignment algorithm doesn't hand each node one contiguous chunk — a
/// 60-layer/2-node `flow` plan produces ~11 raw stages (verified: 6 small
/// chunks for the local node, 5 for the remote one, each capped at roughly
/// 3GB), not the 2 this function originally assumed. The chunks for a given
/// node ARE always contiguous relative to each other, so merging them into
/// one placement per node is behaviorally sound: `run_stage_compute`'s
/// synthetic cost model only depends on total layer count and device kind,
/// not on how finely a node's range happens to be subdivided.
fn merge_stages_for_node(
    node_id: &str,
    stages: &[StagePlacement],
) -> Result<StagePlacement, String> {
    let matching: Vec<&StagePlacement> = stages.iter().filter(|s| s.node_id == node_id).collect();
    let Some(first) = matching.first() else {
        return Err(format!("no pipeline stages assigned to node '{node_id}'"));
    };
    let start_layer = matching.iter().map(|s| s.start_layer).min().unwrap_or(0);
    let end_layer = matching.iter().map(|s| s.end_layer).max().unwrap_or(0);
    Ok(StagePlacement {
        node_id: node_id.to_string(),
        start_layer,
        end_layer,
        device: first.device,
        est_latency_ms: matching.iter().map(|s| s.est_latency_ms).sum(),
    })
}

/// Coordinator side of real remote execution. `plan` must have at least one
/// stage assigned to `local_node_id` and at least one assigned to
/// `remote_node_id` — matching `flow`'s existing local+remote 2-*node*
/// model, though each node's stages get merged (see `merge_stages_for_node`)
/// since the real assignment algorithm splits one node's layers into
/// several raw stages, not necessarily one. The merged local stage runs
/// in-process as usual; the merged remote stage's batches are sent over a
/// real outbound connection (`TcpStream::connect(remote_addr)`) to a
/// separate `run_stage_worker` process, so the round-trip time recorded
/// here is genuine network + remote-compute time, not a local simulation.
pub fn execute_pipeline_with_remote_stage(
    plan: &PipelinePlan,
    local_node_id: &str,
    remote_node_id: &str,
    token_count: usize,
    micro_batch: usize,
    config: TcpTransportConfig,
    remote_addr: SocketAddr,
) -> Result<ExecutionResult, String> {
    let local_stage = merge_stages_for_node(local_node_id, &plan.stages)?;
    let remote_stage = merge_stages_for_node(remote_node_id, &plan.stages)?;
    let local_stage = &local_stage;
    let remote_stage = &remote_stage;

    let micro_batch = micro_batch.max(1);
    let batch_count = token_count.div_ceil(micro_batch);
    if token_count == 0 {
        return Ok(ExecutionResult {
            token_count,
            micro_batch,
            batch_count,
            stage_count: 2,
            total_time_ms: 0.0,
            throughput_tokens_per_sec: 0.0,
            avg_token_latency_ms: 0.0,
            p95_token_latency_ms: 0.0,
            p99_token_latency_ms: 0.0,
            token_latencies_ms: Vec::new(),
            stage_stats: Vec::new(),
        });
    }

    let mut stream = TcpStream::connect(remote_addr).map_err(|e| {
        format!(
            "failed to connect to remote stage worker at {remote_addr}: {e} \
             (is `ghost-link stage-worker --bind {remote_addr}` running there?)"
        )
    })?;
    let _ = stream.set_nodelay(true);
    write_stage_handshake(&mut stream, remote_stage)?;

    let mut frame_buf = Vec::new();
    let mut read_buf = Vec::new();
    let mut token_latencies = Vec::with_capacity(token_count);
    let mut local_compute_ms = 0.0_f32;
    let mut remote_round_trip_ms = 0.0_f32;

    let exec_start = Instant::now();
    for batch_idx in 0..batch_count {
        let batch_start_token = batch_idx * micro_batch;
        let tokens_in_batch = (token_count - batch_start_token).min(micro_batch);
        let payload_len = (tokens_in_batch.max(1) * config.elems_per_token.max(1)).max(32);
        let mut payload: Vec<f32> = (0..payload_len)
            .map(|idx| (batch_idx as f32 * 0.01) + (idx as f32 * 0.0001))
            .collect();

        let batch_started = Instant::now();

        let local_start = Instant::now();
        run_stage_compute(&mut payload, local_stage);
        local_compute_ms += local_start.elapsed().as_secs_f32() * 1000.0;

        let outgoing = TransportBatch {
            batch_id: batch_idx,
            tokens_in_batch,
            payload,
        };
        let rt_start = Instant::now();
        write_transport_batch(
            &mut stream,
            &outgoing,
            0,
            config.auth_token.as_deref(),
            &mut frame_buf,
        )
        .map_err(|e| format!("failed to send batch {batch_idx} to remote worker: {e}"))?;
        let result = read_transport_batch(&mut stream, 0, config.auth_token.as_deref(), &mut read_buf)
            .map_err(|e| format!("failed to read batch {batch_idx} result from remote worker: {e}"))?
            .ok_or_else(|| {
                format!("remote worker at {remote_addr} closed the connection before batch {batch_idx} completed")
            })?;
        remote_round_trip_ms += rt_start.elapsed().as_secs_f32() * 1000.0;

        let batch_latency_ms = batch_started.elapsed().as_secs_f32() * 1000.0;
        for _ in 0..result.tokens_in_batch {
            token_latencies.push(batch_latency_ms);
        }
    }
    let total_time_ms = exec_start.elapsed().as_secs_f32() * 1000.0;
    drop(stream); // signals the worker's read loop to exit cleanly

    let divisor = batch_count.max(1) as f32;
    let throughput_tokens_per_sec = if total_time_ms > 0.0 {
        token_count as f32 / (total_time_ms / 1000.0)
    } else {
        0.0
    };
    let avg_token_latency_ms = if token_latencies.is_empty() {
        0.0
    } else {
        token_latencies.iter().sum::<f32>() / token_latencies.len() as f32
    };
    let mut sorted = token_latencies.clone();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let p95_idx = (sorted.len().saturating_sub(1) as f32 * 0.95).round() as usize;
    let p95_token_latency_ms = sorted.get(p95_idx).copied().unwrap_or(0.0);
    let p99_idx = (sorted.len().saturating_sub(1) as f32 * 0.99).round() as usize;
    let p99_token_latency_ms = sorted.get(p99_idx).copied().unwrap_or(0.0);

    Ok(ExecutionResult {
        token_count,
        micro_batch,
        batch_count,
        stage_count: 2,
        total_time_ms,
        throughput_tokens_per_sec,
        avg_token_latency_ms,
        p95_token_latency_ms,
        p99_token_latency_ms,
        token_latencies_ms: token_latencies,
        stage_stats: vec![
            StageExecutionStats {
                stage_idx: 0,
                processed_batches: batch_count,
                avg_compute_ms: local_compute_ms / divisor,
                avg_recv_wait_ms: 0.0,
                avg_send_wait_ms: 0.0,
                avg_bridge_write_ms: 0.0,
                avg_bridge_read_ms: 0.0,
            },
            StageExecutionStats {
                stage_idx: 1,
                processed_batches: batch_count,
                // The remote side's own compute time isn't observable from
                // here without a second telemetry channel — what IS real
                // and observable is the round trip, reported as bridge
                // write time so it's visible in `ExecutionResult::summary()`
                // without inventing a number for compute we didn't measure.
                avg_compute_ms: 0.0,
                avg_recv_wait_ms: 0.0,
                avg_send_wait_ms: 0.0,
                avg_bridge_write_ms: remote_round_trip_ms / divisor,
                avg_bridge_read_ms: 0.0,
            },
        ],
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::planning::LayerAssignment;
    use std::collections::HashMap;
    use std::io::Cursor;

    #[test]
    fn pipeline_plan_uses_node_device_mapping() {
        let assignments = vec![
            LayerAssignment::new("node-a".to_string(), 0, 10, 5.0),
            LayerAssignment::new("node-b".to_string(), 10, 20, 5.0),
        ];

        let mut devices = HashMap::new();
        devices.insert("node-a".to_string(), DeviceKind::Gpu);
        devices.insert("node-b".to_string(), DeviceKind::Cpu);

        let plan = PipelinePlan::from_assignments(&assignments, &devices);

        assert_eq!(plan.stages.len(), 2);
        assert_eq!(plan.stages[0].device, DeviceKind::Gpu);
        assert_eq!(plan.stages[1].device, DeviceKind::Cpu);
        assert!(plan.est_step_latency_ms() > 0.0);
    }

    #[test]
    fn schedule_size_matches_tokens_times_stages() {
        let schedule = build_token_schedule(3, 4);
        assert_eq!(schedule.len(), 12);
        assert_eq!(
            schedule[0],
            TokenStep {
                token_idx: 0,
                stage_idx: 0
            }
        );
        assert_eq!(
            schedule[11],
            TokenStep {
                token_idx: 3,
                stage_idx: 2
            }
        );
    }

    #[test]
    fn execution_reports_basic_stage_metrics() {
        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "node-a".to_string(),
                    start_layer: 0,
                    end_layer: 10,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.0,
                },
                StagePlacement {
                    node_id: "node-b".to_string(),
                    start_layer: 10,
                    end_layer: 20,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.0,
                },
            ],
        };

        let result = execute_pipeline(&plan, 8, 1).expect("failed");
        assert_eq!(result.stage_count, 2);
        assert_eq!(result.token_count, 8);
        assert_eq!(result.micro_batch, 1);
        assert_eq!(result.batch_count, 8);
        assert_eq!(result.stage_stats.len(), 2);
        assert!(result.total_time_ms > 0.0);
        assert!(result.avg_token_latency_ms > 0.0);
        assert!(result.throughput_tokens_per_sec > 0.0);
    }

    #[test]
    fn execution_respects_micro_batch_count() {
        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "node-a".to_string(),
                    start_layer: 0,
                    end_layer: 10,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.0,
                },
                StagePlacement {
                    node_id: "node-b".to_string(),
                    start_layer: 10,
                    end_layer: 20,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.0,
                },
            ],
        };

        let mb1 = execute_pipeline(&plan, 32, 1).expect("failed");
        let mb4 = execute_pipeline(&plan, 32, 4).expect("failed");

        assert_eq!(mb1.batch_count, 32);
        assert_eq!(mb4.batch_count, 8);
        assert!(mb4.total_time_ms > 0.0);
    }

    #[test]
    fn execution_supports_npu_stage_metrics() {
        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "node-npu".to_string(),
                    start_layer: 0,
                    end_layer: 8,
                    device: DeviceKind::Npu,
                    est_latency_ms: 0.9,
                },
                StagePlacement {
                    node_id: "node-gpu".to_string(),
                    start_layer: 8,
                    end_layer: 16,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.1,
                },
            ],
        };

        let result = execute_pipeline(&plan, 12, 3).expect("failed");
        assert_eq!(result.stage_count, 2);
        assert_eq!(result.batch_count, 4);
        assert_eq!(result.stage_stats.len(), 2);
        assert!(result.stage_stats.iter().any(|s| s.stage_idx == 0));
        assert!(result.total_time_ms > 0.0);
        assert!(result.throughput_tokens_per_sec > 0.0);
    }

    #[test]
    fn tcp_loopback_execution_reports_metrics() {
        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "node-a".to_string(),
                    start_layer: 0,
                    end_layer: 10,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.0,
                },
                StagePlacement {
                    node_id: "node-b".to_string(),
                    start_layer: 10,
                    end_layer: 20,
                    device: DeviceKind::Cpu,
                    est_latency_ms: 2.0,
                },
            ],
        };

        let result = execute_pipeline_tcp_loopback(&plan, 16, 2).expect("failed");
        assert_eq!(result.token_count, 16);
        assert_eq!(result.batch_count, 8);
        assert_eq!(result.stage_stats.len(), 2);
        assert!(result.total_time_ms > 0.0);
        assert!(result.throughput_tokens_per_sec > 0.0);
        assert!(
            result.p99_token_latency_ms >= result.p95_token_latency_ms,
            "p99 ({}) must be >= p95 ({})",
            result.p99_token_latency_ms,
            result.p95_token_latency_ms
        );
    }

    #[test]
    fn elems_per_token_config_scales_payload_size_and_still_completes() {
        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "node-a".to_string(),
                    start_layer: 0,
                    end_layer: 10,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.0,
                },
                StagePlacement {
                    node_id: "node-b".to_string(),
                    start_layer: 10,
                    end_layer: 20,
                    device: DeviceKind::Cpu,
                    est_latency_ms: 2.0,
                },
            ],
        };

        // 4096 hidden_dim * 2 bytes (fp16/bf16) / 4 bytes per wire f32 = 2048
        // elements/token — a real 7B-class model's per-token activation size,
        // instead of the default 16-element synthetic stand-in.
        let config = TcpTransportConfig {
            elems_per_token: 2048,
            ..TcpTransportConfig::default()
        };

        let result = execute_pipeline_tcp_loopback_with_config(&plan, 8, 2, config)
            .expect("large-payload loopback execution failed");
        assert_eq!(result.token_count, 8);
        assert!(result.total_time_ms > 0.0);
        assert!(
            result.p99_token_latency_ms >= result.p95_token_latency_ms,
            "p99 ({}) must be >= p95 ({})",
            result.p99_token_latency_ms,
            result.p95_token_latency_ms
        );
    }

    #[test]
    fn tcp_loopback_execution_with_hardening_config_reports_metrics() {
        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "node-a".to_string(),
                    start_layer: 0,
                    end_layer: 12,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.5,
                },
                StagePlacement {
                    node_id: "node-b".to_string(),
                    start_layer: 12,
                    end_layer: 24,
                    device: DeviceKind::Cpu,
                    est_latency_ms: 2.5,
                },
            ],
        };

        let result = execute_pipeline_tcp_loopback_with_config(
            &plan,
            24,
            3,
            TcpTransportConfig {
                max_inflight_batches: 4,
                reconnect_attempts: 4,
                reconnect_backoff_ms: 5,
                auth_token: Some("test-token".to_string()),
                ..Default::default()
            },
        )
        .expect("hardened loopback failed");

        assert_eq!(result.token_count, 24);
        assert_eq!(result.batch_count, 8);
        assert_eq!(result.stage_stats.len(), 2);
        assert!(result.total_time_ms > 0.0);
        assert!(result.throughput_tokens_per_sec > 0.0);
    }

    #[test]
    fn transport_rejects_auth_mismatch_frames() {
        let batch = TransportBatch {
            batch_id: 7,
            tokens_in_batch: 4,
            payload: vec![0.1, 0.2, 0.3, 0.4],
        };
        let mut encoded = Vec::new();
        let mut frame_buf = Vec::new();
        write_transport_batch(&mut encoded, &batch, 0, Some("token-a"), &mut frame_buf)
            .expect("encode frame");

        let mut cursor = Cursor::new(encoded);
        let mut payload_buf = Vec::new();
        let err = read_transport_batch(&mut cursor, 0, Some("token-b"), &mut payload_buf)
            .expect_err("mismatched token should fail");
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    #[test]
    fn transport_rejects_unexpected_source_stage() {
        let batch = TransportBatch {
            batch_id: 2,
            tokens_in_batch: 2,
            payload: vec![1.0, 2.0],
        };
        let mut encoded = Vec::new();
        let mut frame_buf = Vec::new();
        write_transport_batch(&mut encoded, &batch, 1, Some("token"), &mut frame_buf)
            .expect("encode frame");

        let mut cursor = Cursor::new(encoded);
        let mut payload_buf = Vec::new();
        let err = read_transport_batch(&mut cursor, 0, Some("token"), &mut payload_buf)
            .expect_err("source-stage mismatch should fail");
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    #[cfg(unix)]
    #[test]
    fn unix_socket_loopback_execution_reports_metrics() {
        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "node-a".to_string(),
                    start_layer: 0,
                    end_layer: 10,
                    device: DeviceKind::Gpu,
                    est_latency_ms: 1.0,
                },
                StagePlacement {
                    node_id: "node-b".to_string(),
                    start_layer: 10,
                    end_layer: 20,
                    device: DeviceKind::Cpu,
                    est_latency_ms: 2.0,
                },
            ],
        };

        let result = execute_pipeline_tcp_loopback_with_config(
            &plan,
            16,
            2,
            TcpTransportConfig {
                transport: TransportKind::Unix,
                ..Default::default()
            },
        )
        .expect("unix socket loopback failed");

        assert_eq!(result.token_count, 16);
        assert_eq!(result.batch_count, 8);
        assert_eq!(result.stage_stats.len(), 2);
        assert!(result.total_time_ms > 0.0);
        assert!(result.throughput_tokens_per_sec > 0.0);
    }

    #[test]
    fn stage_handshake_round_trips_layer_count_and_device() {
        let stage = StagePlacement {
            node_id: "coordinator-local".to_string(),
            start_layer: 5,
            end_layer: 37,
            device: DeviceKind::Gpu,
            est_latency_ms: 12.0,
        };
        let mut buf = Vec::new();
        write_stage_handshake(&mut buf, &stage).expect("handshake write failed");

        let mut cursor = Cursor::new(buf);
        let decoded = read_stage_handshake(&mut cursor).expect("handshake read failed");
        assert_eq!(decoded.num_layers(), stage.num_layers());
        assert_eq!(decoded.device, DeviceKind::Gpu);
    }

    #[test]
    fn execute_pipeline_with_remote_stage_rejects_when_remote_node_has_no_stages() {
        let plan = PipelinePlan {
            stages: vec![StagePlacement {
                node_id: "solo".to_string(),
                start_layer: 0,
                end_layer: 10,
                device: DeviceKind::Cpu,
                est_latency_ms: 1.0,
            }],
        };
        let err = execute_pipeline_with_remote_stage(
            &plan,
            "solo",
            "nowhere",
            8,
            2,
            TcpTransportConfig::default(),
            "127.0.0.1:1".parse().unwrap(),
        )
        .unwrap_err();
        assert!(
            err.contains("no pipeline stages assigned to node 'nowhere'"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn merge_stages_for_node_collapses_multiple_chunks_into_one_placement() {
        // Regression: real layer assignment splits one node's range into
        // several raw stages (verified manually: 60 layers / 2 nodes
        // produced 11 raw stages, not 2) — merging must still produce the
        // node's FULL range, not just its first chunk.
        let stages = vec![
            StagePlacement {
                node_id: "node-remote".to_string(),
                start_layer: 32,
                end_layer: 38,
                device: DeviceKind::Gpu,
                est_latency_ms: 1.0,
            },
            StagePlacement {
                node_id: "node-remote".to_string(),
                start_layer: 38,
                end_layer: 44,
                device: DeviceKind::Gpu,
                est_latency_ms: 1.5,
            },
            StagePlacement {
                node_id: "node-local".to_string(),
                start_layer: 0,
                end_layer: 32,
                device: DeviceKind::Cpu,
                est_latency_ms: 3.0,
            },
        ];
        let merged = merge_stages_for_node("node-remote", &stages).expect("merge failed");
        assert_eq!(merged.start_layer, 32);
        assert_eq!(merged.end_layer, 44);
        assert_eq!(merged.num_layers(), 12);
        assert_eq!(merged.device, DeviceKind::Gpu);
        assert!((merged.est_latency_ms - 2.5).abs() < 1e-6);
    }

    /// The real thing, end to end: a genuine second OS thread (standing in
    /// for a genuine second OS *process*, which the CLI-level integration
    /// test in the ghost-link crate covers) binds a real TCP listener on an
    /// OS-assigned port, and the coordinator function connects out to it —
    /// not the local-bind-on-both-ends simulation every other function in
    /// this file uses. Proves the round trip is real by asserting non-zero
    /// bridge time was actually measured, and that the worker's own
    /// independently-tracked batch count agrees with the coordinator's.
    #[test]
    fn execute_pipeline_with_remote_stage_does_a_real_tcp_round_trip() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("failed to bind test listener");
        let worker_addr = listener.local_addr().expect("failed to read local_addr");

        let worker_handle =
            thread::spawn(move || run_stage_worker(listener, &TcpTransportConfig::default()));

        let plan = PipelinePlan {
            stages: vec![
                StagePlacement {
                    node_id: "local".to_string(),
                    start_layer: 0,
                    end_layer: 10,
                    device: DeviceKind::Cpu,
                    est_latency_ms: 1.0,
                },
                StagePlacement {
                    node_id: "remote".to_string(),
                    start_layer: 10,
                    end_layer: 20,
                    device: DeviceKind::Cpu,
                    est_latency_ms: 1.0,
                },
            ],
        };

        let result = execute_pipeline_with_remote_stage(
            &plan,
            "local",
            "remote",
            16,
            2,
            TcpTransportConfig::default(),
            worker_addr,
        )
        .expect("real remote-stage execution failed");

        let worker_summary = worker_handle
            .join()
            .expect("worker thread panicked")
            .expect("worker returned an error");

        assert_eq!(result.token_count, 16);
        assert_eq!(result.batch_count, 8);
        assert_eq!(result.stage_stats.len(), 2);
        assert_eq!(worker_summary.batches_processed, 8);
        assert_eq!(
            result.stage_stats[1].processed_batches,
            worker_summary.batches_processed,
            "coordinator's batch count must agree with what the independent worker process actually processed"
        );
        assert!(
            result.stage_stats[1].avg_bridge_write_ms > 0.0,
            "remote round-trip time must be non-zero for a real socket hop, got {}",
            result.stage_stats[1].avg_bridge_write_ms
        );
    }

    #[test]
    fn spawn_tcp_bridge_skips_connection_attempts_when_circuit_breaker_is_open() {
        use crate::circuit_breaker::{CircuitBreakerConfig, CircuitState};

        // Bind-then-drop reliably yields an address nothing is listening on.
        let dead_addr = {
            let l = TcpListener::bind("127.0.0.1:0").unwrap();
            l.local_addr().unwrap()
        };
        let dummy_listener = BridgeListener::Tcp(TcpListener::bind("127.0.0.1:0").unwrap());

        let breaker = CircuitBreaker::with_config(CircuitBreakerConfig {
            failure_threshold: 1,
            open_duration_secs: 3600,
            reset_timeout_secs: 3600,
        });
        breaker.record_failure();
        assert_eq!(breaker.current_state(), CircuitState::Open);

        let (in_tx, in_rx) = mpsc::sync_channel::<TransportBatch>(1);
        let (out_tx, _out_rx) = mpsc::sync_channel::<TransportBatch>(1);
        drop(in_tx); // closes the passthrough loop's input immediately

        let config = TcpTransportConfig {
            reconnect_attempts: 5,
            reconnect_backoff_ms: 2000,
            ..TcpTransportConfig::default()
        };

        let start = Instant::now();
        let handle = spawn_tcp_bridge(
            0,
            in_rx,
            out_tx,
            config,
            dummy_listener,
            BridgeAddr::Tcp(dead_addr),
            Some(breaker),
        );
        handle.join().expect("bridge thread panicked");

        // 5 attempts * 2s backoff would take >=10s if the open breaker weren't
        // honored; a healthy short-circuit finishes in well under a second.
        assert!(
            start.elapsed() < Duration::from_millis(1500),
            "open circuit breaker should skip connection attempts entirely, took {:?}",
            start.elapsed()
        );
    }
}