aprender-test-lib 0.31.1

Probar: Rust-native testing framework with pixel coverage, TUI snapshots, and visual regression
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
//! DistributedBrick: Work-stealing and data locality (PROBAR-SPEC-009-P10)
//!
//! This module enables distributed brick execution with:
//! - Work-stealing across nodes
//! - Data locality awareness
//! - Multi-backend dispatch (CPU/GPU/Remote/SIMD)
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                   DISTRIBUTED BRICK FLOW                     │
//! ├─────────────────────────────────────────────────────────────┤
//! │                                                              │
//! │  1. DistributedBrick<B> wraps any Brick                     │
//! │  2. BrickDataTracker tracks data locality                   │
//! │  3. MultiBrickExecutor selects best backend                 │
//! │  4. BrickCoordinator handles PUB/SUB coordination           │
//! │                                                              │
//! └─────────────────────────────────────────────────────────────┘
//! ```
//!
//! # References
//!
//! - PROBAR-SPEC-009-P10: Distribution - Repartir Integration

// Allow expect for RwLock - lock poisoning is truly exceptional
#![allow(clippy::expect_used)]

use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

use super::{Brick, BrickAssertion, BrickBudget, BrickError, BrickResult, BrickVerification};

/// Unique identifier for a worker node
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WorkerId(pub u64);

impl WorkerId {
    /// Create a new worker ID
    #[must_use]
    pub const fn new(id: u64) -> Self {
        Self(id)
    }

    /// Get the underlying ID value
    #[must_use]
    pub const fn value(&self) -> u64 {
        self.0
    }
}

impl fmt::Display for WorkerId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "worker-{}", self.0)
    }
}

/// Execution backend for brick operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Backend {
    /// CPU execution with standard instructions
    Cpu,
    /// GPU execution via WebGPU/wgpu
    Gpu,
    /// Remote execution on another node
    Remote,
    /// CPU execution with SIMD acceleration
    Simd,
}

impl Backend {
    /// Check if backend is available on current system
    #[must_use]
    pub fn is_available(&self) -> bool {
        match self {
            Self::Cpu | Self::Simd => true,
            Self::Gpu => cfg!(feature = "gpu"),
            // Remote backend requires distributed feature (not yet implemented)
            Self::Remote => false,
        }
    }

    /// Get relative performance estimate (higher = faster)
    #[must_use]
    pub const fn performance_estimate(&self) -> u32 {
        match self {
            Self::Gpu => 100,
            Self::Simd => 50,
            Self::Cpu => 10,
            Self::Remote => 5, // Network latency
        }
    }
}

impl Default for Backend {
    fn default() -> Self {
        Self::Cpu
    }
}

/// Input data for brick execution
#[derive(Debug, Clone, Default)]
pub struct BrickInput {
    /// Input tensor data
    pub data: Vec<f32>,
    /// Input shape dimensions
    pub shape: Vec<usize>,
    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

impl BrickInput {
    /// Create new brick input
    #[must_use]
    pub fn new(data: Vec<f32>, shape: Vec<usize>) -> Self {
        Self {
            data,
            shape,
            metadata: HashMap::new(),
        }
    }

    /// Get total size in bytes
    #[must_use]
    pub fn size_bytes(&self) -> usize {
        self.data.len() * std::mem::size_of::<f32>()
    }

    /// Get total element count
    #[must_use]
    pub fn element_count(&self) -> usize {
        self.data.len()
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }
}

/// Output data from brick execution
#[derive(Debug, Clone, Default)]
pub struct BrickOutput {
    /// Output tensor data
    pub data: Vec<f32>,
    /// Output shape dimensions
    pub shape: Vec<usize>,
    /// Execution metrics
    pub metrics: ExecutionMetrics,
}

impl BrickOutput {
    /// Create new brick output
    #[must_use]
    pub fn new(data: Vec<f32>, shape: Vec<usize>) -> Self {
        Self {
            data,
            shape,
            metrics: ExecutionMetrics::default(),
        }
    }

    /// Get total size in bytes
    #[must_use]
    pub fn size_bytes(&self) -> usize {
        self.data.len() * std::mem::size_of::<f32>()
    }
}

/// Metrics from brick execution
#[derive(Debug, Clone, Default)]
pub struct ExecutionMetrics {
    /// Time to execute
    pub execution_time: Duration,
    /// Backend used
    pub backend: Backend,
    /// Worker that executed
    pub worker_id: Option<WorkerId>,
    /// Data transfer time (if remote)
    pub transfer_time: Option<Duration>,
}

impl ExecutionMetrics {
    /// Create new execution metrics
    #[must_use]
    pub fn new(execution_time: Duration, backend: Backend) -> Self {
        Self {
            execution_time,
            backend,
            worker_id: None,
            transfer_time: None,
        }
    }
}

/// Distributed brick wrapper for multi-backend execution
///
/// Wraps any `Brick` to enable distributed execution with:
/// - Backend selection (CPU/GPU/Remote/SIMD)
/// - Data dependency tracking for locality
/// - Work-stealing support
#[derive(Debug)]
pub struct DistributedBrick<B: Brick> {
    inner: B,
    backend: Backend,
    data_dependencies: Vec<String>,
    preferred_worker: Option<WorkerId>,
}

impl<B: Brick> DistributedBrick<B> {
    /// Create a new distributed brick wrapper
    #[must_use]
    pub fn new(inner: B) -> Self {
        Self {
            inner,
            backend: Backend::default(),
            data_dependencies: Vec::new(),
            preferred_worker: None,
        }
    }

    /// Set the preferred execution backend
    #[must_use]
    pub fn with_backend(mut self, backend: Backend) -> Self {
        self.backend = backend;
        self
    }

    /// Add data dependencies for locality-aware scheduling
    #[must_use]
    pub fn with_data_dependencies(mut self, deps: Vec<String>) -> Self {
        self.data_dependencies = deps;
        self
    }

    /// Set preferred worker for execution
    #[must_use]
    pub fn with_preferred_worker(mut self, worker: WorkerId) -> Self {
        self.preferred_worker = Some(worker);
        self
    }

    /// Get the inner brick
    #[must_use]
    pub fn inner(&self) -> &B {
        &self.inner
    }

    /// Get mutable access to inner brick
    pub fn inner_mut(&mut self) -> &mut B {
        &mut self.inner
    }

    /// Get current backend
    #[must_use]
    pub fn backend(&self) -> Backend {
        self.backend
    }

    /// Get data dependencies
    #[must_use]
    pub fn data_dependencies(&self) -> &[String] {
        &self.data_dependencies
    }

    /// Get preferred worker
    #[must_use]
    pub fn preferred_worker(&self) -> Option<WorkerId> {
        self.preferred_worker
    }

    /// Convert to a task specification for distributed execution
    #[must_use]
    pub fn to_task_spec(&self) -> TaskSpec {
        TaskSpec {
            brick_name: self.inner.brick_name().to_string(),
            backend: self.backend,
            data_dependencies: self.data_dependencies.clone(),
            preferred_worker: self.preferred_worker,
        }
    }
}

impl<B: Brick> Brick for DistributedBrick<B> {
    fn brick_name(&self) -> &'static str {
        self.inner.brick_name()
    }

    fn assertions(&self) -> &[BrickAssertion] {
        self.inner.assertions()
    }

    fn budget(&self) -> BrickBudget {
        self.inner.budget()
    }

    fn verify(&self) -> BrickVerification {
        self.inner.verify()
    }

    fn to_html(&self) -> String {
        self.inner.to_html()
    }

    fn to_css(&self) -> String {
        self.inner.to_css()
    }
}

/// Task specification for distributed execution
#[derive(Debug, Clone)]
pub struct TaskSpec {
    /// Brick name for identification
    pub brick_name: String,
    /// Requested backend
    pub backend: Backend,
    /// Data dependencies
    pub data_dependencies: Vec<String>,
    /// Preferred worker
    pub preferred_worker: Option<WorkerId>,
}

/// Data location entry for a specific piece of data
#[derive(Debug, Clone)]
pub struct DataLocation {
    /// Data key/identifier
    pub key: String,
    /// Workers that have this data
    pub workers: Vec<WorkerId>,
    /// Size of data in bytes
    pub size_bytes: usize,
    /// Last access time
    pub last_access: Instant,
}

/// Track where brick weights/data reside across workers
///
/// Used for locality-aware scheduling to minimize data movement.
#[derive(Debug)]
pub struct BrickDataTracker {
    /// Map from data key to location info
    locations: RwLock<HashMap<String, DataLocation>>,
}

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

impl BrickDataTracker {
    /// Create a new data tracker
    #[must_use]
    pub fn new() -> Self {
        Self {
            locations: RwLock::new(HashMap::new()),
        }
    }

    /// Register that a worker has certain data
    pub fn track_data(&self, key: &str, worker_id: WorkerId, size_bytes: usize) {
        let mut locations = self.locations.write().expect("lock poisoned");
        locations
            .entry(key.to_string())
            .and_modify(|loc| {
                if !loc.workers.contains(&worker_id) {
                    loc.workers.push(worker_id);
                }
                loc.last_access = Instant::now();
            })
            .or_insert_with(|| DataLocation {
                key: key.to_string(),
                workers: vec![worker_id],
                size_bytes,
                last_access: Instant::now(),
            });
    }

    /// Register that a worker has brick weights
    pub fn track_weights(&self, brick_name: &str, worker_id: WorkerId) {
        let key = format!("{}_weights", brick_name);
        self.track_data(&key, worker_id, 0);
    }

    /// Remove data location from a worker
    pub fn remove_data(&self, key: &str, worker_id: WorkerId) {
        let mut locations = self.locations.write().expect("lock poisoned");
        if let Some(loc) = locations.get_mut(key) {
            loc.workers.retain(|w| *w != worker_id);
        }
    }

    /// Get workers that have specific data
    #[must_use]
    pub fn get_workers_for_data(&self, key: &str) -> Vec<WorkerId> {
        let locations = self.locations.read().expect("lock poisoned");
        locations
            .get(key)
            .map_or(Vec::new(), |loc| loc.workers.clone())
    }

    /// Calculate affinity scores for workers based on data dependencies
    pub fn calculate_affinity(&self, dependencies: &[String]) -> HashMap<WorkerId, f64> {
        let locations = self.locations.read().expect("lock poisoned");
        let mut affinity: HashMap<WorkerId, f64> = HashMap::new();

        for dep in dependencies {
            if let Some(loc) = locations.get(dep) {
                let score_per_worker = 1.0 / loc.workers.len() as f64;
                for worker in &loc.workers {
                    *affinity.entry(*worker).or_insert(0.0) += score_per_worker;
                }
            }
        }

        // Normalize scores
        if !affinity.is_empty() {
            let max_score = affinity.values().cloned().fold(0.0_f64, f64::max);
            if max_score > 0.0 {
                for score in affinity.values_mut() {
                    *score /= max_score;
                }
            }
        }

        affinity
    }

    /// Find the best worker for a brick based on data locality
    #[must_use]
    pub fn find_best_worker(&self, brick: &dyn Brick) -> Option<WorkerId> {
        // Use brick name to find weights
        let weights_key = format!("{}_weights", brick.brick_name());
        let workers = self.get_workers_for_data(&weights_key);
        workers.first().copied()
    }

    /// Find best worker for distributed brick with dependencies
    #[must_use]
    pub fn find_best_worker_for_distributed<B: Brick>(
        &self,
        brick: &DistributedBrick<B>,
    ) -> Option<WorkerId> {
        // Check preferred worker first
        if let Some(preferred) = brick.preferred_worker() {
            return Some(preferred);
        }

        // Calculate affinity based on dependencies
        let affinity = self.calculate_affinity(brick.data_dependencies());
        affinity
            .into_iter()
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(worker, _)| worker)
    }

    /// Get total data size tracked
    #[must_use]
    pub fn total_data_size(&self) -> usize {
        let locations = self.locations.read().expect("lock poisoned");
        locations.values().map(|loc| loc.size_bytes).sum()
    }
}

/// Backend selector for choosing optimal execution backend
#[derive(Debug)]
pub struct BackendSelector {
    /// Minimum element count for GPU execution
    gpu_threshold: usize,
    /// Minimum element count for SIMD execution
    simd_threshold: usize,
    /// Maximum element count for CPU (else remote)
    cpu_max_threshold: usize,
}

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

impl BackendSelector {
    /// Create a new backend selector with default thresholds
    #[must_use]
    pub fn new() -> Self {
        Self {
            gpu_threshold: 1_000_000,       // 1M elements for GPU
            simd_threshold: 10_000,         // 10K elements for SIMD
            cpu_max_threshold: 100_000_000, // 100M elements max for local
        }
    }

    /// Configure GPU threshold
    #[must_use]
    pub fn with_gpu_threshold(mut self, threshold: usize) -> Self {
        self.gpu_threshold = threshold;
        self
    }

    /// Configure SIMD threshold
    #[must_use]
    pub fn with_simd_threshold(mut self, threshold: usize) -> Self {
        self.simd_threshold = threshold;
        self
    }

    /// Configure CPU max threshold
    #[must_use]
    pub fn with_cpu_max_threshold(mut self, threshold: usize) -> Self {
        self.cpu_max_threshold = threshold;
        self
    }

    /// Select best backend based on input characteristics
    #[must_use]
    pub fn select(&self, element_count: usize, gpu_available: bool) -> Backend {
        // Too large for local - use remote if available (not yet implemented)
        if element_count > self.cpu_max_threshold && Backend::Remote.is_available() {
            return Backend::Remote;
        }

        // Large enough for GPU
        if element_count >= self.gpu_threshold && gpu_available {
            return Backend::Gpu;
        }

        // Medium size - use SIMD
        if element_count >= self.simd_threshold {
            return Backend::Simd;
        }

        // Small - use plain CPU
        Backend::Cpu
    }

    /// Select backend for a brick with input
    #[must_use]
    pub fn select_for_brick(
        &self,
        _brick_complexity: u32,
        input_size: usize,
        gpu_available: bool,
    ) -> Backend {
        // Future: factor in brick_complexity
        self.select(input_size, gpu_available)
    }
}

/// Multi-backend executor for brick operations
///
/// Dispatches brick execution to the best available backend.
#[derive(Debug)]
pub struct MultiBrickExecutor {
    selector: BackendSelector,
    gpu_available: bool,
    data_tracker: Arc<BrickDataTracker>,
}

impl MultiBrickExecutor {
    /// Create a new multi-backend executor
    #[must_use]
    pub fn new(data_tracker: Arc<BrickDataTracker>) -> Self {
        Self {
            selector: BackendSelector::new(),
            gpu_available: cfg!(feature = "gpu"),
            data_tracker,
        }
    }

    /// Create with custom backend selector
    #[must_use]
    pub fn with_selector(mut self, selector: BackendSelector) -> Self {
        self.selector = selector;
        self
    }

    /// Set GPU availability
    #[must_use]
    pub fn with_gpu_available(mut self, available: bool) -> Self {
        self.gpu_available = available;
        self
    }

    /// Execute a brick on the best backend
    pub fn execute(&self, brick: &dyn Brick, input: BrickInput) -> BrickResult<BrickOutput> {
        let start = Instant::now();

        // Select backend
        let backend = self
            .selector
            .select(input.element_count(), self.gpu_available);

        // Execute on selected backend
        let (output_data, output_shape) = match backend {
            Backend::Cpu => self.execute_cpu(brick, &input)?,
            Backend::Simd => self.execute_simd(brick, &input)?,
            Backend::Gpu => self.execute_gpu(brick, &input)?,
            Backend::Remote => self.execute_remote(brick, &input)?,
        };

        let execution_time = start.elapsed();

        // Build output with metrics
        let mut output = BrickOutput::new(output_data, output_shape);
        output.metrics = ExecutionMetrics::new(execution_time, backend);

        Ok(output)
    }

    /// Execute distributed brick
    pub fn execute_distributed<B: Brick>(
        &self,
        brick: &DistributedBrick<B>,
        input: BrickInput,
    ) -> BrickResult<BrickOutput> {
        let start = Instant::now();

        // Use brick's preferred backend or select automatically
        let backend = brick.backend();

        // Find best worker for locality
        let worker_id = self.data_tracker.find_best_worker_for_distributed(brick);

        // Execute
        let (output_data, output_shape) = match backend {
            Backend::Cpu => self.execute_cpu(brick.inner(), &input)?,
            Backend::Simd => self.execute_simd(brick.inner(), &input)?,
            Backend::Gpu => self.execute_gpu(brick.inner(), &input)?,
            Backend::Remote => self.execute_remote(brick.inner(), &input)?,
        };

        let execution_time = start.elapsed();

        // Build output with metrics
        let mut output = BrickOutput::new(output_data, output_shape);
        output.metrics = ExecutionMetrics {
            execution_time,
            backend,
            worker_id,
            transfer_time: None,
        };

        Ok(output)
    }

    fn execute_cpu(
        &self,
        _brick: &dyn Brick,
        input: &BrickInput,
    ) -> BrickResult<(Vec<f32>, Vec<usize>)> {
        // Simple passthrough for now - real implementation would execute brick
        Ok((input.data.clone(), input.shape.clone()))
    }

    fn execute_simd(
        &self,
        _brick: &dyn Brick,
        input: &BrickInput,
    ) -> BrickResult<(Vec<f32>, Vec<usize>)> {
        // SIMD path - would use actual SIMD instructions
        Ok((input.data.clone(), input.shape.clone()))
    }

    fn execute_gpu(
        &self,
        _brick: &dyn Brick,
        input: &BrickInput,
    ) -> BrickResult<(Vec<f32>, Vec<usize>)> {
        // GPU path - would use WebGPU/wgpu
        if !self.gpu_available {
            return Err(BrickError::HtmlGenerationFailed {
                reason: "GPU not available".into(),
            });
        }
        Ok((input.data.clone(), input.shape.clone()))
    }

    fn execute_remote(
        &self,
        _brick: &dyn Brick,
        input: &BrickInput,
    ) -> BrickResult<(Vec<f32>, Vec<usize>)> {
        // Remote path - would serialize and send to remote worker
        if !Backend::Remote.is_available() {
            return Err(BrickError::HtmlGenerationFailed {
                reason: "Distributed execution not available".into(),
            });
        }
        Ok((input.data.clone(), input.shape.clone()))
    }

    /// Get the data tracker
    #[must_use]
    pub fn data_tracker(&self) -> &Arc<BrickDataTracker> {
        &self.data_tracker
    }
}

/// Message for PUB/SUB coordination
#[derive(Debug, Clone)]
pub enum BrickMessage {
    /// Weight update message
    WeightUpdate {
        /// Name of the brick whose weights are being updated
        brick_name: String,
        /// Serialized weight data
        weights: Vec<u8>,
        /// Weight version number
        version: u64,
    },
    /// State change notification
    StateChange {
        /// Name of the brick that changed state
        brick_name: String,
        /// Event description
        event: String,
    },
    /// Request brick execution
    ExecutionRequest {
        /// Name of brick to execute
        brick_name: String,
        /// Key to input data
        input_key: String,
        /// Unique request ID for correlation
        request_id: u64,
    },
    /// Execution result
    ExecutionResult {
        /// Request ID this result corresponds to
        request_id: u64,
        /// Key to output data
        output_key: String,
        /// Whether execution succeeded
        success: bool,
    },
}

/// Subscription to brick events
#[derive(Debug)]
pub struct Subscription {
    topic: String,
    messages: Arc<RwLock<Vec<BrickMessage>>>,
}

impl Subscription {
    /// Get all pending messages
    #[must_use]
    pub fn drain(&self) -> Vec<BrickMessage> {
        let mut messages = self.messages.write().expect("lock poisoned");
        std::mem::take(&mut *messages)
    }

    /// Check if there are pending messages
    #[must_use]
    pub fn has_messages(&self) -> bool {
        let messages = self.messages.read().expect("lock poisoned");
        !messages.is_empty()
    }

    /// Get subscription topic
    #[must_use]
    pub fn topic(&self) -> &str {
        &self.topic
    }
}

// ============================================================================
// Work-Stealing Scheduler (Phase 10e)
// ============================================================================

/// A task that can be executed by workers and potentially stolen
#[derive(Debug, Clone)]
pub struct WorkStealingTask {
    /// Unique task ID
    pub id: u64,
    /// Task specification
    pub spec: TaskSpec,
    /// Input data key
    pub input_key: String,
    /// Priority (higher = more urgent)
    pub priority: u32,
    /// Creation time
    pub created_at: Instant,
}

impl WorkStealingTask {
    /// Create a new work-stealing task
    #[must_use]
    pub fn new(id: u64, spec: TaskSpec, input_key: String) -> Self {
        Self {
            id,
            spec,
            input_key,
            priority: 0,
            created_at: Instant::now(),
        }
    }

    /// Set task priority
    #[must_use]
    pub fn with_priority(mut self, priority: u32) -> Self {
        self.priority = priority;
        self
    }

    /// Get task age
    #[must_use]
    pub fn age(&self) -> Duration {
        self.created_at.elapsed()
    }
}

/// Per-worker task queue supporting work-stealing
#[derive(Debug)]
pub struct WorkerQueue {
    /// Worker ID
    worker_id: WorkerId,
    /// Local task queue (owned tasks)
    local_queue: RwLock<Vec<WorkStealingTask>>,
    /// Number of tasks completed
    completed_count: AtomicU64,
    /// Number of tasks stolen from this queue
    stolen_count: AtomicU64,
}

impl WorkerQueue {
    /// Create a new worker queue
    #[must_use]
    pub fn new(worker_id: WorkerId) -> Self {
        Self {
            worker_id,
            local_queue: RwLock::new(Vec::new()),
            completed_count: AtomicU64::new(0),
            stolen_count: AtomicU64::new(0),
        }
    }

    /// Push a task to the local queue
    pub fn push(&self, task: WorkStealingTask) {
        let mut queue = self.local_queue.write().expect("lock poisoned");
        queue.push(task);
        // Sort by priority (higher first)
        queue.sort_by(|a, b| b.priority.cmp(&a.priority));
    }

    /// Pop a task from the local queue (highest priority first)
    pub fn pop(&self) -> Option<WorkStealingTask> {
        let mut queue = self.local_queue.write().expect("lock poisoned");
        if queue.is_empty() {
            return None;
        }
        Some(queue.remove(0)) // Get highest priority (front after sort)
    }

    /// Steal a task from this queue (lowest priority - be nice to owner)
    pub fn steal(&self) -> Option<WorkStealingTask> {
        let mut queue = self.local_queue.write().expect("lock poisoned");
        if queue.is_empty() {
            return None;
        }
        self.stolen_count.fetch_add(1, Ordering::Relaxed);
        queue.pop() // Steal lowest priority (back after sort)
    }

    /// Check if queue is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        let queue = self.local_queue.read().expect("lock poisoned");
        queue.is_empty()
    }

    /// Get queue length
    #[must_use]
    pub fn len(&self) -> usize {
        let queue = self.local_queue.read().expect("lock poisoned");
        queue.len()
    }

    /// Mark a task as completed
    pub fn mark_completed(&self) {
        self.completed_count.fetch_add(1, Ordering::Relaxed);
    }

    /// Get worker ID
    #[must_use]
    pub fn worker_id(&self) -> WorkerId {
        self.worker_id
    }

    /// Get completed count
    #[must_use]
    pub fn completed_count(&self) -> u64 {
        self.completed_count.load(Ordering::Relaxed)
    }

    /// Get stolen count
    #[must_use]
    pub fn stolen_count(&self) -> u64 {
        self.stolen_count.load(Ordering::Relaxed)
    }
}

/// Work-stealing scheduler for distributed brick execution
///
/// Implements work-stealing algorithm where idle workers steal tasks
/// from busy workers' queues. This provides automatic load balancing.
///
/// # Algorithm
///
/// 1. Each worker has a local deque (double-ended queue)
/// 2. Workers push/pop from their own queue (LIFO - good for cache locality)
/// 3. When idle, workers steal from other queues (FIFO - steal oldest tasks)
/// 4. Stealing considers data locality via `BrickDataTracker`
#[derive(Debug)]
pub struct WorkStealingScheduler {
    /// Worker queues indexed by worker ID
    queues: RwLock<HashMap<WorkerId, Arc<WorkerQueue>>>,
    /// Data tracker for locality-aware stealing
    data_tracker: Arc<BrickDataTracker>,
    /// Task ID counter
    task_counter: AtomicU64,
    /// Total tasks submitted
    submitted_count: AtomicU64,
}

impl WorkStealingScheduler {
    /// Create a new work-stealing scheduler
    #[must_use]
    pub fn new(data_tracker: Arc<BrickDataTracker>) -> Self {
        Self {
            queues: RwLock::new(HashMap::new()),
            data_tracker,
            task_counter: AtomicU64::new(0),
            submitted_count: AtomicU64::new(0),
        }
    }

    /// Register a worker with the scheduler
    pub fn register_worker(&self, worker_id: WorkerId) -> Arc<WorkerQueue> {
        let queue = Arc::new(WorkerQueue::new(worker_id));
        let mut queues = self.queues.write().expect("lock poisoned");
        queues.insert(worker_id, Arc::clone(&queue));
        queue
    }

    /// Unregister a worker
    pub fn unregister_worker(&self, worker_id: WorkerId) {
        let mut queues = self.queues.write().expect("lock poisoned");
        queues.remove(&worker_id);
    }

    /// Submit a task to the best worker based on locality
    pub fn submit(&self, spec: TaskSpec, input_key: String) -> u64 {
        let task_id = self.task_counter.fetch_add(1, Ordering::SeqCst);
        let task = WorkStealingTask::new(task_id, spec.clone(), input_key);

        // Find best worker based on data locality
        let target_worker = self.find_best_worker_for_task(&spec);

        let queues = self.queues.read().expect("lock poisoned");
        if let Some(queue) = target_worker.and_then(|w| queues.get(&w)) {
            queue.push(task);
        } else if let Some((_, queue)) = queues.iter().next() {
            // Fallback to first available worker
            queue.push(task);
        }

        self.submitted_count.fetch_add(1, Ordering::Relaxed);
        task_id
    }

    /// Submit with explicit priority
    pub fn submit_priority(&self, spec: TaskSpec, input_key: String, priority: u32) -> u64 {
        let task_id = self.task_counter.fetch_add(1, Ordering::SeqCst);
        let task = WorkStealingTask::new(task_id, spec.clone(), input_key).with_priority(priority);

        let target_worker = self.find_best_worker_for_task(&spec);

        let queues = self.queues.read().expect("lock poisoned");
        if let Some(queue) = target_worker.and_then(|w| queues.get(&w)) {
            queue.push(task);
        } else if let Some((_, queue)) = queues.iter().next() {
            queue.push(task);
        }

        self.submitted_count.fetch_add(1, Ordering::Relaxed);
        task_id
    }

    /// Try to get work for a worker (local pop or steal)
    pub fn get_work(&self, worker_id: WorkerId) -> Option<WorkStealingTask> {
        let queues = self.queues.read().expect("lock poisoned");

        // First try local queue
        if let Some(queue) = queues.get(&worker_id) {
            if let Some(task) = queue.pop() {
                return Some(task);
            }
        }

        // Try to steal from other workers
        self.try_steal(worker_id, &queues)
    }

    /// Try to steal work from another worker's queue
    fn try_steal(
        &self,
        stealer_id: WorkerId,
        queues: &HashMap<WorkerId, Arc<WorkerQueue>>,
    ) -> Option<WorkStealingTask> {
        // Find queues with work, preferring those with data locality
        let mut candidates: Vec<_> = queues
            .iter()
            .filter(|(id, q)| **id != stealer_id && !q.is_empty())
            .collect();

        if candidates.is_empty() {
            return None;
        }

        // Sort by queue length (steal from busiest)
        candidates.sort_by(|a, b| b.1.len().cmp(&a.1.len()));

        // Try to steal from the busiest queue
        for (_, queue) in candidates {
            if let Some(task) = queue.steal() {
                return Some(task);
            }
        }

        None
    }

    /// Find best worker for a task based on data locality
    fn find_best_worker_for_task(&self, spec: &TaskSpec) -> Option<WorkerId> {
        // Check preferred worker
        if let Some(preferred) = spec.preferred_worker {
            return Some(preferred);
        }

        // Calculate affinity based on data dependencies
        let affinity = self
            .data_tracker
            .calculate_affinity(&spec.data_dependencies);
        affinity
            .into_iter()
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(worker, _)| worker)
    }

    /// Get scheduler statistics
    #[must_use]
    pub fn stats(&self) -> SchedulerStats {
        let queues = self.queues.read().expect("lock poisoned");

        let worker_stats: Vec<_> = queues
            .values()
            .map(|q| WorkerStats {
                worker_id: q.worker_id(),
                queue_length: q.len(),
                completed: q.completed_count(),
                stolen_from: q.stolen_count(),
            })
            .collect();

        let total_pending: usize = worker_stats.iter().map(|s| s.queue_length).sum();
        let total_completed: u64 = worker_stats.iter().map(|s| s.completed).sum();
        let total_stolen: u64 = worker_stats.iter().map(|s| s.stolen_from).sum();

        SchedulerStats {
            worker_count: queues.len(),
            total_submitted: self.submitted_count.load(Ordering::Relaxed),
            total_pending,
            total_completed,
            total_stolen,
            workers: worker_stats,
        }
    }

    /// Get the data tracker
    #[must_use]
    pub fn data_tracker(&self) -> &Arc<BrickDataTracker> {
        &self.data_tracker
    }
}

/// Statistics for a single worker
#[derive(Debug, Clone)]
pub struct WorkerStats {
    /// Worker ID
    pub worker_id: WorkerId,
    /// Current queue length
    pub queue_length: usize,
    /// Tasks completed
    pub completed: u64,
    /// Tasks stolen from this worker
    pub stolen_from: u64,
}

/// Scheduler-wide statistics
#[derive(Debug, Clone)]
pub struct SchedulerStats {
    /// Number of registered workers
    pub worker_count: usize,
    /// Total tasks submitted
    pub total_submitted: u64,
    /// Total tasks pending across all queues
    pub total_pending: usize,
    /// Total tasks completed
    pub total_completed: u64,
    /// Total tasks stolen (indicates load balancing activity)
    pub total_stolen: u64,
    /// Per-worker statistics
    pub workers: Vec<WorkerStats>,
}

// ============================================================================
// PUB/SUB Coordinator
// ============================================================================

/// PUB/SUB coordinator for brick communication
///
/// Enables distributed coordination via publish/subscribe messaging.
#[derive(Debug)]
pub struct BrickCoordinator {
    /// Active subscriptions by topic
    subscriptions: RwLock<HashMap<String, Vec<Arc<RwLock<Vec<BrickMessage>>>>>>,
    /// Message counter for request IDs
    message_counter: AtomicU64,
}

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

impl BrickCoordinator {
    /// Create a new coordinator
    #[must_use]
    pub fn new() -> Self {
        Self {
            subscriptions: RwLock::new(HashMap::new()),
            message_counter: AtomicU64::new(0),
        }
    }

    /// Subscribe to a topic
    #[must_use]
    pub fn subscribe(&self, topic: &str) -> Subscription {
        let messages = Arc::new(RwLock::new(Vec::new()));
        {
            let mut subs = self.subscriptions.write().expect("lock poisoned");
            subs.entry(topic.to_string())
                .or_default()
                .push(Arc::clone(&messages));
        }
        Subscription {
            topic: topic.to_string(),
            messages,
        }
    }

    /// Subscribe to brick events
    #[must_use]
    pub fn subscribe_brick(&self, brick_name: &str) -> Subscription {
        let topic = format!("brick/{}/events", brick_name);
        self.subscribe(&topic)
    }

    /// Publish a message to a topic
    pub fn publish(&self, topic: &str, message: BrickMessage) {
        let subs = self.subscriptions.read().expect("lock poisoned");
        if let Some(subscribers) = subs.get(topic) {
            for sub in subscribers {
                let mut messages = sub.write().expect("lock poisoned");
                messages.push(message.clone());
            }
        }
    }

    /// Broadcast weight updates for a brick
    pub fn broadcast_weights(&self, brick_name: &str, weights: Vec<u8>) {
        let topic = format!("brick/{}/weights", brick_name);
        let version = self.message_counter.fetch_add(1, Ordering::SeqCst);
        self.publish(
            &topic,
            BrickMessage::WeightUpdate {
                brick_name: brick_name.to_string(),
                weights,
                version,
            },
        );
    }

    /// Broadcast state change for a brick
    pub fn broadcast_state_change(&self, brick_name: &str, event: &str) {
        let topic = format!("brick/{}/events", brick_name);
        self.publish(
            &topic,
            BrickMessage::StateChange {
                brick_name: brick_name.to_string(),
                event: event.to_string(),
            },
        );
    }

    /// Generate a unique request ID
    #[must_use]
    pub fn next_request_id(&self) -> u64 {
        self.message_counter.fetch_add(1, Ordering::SeqCst)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    struct TestBrick {
        name: &'static str,
    }

    impl Brick for TestBrick {
        fn brick_name(&self) -> &'static str {
            self.name
        }

        fn assertions(&self) -> &[BrickAssertion] {
            &[BrickAssertion::TextVisible]
        }

        fn budget(&self) -> BrickBudget {
            BrickBudget::uniform(16)
        }

        fn verify(&self) -> BrickVerification {
            BrickVerification {
                passed: vec![BrickAssertion::TextVisible],
                failed: vec![],
                verification_time: Duration::from_micros(100),
            }
        }

        fn to_html(&self) -> String {
            format!("<div>{}</div>", self.name)
        }

        fn to_css(&self) -> String {
            ".test { }".into()
        }
    }

    #[test]
    fn test_worker_id() {
        let id = WorkerId::new(42);
        assert_eq!(id.value(), 42);
        assert_eq!(format!("{id}"), "worker-42");
    }

    #[test]
    fn test_backend_availability() {
        assert!(Backend::Cpu.is_available());
        assert!(Backend::Simd.is_available());
        // GPU/Remote depend on feature flags
    }

    #[test]
    fn test_backend_performance() {
        assert!(Backend::Gpu.performance_estimate() > Backend::Simd.performance_estimate());
        assert!(Backend::Simd.performance_estimate() > Backend::Cpu.performance_estimate());
    }

    #[test]
    fn test_distributed_brick_creation() {
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner)
            .with_backend(Backend::Gpu)
            .with_data_dependencies(vec!["weights".into(), "biases".into()])
            .with_preferred_worker(WorkerId::new(1));

        assert_eq!(distributed.backend(), Backend::Gpu);
        assert_eq!(distributed.data_dependencies().len(), 2);
        assert_eq!(distributed.preferred_worker(), Some(WorkerId::new(1)));
        assert_eq!(distributed.brick_name(), "Test");
    }

    #[test]
    fn test_distributed_brick_implements_brick() {
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner);

        // Verify it implements Brick trait
        assert!(distributed.verify().is_valid());
        assert_eq!(distributed.budget().total_ms, 16);
    }

    #[test]
    fn test_task_spec() {
        let inner = TestBrick { name: "TestTask" };
        let distributed = DistributedBrick::new(inner)
            .with_backend(Backend::Simd)
            .with_data_dependencies(vec!["model".into()]);

        let spec = distributed.to_task_spec();
        assert_eq!(spec.brick_name, "TestTask");
        assert_eq!(spec.backend, Backend::Simd);
        assert_eq!(spec.data_dependencies, vec!["model"]);
    }

    #[test]
    fn test_brick_input_output() {
        let input = BrickInput::new(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2]);
        assert_eq!(input.element_count(), 4);
        assert_eq!(input.size_bytes(), 16);

        let output = BrickOutput::new(vec![5.0, 6.0], vec![2]);
        assert_eq!(output.size_bytes(), 8);
    }

    #[test]
    fn test_data_tracker() {
        let tracker = BrickDataTracker::new();

        // Track some data
        tracker.track_data("model_weights", WorkerId::new(1), 1024);
        tracker.track_data("model_weights", WorkerId::new(2), 1024);
        tracker.track_data("biases", WorkerId::new(1), 256);

        // Check workers
        let workers = tracker.get_workers_for_data("model_weights");
        assert_eq!(workers.len(), 2);

        // Calculate affinity
        let affinity = tracker.calculate_affinity(&["model_weights".into(), "biases".into()]);
        assert!(affinity.get(&WorkerId::new(1)).unwrap_or(&0.0) > &0.0);
    }

    #[test]
    fn test_data_tracker_find_best_worker() {
        let tracker = BrickDataTracker::new();

        let brick = TestBrick { name: "MelBrick" };
        tracker.track_weights("MelBrick", WorkerId::new(5));

        let best = tracker.find_best_worker(&brick);
        assert_eq!(best, Some(WorkerId::new(5)));
    }

    #[test]
    fn test_backend_selector() {
        let selector = BackendSelector::new()
            .with_gpu_threshold(1000)
            .with_simd_threshold(100);

        // Small input -> CPU
        assert_eq!(selector.select(50, true), Backend::Cpu);

        // Medium input -> SIMD
        assert_eq!(selector.select(500, true), Backend::Simd);

        // Large input with GPU -> GPU
        assert_eq!(selector.select(5000, true), Backend::Gpu);

        // Large input without GPU -> SIMD
        assert_eq!(selector.select(5000, false), Backend::Simd);
    }

    #[test]
    fn test_multi_executor() {
        let tracker = Arc::new(BrickDataTracker::new());
        let executor = MultiBrickExecutor::new(tracker);

        let brick = TestBrick { name: "Test" };
        let input = BrickInput::new(vec![1.0, 2.0, 3.0], vec![3]);

        let result = executor.execute(&brick, input);
        assert!(result.is_ok());

        let output = result.expect("execution should succeed");
        assert_eq!(output.data.len(), 3);
        assert!(output.metrics.execution_time >= Duration::ZERO);
    }

    #[test]
    fn test_brick_coordinator() {
        let coordinator = BrickCoordinator::new();

        // Subscribe to events
        let sub = coordinator.subscribe_brick("MyBrick");

        // Broadcast event
        coordinator.broadcast_state_change("MyBrick", "loaded");

        // Check subscription received message
        assert!(sub.has_messages());
        let messages = sub.drain();
        assert_eq!(messages.len(), 1);
        matches!(&messages[0], BrickMessage::StateChange { brick_name, .. } if brick_name == "MyBrick");
    }

    #[test]
    fn test_coordinator_weight_broadcast() {
        let coordinator = BrickCoordinator::new();

        let sub = coordinator.subscribe("brick/Encoder/weights");
        coordinator.broadcast_weights("Encoder", vec![1, 2, 3, 4]);

        let messages = sub.drain();
        assert_eq!(messages.len(), 1);
        match &messages[0] {
            BrickMessage::WeightUpdate {
                brick_name,
                weights,
                version,
            } => {
                assert_eq!(brick_name, "Encoder");
                assert_eq!(weights, &vec![1, 2, 3, 4]);
                assert_eq!(*version, 0);
            }
            _ => panic!("Expected WeightUpdate message"),
        }
    }

    #[test]
    fn test_subscription_topic() {
        let coordinator = BrickCoordinator::new();
        let sub = coordinator.subscribe("my/topic");
        assert_eq!(sub.topic(), "my/topic");
    }

    #[test]
    fn test_execution_metrics() {
        let metrics = ExecutionMetrics::new(Duration::from_millis(50), Backend::Gpu);
        assert_eq!(metrics.execution_time, Duration::from_millis(50));
        assert_eq!(metrics.backend, Backend::Gpu);
        assert!(metrics.worker_id.is_none());
    }

    // ========================================================================
    // Work-Stealing Scheduler Tests (Phase 10e)
    // ========================================================================

    #[test]
    fn test_work_stealing_task() {
        let spec = TaskSpec {
            brick_name: "TestBrick".into(),
            backend: Backend::Cpu,
            data_dependencies: vec![],
            preferred_worker: None,
        };
        let task = WorkStealingTask::new(1, spec, "input_key".into()).with_priority(10);

        assert_eq!(task.id, 1);
        assert_eq!(task.priority, 10);
        assert_eq!(task.input_key, "input_key");
        assert!(task.age() >= Duration::ZERO);
    }

    #[test]
    fn test_worker_queue_basic() {
        let queue = WorkerQueue::new(WorkerId::new(1));

        assert!(queue.is_empty());
        assert_eq!(queue.len(), 0);

        let spec = TaskSpec {
            brick_name: "Test".into(),
            backend: Backend::Cpu,
            data_dependencies: vec![],
            preferred_worker: None,
        };
        let task = WorkStealingTask::new(1, spec, "key".into());
        queue.push(task);

        assert!(!queue.is_empty());
        assert_eq!(queue.len(), 1);

        let popped = queue.pop();
        assert!(popped.is_some());
        assert!(queue.is_empty());
    }

    #[test]
    fn test_worker_queue_priority_ordering() {
        let queue = WorkerQueue::new(WorkerId::new(1));

        // Push tasks with different priorities
        for i in 0..5 {
            let spec = TaskSpec {
                brick_name: format!("Task{}", i),
                backend: Backend::Cpu,
                data_dependencies: vec![],
                preferred_worker: None,
            };
            let task = WorkStealingTask::new(i as u64, spec, "key".into()).with_priority(i);
            queue.push(task);
        }

        // Pop should return highest priority first
        let task = queue.pop().unwrap();
        assert_eq!(task.priority, 4);

        let task = queue.pop().unwrap();
        assert_eq!(task.priority, 3);
    }

    #[test]
    fn test_worker_queue_steal() {
        let queue = WorkerQueue::new(WorkerId::new(1));

        // Push 3 tasks with priorities 0, 1, 2
        for i in 0..3 {
            let spec = TaskSpec {
                brick_name: format!("Task{}", i),
                backend: Backend::Cpu,
                data_dependencies: vec![],
                preferred_worker: None,
            };
            let task = WorkStealingTask::new(i as u64, spec, "key".into()).with_priority(i);
            queue.push(task);
        }

        // Steal takes from front (lowest priority after sort)
        let stolen = queue.steal().unwrap();
        assert_eq!(stolen.priority, 0);
        assert_eq!(queue.stolen_count(), 1);

        // Queue still has 2 tasks
        assert_eq!(queue.len(), 2);
    }

    #[test]
    fn test_work_stealing_scheduler_basic() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        // Register workers
        let _q1 = scheduler.register_worker(WorkerId::new(1));
        let _q2 = scheduler.register_worker(WorkerId::new(2));

        let stats = scheduler.stats();
        assert_eq!(stats.worker_count, 2);
        assert_eq!(stats.total_submitted, 0);
    }

    #[test]
    fn test_work_stealing_scheduler_submit() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        scheduler.register_worker(WorkerId::new(1));

        let spec = TaskSpec {
            brick_name: "Test".into(),
            backend: Backend::Cpu,
            data_dependencies: vec![],
            preferred_worker: None,
        };

        let task_id = scheduler.submit(spec, "input".into());
        assert_eq!(task_id, 0);

        let stats = scheduler.stats();
        assert_eq!(stats.total_submitted, 1);
        assert_eq!(stats.total_pending, 1);
    }

    #[test]
    fn test_work_stealing_scheduler_get_work() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        scheduler.register_worker(WorkerId::new(1));
        scheduler.register_worker(WorkerId::new(2));

        // Submit task preferring worker 1
        let spec = TaskSpec {
            brick_name: "Test".into(),
            backend: Backend::Cpu,
            data_dependencies: vec![],
            preferred_worker: Some(WorkerId::new(1)),
        };
        scheduler.submit(spec, "input".into());

        // Worker 1 should get the task
        let task = scheduler.get_work(WorkerId::new(1));
        assert!(task.is_some());

        // Worker 2 has nothing to get (or steal since queue is now empty)
        let task = scheduler.get_work(WorkerId::new(2));
        assert!(task.is_none());
    }

    #[test]
    fn test_work_stealing_scheduler_steal() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        scheduler.register_worker(WorkerId::new(1));
        scheduler.register_worker(WorkerId::new(2));

        // Submit 3 tasks to worker 1
        for i in 0..3 {
            let spec = TaskSpec {
                brick_name: format!("Task{}", i),
                backend: Backend::Cpu,
                data_dependencies: vec![],
                preferred_worker: Some(WorkerId::new(1)),
            };
            scheduler.submit(spec, format!("input{}", i));
        }

        // Worker 2 should be able to steal a task
        let stolen = scheduler.get_work(WorkerId::new(2));
        assert!(stolen.is_some());

        let stats = scheduler.stats();
        assert_eq!(stats.total_stolen, 1);
        assert_eq!(stats.total_pending, 2); // 3 submitted - 1 stolen
    }

    #[test]
    fn test_work_stealing_scheduler_locality() {
        let tracker = Arc::new(BrickDataTracker::new());

        // Track data on worker 1
        tracker.track_data("model_weights", WorkerId::new(1), 1024);

        let scheduler = WorkStealingScheduler::new(Arc::clone(&tracker));
        scheduler.register_worker(WorkerId::new(1));
        scheduler.register_worker(WorkerId::new(2));

        // Submit task with data dependency - should go to worker 1
        let spec = TaskSpec {
            brick_name: "MelBrick".into(),
            backend: Backend::Cpu,
            data_dependencies: vec!["model_weights".into()],
            preferred_worker: None,
        };
        scheduler.submit(spec, "audio_input".into());

        // Worker 1 should have the task
        let task = scheduler.get_work(WorkerId::new(1));
        assert!(task.is_some());
        assert_eq!(task.unwrap().spec.brick_name, "MelBrick");
    }

    #[test]
    fn test_scheduler_stats() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        scheduler.register_worker(WorkerId::new(1));
        scheduler.register_worker(WorkerId::new(2));

        // Submit some tasks
        for i in 0..5 {
            let spec = TaskSpec {
                brick_name: format!("Task{}", i),
                backend: Backend::Cpu,
                data_dependencies: vec![],
                preferred_worker: if i % 2 == 0 {
                    Some(WorkerId::new(1))
                } else {
                    Some(WorkerId::new(2))
                },
            };
            scheduler.submit(spec, format!("input{}", i));
        }

        let stats = scheduler.stats();
        assert_eq!(stats.worker_count, 2);
        assert_eq!(stats.total_submitted, 5);
        assert_eq!(stats.total_pending, 5);
        assert_eq!(stats.workers.len(), 2);
    }

    // ========================================================================
    // Additional comprehensive tests for 95%+ coverage
    // ========================================================================

    #[test]
    fn test_worker_id_copy_clone() {
        let id = WorkerId::new(123);
        let cloned = id;
        assert_eq!(id, cloned);
        assert_eq!(id.0, 123);
    }

    #[test]
    fn test_worker_id_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(WorkerId::new(1));
        set.insert(WorkerId::new(2));
        set.insert(WorkerId::new(1)); // Duplicate
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_backend_default() {
        let backend = Backend::default();
        assert_eq!(backend, Backend::Cpu);
    }

    #[test]
    fn test_backend_remote_not_available() {
        assert!(!Backend::Remote.is_available());
    }

    #[test]
    fn test_backend_performance_remote() {
        assert_eq!(Backend::Remote.performance_estimate(), 5);
        assert_eq!(Backend::Cpu.performance_estimate(), 10);
    }

    #[test]
    fn test_brick_input_default() {
        let input = BrickInput::default();
        assert!(input.data.is_empty());
        assert!(input.shape.is_empty());
        assert!(input.metadata.is_empty());
    }

    #[test]
    fn test_brick_input_with_metadata() {
        let input = BrickInput::new(vec![1.0], vec![1])
            .with_metadata("key1", "value1")
            .with_metadata("key2", "value2");
        assert_eq!(input.metadata.get("key1"), Some(&"value1".to_string()));
        assert_eq!(input.metadata.get("key2"), Some(&"value2".to_string()));
    }

    #[test]
    fn test_brick_output_default() {
        let output = BrickOutput::default();
        assert!(output.data.is_empty());
        assert!(output.shape.is_empty());
    }

    #[test]
    fn test_execution_metrics_default() {
        let metrics = ExecutionMetrics::default();
        assert_eq!(metrics.execution_time, Duration::ZERO);
        assert_eq!(metrics.backend, Backend::Cpu);
        assert!(metrics.worker_id.is_none());
        assert!(metrics.transfer_time.is_none());
    }

    #[test]
    fn test_distributed_brick_inner() {
        let inner = TestBrick { name: "Inner" };
        let distributed = DistributedBrick::new(inner);
        assert_eq!(distributed.inner().brick_name(), "Inner");
    }

    #[test]
    fn test_distributed_brick_inner_mut() {
        let inner = TestBrick { name: "Inner" };
        let mut distributed = DistributedBrick::new(inner);
        let _ = distributed.inner_mut();
        // Just verify we can get mutable reference
    }

    #[test]
    fn test_distributed_brick_to_html() {
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner);
        assert_eq!(distributed.to_html(), "<div>Test</div>");
    }

    #[test]
    fn test_distributed_brick_to_css() {
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner);
        assert_eq!(distributed.to_css(), ".test { }");
    }

    #[test]
    fn test_distributed_brick_assertions() {
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner);
        assert_eq!(distributed.assertions().len(), 1);
    }

    #[test]
    fn test_task_spec_clone() {
        let spec = TaskSpec {
            brick_name: "Test".into(),
            backend: Backend::Gpu,
            data_dependencies: vec!["dep1".into()],
            preferred_worker: Some(WorkerId::new(5)),
        };
        let cloned = spec.clone();
        assert_eq!(spec.brick_name, cloned.brick_name);
        assert_eq!(spec.backend, cloned.backend);
    }

    #[test]
    fn test_brick_data_tracker_default() {
        let tracker = BrickDataTracker::default();
        assert_eq!(tracker.total_data_size(), 0);
    }

    #[test]
    fn test_brick_data_tracker_remove_data() {
        let tracker = BrickDataTracker::new();
        tracker.track_data("data1", WorkerId::new(1), 100);
        tracker.track_data("data1", WorkerId::new(2), 100);

        let workers = tracker.get_workers_for_data("data1");
        assert_eq!(workers.len(), 2);

        tracker.remove_data("data1", WorkerId::new(1));
        let workers = tracker.get_workers_for_data("data1");
        assert_eq!(workers.len(), 1);
        assert_eq!(workers[0], WorkerId::new(2));
    }

    #[test]
    fn test_brick_data_tracker_total_size() {
        let tracker = BrickDataTracker::new();
        tracker.track_data("data1", WorkerId::new(1), 100);
        tracker.track_data("data2", WorkerId::new(1), 200);
        assert_eq!(tracker.total_data_size(), 300);
    }

    #[test]
    fn test_brick_data_tracker_get_nonexistent() {
        let tracker = BrickDataTracker::new();
        let workers = tracker.get_workers_for_data("nonexistent");
        assert!(workers.is_empty());
    }

    #[test]
    fn test_brick_data_tracker_calculate_affinity_empty() {
        let tracker = BrickDataTracker::new();
        let affinity = tracker.calculate_affinity(&["nonexistent".into()]);
        assert!(affinity.is_empty());
    }

    #[test]
    fn test_brick_data_tracker_find_best_worker_no_weights() {
        let tracker = BrickDataTracker::new();
        let brick = TestBrick { name: "NoBrick" };
        let best = tracker.find_best_worker(&brick);
        assert!(best.is_none());
    }

    #[test]
    fn test_brick_data_tracker_find_best_worker_distributed_preferred() {
        let tracker = BrickDataTracker::new();
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner).with_preferred_worker(WorkerId::new(42));

        let best = tracker.find_best_worker_for_distributed(&distributed);
        assert_eq!(best, Some(WorkerId::new(42)));
    }

    #[test]
    fn test_brick_data_tracker_find_best_worker_distributed_affinity() {
        let tracker = BrickDataTracker::new();
        tracker.track_data("dep1", WorkerId::new(5), 100);

        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner).with_data_dependencies(vec!["dep1".into()]);

        let best = tracker.find_best_worker_for_distributed(&distributed);
        assert_eq!(best, Some(WorkerId::new(5)));
    }

    #[test]
    fn test_backend_selector_default() {
        let selector = BackendSelector::default();
        // Default thresholds
        assert_eq!(selector.select(50, true), Backend::Cpu);
    }

    #[test]
    fn test_backend_selector_cpu_max_threshold() {
        let selector = BackendSelector::new()
            .with_cpu_max_threshold(100)
            .with_simd_threshold(50);
        // Over cpu_max_threshold but Remote not available, so falls through to GPU/SIMD/CPU selection
        // Since 200 >= simd_threshold (50), returns SIMD
        let backend = selector.select(200, false);
        assert_eq!(backend, Backend::Simd);

        // Below simd_threshold returns CPU
        let backend = selector.select(10, false);
        assert_eq!(backend, Backend::Cpu);
    }

    #[test]
    fn test_backend_selector_select_for_brick() {
        let selector = BackendSelector::new();
        let backend = selector.select_for_brick(50, 100, true);
        assert_eq!(backend, Backend::Cpu);
    }

    #[test]
    fn test_multi_executor_with_selector() {
        let tracker = Arc::new(BrickDataTracker::new());
        let selector = BackendSelector::new().with_simd_threshold(1);
        let executor = MultiBrickExecutor::new(tracker).with_selector(selector);

        let brick = TestBrick { name: "Test" };
        let input = BrickInput::new(vec![1.0, 2.0], vec![2]);
        let result = executor.execute(&brick, input);
        assert!(result.is_ok());
        // With threshold 1, should use SIMD
        assert_eq!(result.unwrap().metrics.backend, Backend::Simd);
    }

    #[test]
    fn test_multi_executor_with_gpu_available() {
        let tracker = Arc::new(BrickDataTracker::new());
        let executor = MultiBrickExecutor::new(tracker).with_gpu_available(true);
        let _ = executor.data_tracker();
    }

    #[test]
    fn test_multi_executor_execute_distributed() {
        let tracker = Arc::new(BrickDataTracker::new());
        let executor = MultiBrickExecutor::new(tracker);

        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner).with_backend(Backend::Cpu);
        let input = BrickInput::new(vec![1.0], vec![1]);

        let result = executor.execute_distributed(&distributed, input);
        assert!(result.is_ok());
    }

    #[test]
    fn test_multi_executor_execute_simd() {
        let tracker = Arc::new(BrickDataTracker::new());
        let selector = BackendSelector::new().with_simd_threshold(1);
        let executor = MultiBrickExecutor::new(tracker).with_selector(selector);

        let brick = TestBrick { name: "Test" };
        let input = BrickInput::new(vec![1.0, 2.0], vec![2]);

        let result = executor.execute(&brick, input);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().metrics.backend, Backend::Simd);
    }

    #[test]
    fn test_multi_executor_execute_gpu_unavailable() {
        let tracker = Arc::new(BrickDataTracker::new());
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner).with_backend(Backend::Gpu);
        let executor = MultiBrickExecutor::new(tracker).with_gpu_available(false);
        let input = BrickInput::new(vec![1.0], vec![1]);

        let result = executor.execute_distributed(&distributed, input);
        assert!(result.is_err());
    }

    #[test]
    fn test_multi_executor_execute_remote_unavailable() {
        let tracker = Arc::new(BrickDataTracker::new());
        let inner = TestBrick { name: "Test" };
        let distributed = DistributedBrick::new(inner).with_backend(Backend::Remote);
        let executor = MultiBrickExecutor::new(tracker);
        let input = BrickInput::new(vec![1.0], vec![1]);

        let result = executor.execute_distributed(&distributed, input);
        assert!(result.is_err());
    }

    #[test]
    fn test_subscription_drain_empty() {
        let coordinator = BrickCoordinator::new();
        let sub = coordinator.subscribe("test/topic");
        let messages = sub.drain();
        assert!(messages.is_empty());
    }

    #[test]
    fn test_subscription_has_messages_false() {
        let coordinator = BrickCoordinator::new();
        let sub = coordinator.subscribe("test/topic");
        assert!(!sub.has_messages());
    }

    #[test]
    fn test_brick_coordinator_default() {
        let coordinator = BrickCoordinator::default();
        let id = coordinator.next_request_id();
        assert_eq!(id, 0);
    }

    #[test]
    fn test_brick_coordinator_next_request_id() {
        let coordinator = BrickCoordinator::new();
        assert_eq!(coordinator.next_request_id(), 0);
        assert_eq!(coordinator.next_request_id(), 1);
        assert_eq!(coordinator.next_request_id(), 2);
    }

    #[test]
    fn test_brick_coordinator_publish_no_subscribers() {
        let coordinator = BrickCoordinator::new();
        // Should not panic even with no subscribers
        coordinator.publish(
            "nonexistent/topic",
            BrickMessage::StateChange {
                brick_name: "Test".into(),
                event: "test".into(),
            },
        );
    }

    #[test]
    fn test_brick_message_execution_request() {
        let msg = BrickMessage::ExecutionRequest {
            brick_name: "Test".into(),
            input_key: "key".into(),
            request_id: 42,
        };
        match msg {
            BrickMessage::ExecutionRequest {
                brick_name,
                input_key,
                request_id,
            } => {
                assert_eq!(brick_name, "Test");
                assert_eq!(input_key, "key");
                assert_eq!(request_id, 42);
            }
            _ => panic!("Wrong message type"),
        }
    }

    #[test]
    fn test_brick_message_execution_result() {
        let msg = BrickMessage::ExecutionResult {
            request_id: 42,
            output_key: "out".into(),
            success: true,
        };
        match msg {
            BrickMessage::ExecutionResult {
                request_id,
                output_key,
                success,
            } => {
                assert_eq!(request_id, 42);
                assert_eq!(output_key, "out");
                assert!(success);
            }
            _ => panic!("Wrong message type"),
        }
    }

    #[test]
    fn test_work_stealing_task_clone() {
        let spec = TaskSpec {
            brick_name: "Test".into(),
            backend: Backend::Cpu,
            data_dependencies: vec![],
            preferred_worker: None,
        };
        let task = WorkStealingTask::new(1, spec, "key".into());
        let cloned = task.clone();
        assert_eq!(task.id, cloned.id);
    }

    #[test]
    fn test_worker_queue_worker_id() {
        let queue = WorkerQueue::new(WorkerId::new(42));
        assert_eq!(queue.worker_id(), WorkerId::new(42));
    }

    #[test]
    fn test_worker_queue_completed_count() {
        let queue = WorkerQueue::new(WorkerId::new(1));
        assert_eq!(queue.completed_count(), 0);
        queue.mark_completed();
        assert_eq!(queue.completed_count(), 1);
        queue.mark_completed();
        assert_eq!(queue.completed_count(), 2);
    }

    #[test]
    fn test_worker_queue_pop_empty() {
        let queue = WorkerQueue::new(WorkerId::new(1));
        assert!(queue.pop().is_none());
    }

    #[test]
    fn test_worker_queue_steal_empty() {
        let queue = WorkerQueue::new(WorkerId::new(1));
        assert!(queue.steal().is_none());
    }

    #[test]
    fn test_scheduler_unregister_worker() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        scheduler.register_worker(WorkerId::new(1));
        assert_eq!(scheduler.stats().worker_count, 1);

        scheduler.unregister_worker(WorkerId::new(1));
        assert_eq!(scheduler.stats().worker_count, 0);
    }

    #[test]
    fn test_scheduler_submit_no_workers() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        let spec = TaskSpec {
            brick_name: "Test".into(),
            backend: Backend::Cpu,
            data_dependencies: vec![],
            preferred_worker: None,
        };

        let task_id = scheduler.submit(spec, "input".into());
        assert_eq!(task_id, 0);
        // Task submitted but no workers to receive it
        assert_eq!(scheduler.stats().total_submitted, 1);
    }

    #[test]
    fn test_scheduler_submit_priority() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        scheduler.register_worker(WorkerId::new(1));

        let spec = TaskSpec {
            brick_name: "Test".into(),
            backend: Backend::Cpu,
            data_dependencies: vec![],
            preferred_worker: None,
        };

        let task_id = scheduler.submit_priority(spec, "input".into(), 100);
        assert_eq!(task_id, 0);

        let task = scheduler.get_work(WorkerId::new(1));
        assert!(task.is_some());
        assert_eq!(task.unwrap().priority, 100);
    }

    #[test]
    fn test_scheduler_get_work_unregistered_worker() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(tracker);

        // Try to get work for worker that doesn't exist
        let task = scheduler.get_work(WorkerId::new(999));
        assert!(task.is_none());
    }

    #[test]
    fn test_scheduler_data_tracker_accessor() {
        let tracker = Arc::new(BrickDataTracker::new());
        let scheduler = WorkStealingScheduler::new(Arc::clone(&tracker));

        let _ = scheduler.data_tracker();
    }

    #[test]
    fn test_worker_stats_fields() {
        let stats = WorkerStats {
            worker_id: WorkerId::new(1),
            queue_length: 5,
            completed: 10,
            stolen_from: 2,
        };
        assert_eq!(stats.worker_id, WorkerId::new(1));
        assert_eq!(stats.queue_length, 5);
        assert_eq!(stats.completed, 10);
        assert_eq!(stats.stolen_from, 2);
    }

    #[test]
    fn test_scheduler_stats_fields() {
        let stats = SchedulerStats {
            worker_count: 2,
            total_submitted: 10,
            total_pending: 5,
            total_completed: 4,
            total_stolen: 1,
            workers: vec![],
        };
        assert_eq!(stats.worker_count, 2);
        assert_eq!(stats.total_submitted, 10);
        assert_eq!(stats.total_pending, 5);
        assert_eq!(stats.total_completed, 4);
        assert_eq!(stats.total_stolen, 1);
    }

    #[test]
    fn test_data_location_clone() {
        let loc = DataLocation {
            key: "test".into(),
            workers: vec![WorkerId::new(1)],
            size_bytes: 100,
            last_access: Instant::now(),
        };
        let cloned = loc.clone();
        assert_eq!(loc.key, cloned.key);
    }

    #[test]
    fn test_track_data_updates_existing() {
        let tracker = BrickDataTracker::new();
        tracker.track_data("key", WorkerId::new(1), 100);
        tracker.track_data("key", WorkerId::new(1), 200); // Same worker again

        let workers = tracker.get_workers_for_data("key");
        assert_eq!(workers.len(), 1); // Should not duplicate
    }
}