zenith-runtime 0.1.0

Zenith 全链路数据面运行时:WorkerRuntime(eBPF + XSK + Worker 集成)、三级 Supervisor、ChangeSet 热切换、RuntimeGraph 拓扑规划
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
//! RuntimeGraph 规划引擎
//!
//! RuntimeGraph 映射 Zenith 运行时的执行拓扑:
//! **Domains → Workers → Queues → Resources**
//!
//! ## 架构层级
//! ```text
//! +--------------------------------------------------+
//! |               ExecutionDomain                    |
//! |  (DataPlane / ControlPlane / Management / ...)    |
//! +--------------------------------------------------+
//!                    │ 1:N
//!//! +--------------------------------------------------+
//! |               ResourceNode                      |
//! |  (CPU / Memory / NIC 资源绑定到域)               |
//! +--------------------------------------------------+
//!                    │ 1:N
//!//! +--------------------------------------------------+
//! |             QueueMapping                        |
//! |  (queue_id → worker_id 亲和性规则)               |
//! +--------------------------------------------------+
//! ```
//!
//! ## 核心特性
//! - 固定容量存储(const generics,运行时零堆分配)
//! - 域隔离强制实施(Domain Isolation)
//! - NUMA 感知放置模拟
//! - 拓扑规划:基于能力需求的 Worker→Domain 分配
//! - 队列分布策略:RSS Hash / 轮询 / NUMA 本地
//!
//! ## 设计原则
//! - 热路径零堆分配:使用 const-generics 定长数组预分配
//! - 类型安全:通过 Rust 类型系统强制域隔离
//! - 可验证:`validate()` 方法在规划后检查拓扑正确性

use std::fmt;

use thiserror::Error;

// ---------------------------------------------------------------------------
// 错误类型
// ---------------------------------------------------------------------------

/// RuntimeGraph 错误
#[derive(Debug, Error, PartialEq, Eq)]
pub enum GraphError {
    /// 节点容量已满
    #[error("node capacity exceeded: max={0}")]
    NodeCapacityExceeded(usize),

    /// 映射容量已满
    #[error("mapping capacity exceeded: max={0}")]
    MappingCapacityExceeded(usize),

    /// 节点未找到
    #[error("node not found: id={0}")]
    NodeNotFound(u64),

    /// 节点已存在
    #[error("node already exists: id={0}")]
    NodeAlreadyExists(u64),

    /// 域隔离违规
    #[error("domain isolation violation: node={node_id}, domain={domain:?}")]
    DomainIsolationViolation {
        /// 违规节点 ID
        node_id: u64,
        /// 违规域
        domain: ExecutionDomain,
    },

    /// 资源不足
    #[error("insufficient resources: domain={domain:?}, need_cpu={need_cpu}, have_cpu={have_cpu}, need_mem={need_mem}, have_mem={have_mem}")]
    InsufficientResources {
        /// 目标域
        domain: ExecutionDomain,
        /// 需求 CPU 核心数
        need_cpu: u32,
        /// 实际可用 CPU 核心数
        have_cpu: u32,
        /// 需求内存 MB
        need_mem: u32,
        /// 实际可用内存 MB
        have_mem: u32,
    },

    /// 无效拓扑
    #[error("invalid topology: {0}")]
    InvalidTopology(&'static str),

    /// 未找到足够的 worker
    #[error("no workers available for domain: {0:?}")]
    NoWorkersForDomain(ExecutionDomain),

    /// 映射未找到
    #[error("mapping not found: queue_id={0}")]
    MappingNotFound(u32),
}

// ---------------------------------------------------------------------------
// 执行域
// ---------------------------------------------------------------------------

/// 执行域枚举
///
/// 每个域代表系统中一个独立的执行上下文,域之间严格隔离。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExecutionDomain {
    /// 数据面(数据包快速转发)
    DataPlane,
    /// 控制面(路由、策略下发)
    ControlPlane,
    /// 管理层(配置、编排)
    Management,
    /// 可观测性(监控、Tracing)
    Observability,
    /// 安全(加密、认证)
    Security,
    /// 存储(持久化、缓存)
    Storage,
}

impl ExecutionDomain {
    /// 返回所有域的迭代器
    pub fn all() -> [ExecutionDomain; 6] {
        [
            ExecutionDomain::DataPlane,
            ExecutionDomain::ControlPlane,
            ExecutionDomain::Management,
            ExecutionDomain::Observability,
            ExecutionDomain::Security,
            ExecutionDomain::Storage,
        ]
    }

    /// 是否为数据面域
    #[inline]
    pub fn is_data_plane(&self) -> bool {
        matches!(self, ExecutionDomain::DataPlane)
    }

    /// 是否需要高 CPU 核心数
    #[inline]
    pub fn requires_high_cpu(&self) -> bool {
        matches!(self, ExecutionDomain::DataPlane | ExecutionDomain::Security)
    }

    /// 是否需要大内存
    #[inline]
    pub fn requires_large_memory(&self) -> bool {
        matches!(self, ExecutionDomain::Storage | ExecutionDomain::Observability)
    }

    /// 默认资源需求(每个 worker)
    pub fn default_requirements(&self) -> (u32, u32, u32) {
        match self {
            ExecutionDomain::DataPlane => (4, 4096, 8),
            ExecutionDomain::ControlPlane => (2, 2048, 4),
            ExecutionDomain::Management => (2, 2048, 2),
            ExecutionDomain::Observability => (2, 8192, 4),
            ExecutionDomain::Security => (4, 4096, 4),
            ExecutionDomain::Storage => (2, 16384, 2),
        }
    }
}

impl fmt::Display for ExecutionDomain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExecutionDomain::DataPlane => write!(f, "DataPlane"),
            ExecutionDomain::ControlPlane => write!(f, "ControlPlane"),
            ExecutionDomain::Management => write!(f, "Management"),
            ExecutionDomain::Observability => write!(f, "Observability"),
            ExecutionDomain::Security => write!(f, "Security"),
            ExecutionDomain::Storage => write!(f, "Storage"),
        }
    }
}

// ---------------------------------------------------------------------------
// 节点状态
// ---------------------------------------------------------------------------

/// 资源节点状态
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeStatus {
    /// 在线
    Online,
    /// 离线
    Offline,
    /// 降级运行
    Degraded,
    /// 维护中
    Maintenance,
}

impl NodeStatus {
    /// 是否可调度
    #[inline]
    pub fn is_schedulable(&self) -> bool {
        matches!(self, NodeStatus::Online)
    }
}

// ---------------------------------------------------------------------------
// ResourceNode
// ---------------------------------------------------------------------------

/// 资源节点
///
/// 代表一个可用于承载 Worker 的物理或虚拟资源单元。
#[derive(Debug, Clone, Copy)]
pub struct ResourceNode {
    /// 节点唯一 ID
    pub id: u64,
    /// 所属执行域
    pub domain: ExecutionDomain,
    /// CPU 核心数
    pub cpu_cores: u32,
    /// 内存大小(MB)
    pub memory_mb: u32,
    /// 可用 NIC 队列数
    pub nic_queues: u32,
    /// 节点状态
    pub status: NodeStatus,
    /// NUMA 节点编号(用于 NUMA 感知放置)
    pub numa_node: u32,
}

impl ResourceNode {
    /// 创建新的资源节点
    pub const fn new(
        id: u64,
        domain: ExecutionDomain,
        cpu_cores: u32,
        memory_mb: u32,
        nic_queues: u32,
    ) -> Self {
        Self {
            id,
            domain,
            cpu_cores,
            memory_mb,
            nic_queues,
            status: NodeStatus::Online,
            numa_node: 0,
        }
    }

    /// 设置 NUMA 节点
    pub const fn with_numa(mut self, numa_node: u32) -> Self {
        self.numa_node = numa_node;
        self
    }

    /// 设置状态
    pub const fn with_status(mut self, status: NodeStatus) -> Self {
        self.status = status;
        self
    }

    /// 是否在线且可调度
    #[inline]
    pub fn is_available(&self) -> bool {
        self.status.is_schedulable()
    }

    /// 是否满足给定资源需求
    #[inline]
    pub fn meets_requirements(&self, cpu: u32, mem: u32, queues: u32) -> bool {
        self.cpu_cores >= cpu
            && self.memory_mb >= mem
            && self.nic_queues >= queues
    }
}

// ---------------------------------------------------------------------------
// 亲和性规则
// ---------------------------------------------------------------------------

/// 队列亲和性规则
///
/// 决定 Worker 与队列之间的绑定强度。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AffinityRule {
    /// 无亲和性(可自由调度)
    None,
    /// NUMA 本地(必须在同一 NUMA 节点)
    NumaLocal,
    /// CPU 本地(必须在同一 CPU 插槽)
    CpuLocal,
    /// 精确绑定(独占该 Worker)
    Exact,
}

// ---------------------------------------------------------------------------
// QueueMapping
// ---------------------------------------------------------------------------

/// 队列映射
///
/// 将 NIC 队列 ID 映射到 Worker ID,并携带亲和性规则。
#[derive(Debug, Clone, Copy)]
pub struct QueueMapping {
    /// 队列 ID(NIC 接收队列编号)
    pub queue_id: u32,
    /// Worker ID
    pub worker_id: u32,
    /// 亲和性规则
    pub affinity: AffinityRule,
}

impl QueueMapping {
    /// 创建新的队列映射
    pub const fn new(queue_id: u32, worker_id: u32) -> Self {
        Self {
            queue_id,
            worker_id,
            affinity: AffinityRule::None,
        }
    }

    /// 设置亲和性规则
    pub const fn with_affinity(mut self, affinity: AffinityRule) -> Self {
        self.affinity = affinity;
        self
    }
}

// ---------------------------------------------------------------------------
// WorkerAssignment
// ---------------------------------------------------------------------------

/// Worker 分配结果
///
/// 描述一个 Worker 被分配到哪个域的哪个节点,以及绑定了哪些队列。
#[derive(Debug, Clone)]
pub struct WorkerAssignment {
    /// Worker ID
    pub worker_id: u32,
    /// 所在节点 ID
    pub node_id: u64,
    /// 所属域
    pub domain: ExecutionDomain,
    /// NUMA 节点编号
    pub numa_node: u32,
    /// 绑定的队列列表
    pub queue_ids: Vec<u32>,
}

// ---------------------------------------------------------------------------
// DomainSnapshot
// ---------------------------------------------------------------------------

/// 域资源快照
///
/// 描述一个域的资源需求规格,用于拓扑规划。
#[derive(Debug, Clone, Copy)]
pub struct DomainSnapshot {
    /// 目标域
    pub domain: ExecutionDomain,
    /// 所需 CPU 核心数(每个 Worker)
    pub required_cpu_cores: u32,
    /// 所需内存 MB(每个 Worker)
    pub required_memory_mb: u32,
    /// 所需 NIC 队列数(每个 Worker)
    pub required_nic_queues: u32,
    /// 需要的 Worker 数量
    pub worker_count: usize,
}

impl DomainSnapshot {
    /// 从域默认需求创建快照
    pub fn from_domain(domain: ExecutionDomain, worker_count: usize) -> Self {
        let (cpu, mem, queues) = domain.default_requirements();
        Self {
            domain,
            required_cpu_cores: cpu,
            required_memory_mb: mem,
            required_nic_queues: queues,
            worker_count,
        }
    }

    /// 自定义 CPU 需求
    pub const fn with_cpu(mut self, cpu: u32) -> Self {
        self.required_cpu_cores = cpu;
        self
    }

    /// 自定义内存需求
    pub const fn with_memory(mut self, mem: u32) -> Self {
        self.required_memory_mb = mem;
        self
    }

    /// 自定义 Worker 数量
    pub const fn with_workers(mut self, count: usize) -> Self {
        self.worker_count = count;
        self
    }
}

// ---------------------------------------------------------------------------
// 队列分布策略
// ---------------------------------------------------------------------------

/// 队列分布策略
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum QueueStrategy {
    /// RSS(Receive Side Scaling)哈希分布
    /// 根据包的五元组哈希将队列分配到 Worker
    RssHash,
    /// 轮询分配
    /// 队列依次分配给各 Worker
    RoundRobin,
    /// NUMA 本地优先
    /// 队列优先分配到同 NUMA 节点的 Worker
    NumaLocal,
}

// ---------------------------------------------------------------------------
// RuntimeGraph
// ---------------------------------------------------------------------------

/// RuntimeGraph — 执行拓扑图
///
/// 使用 const-generics 实现的固定容量拓扑存储。
/// `MAX_NODES` 限制最大资源节点数,`MAX_MAPPINGS` 限制最大队列映射数。
/// 所有存储在栈上预分配,运行时零堆分配。
///
/// # 类型参数
/// - `MAX_NODES`: 最大资源节点数
/// - `MAX_MAPPINGS`: 最大队列映射数
#[derive(Debug)]
pub struct RuntimeGraph<const MAX_NODES: usize, const MAX_MAPPINGS: usize> {
    nodes: [Option<ResourceNode>; MAX_NODES],
    mappings: [Option<QueueMapping>; MAX_MAPPINGS],
    node_count: usize,
    mapping_count: usize,
}

impl<const MAX_NODES: usize, const MAX_MAPPINGS: usize> Default
    for RuntimeGraph<MAX_NODES, MAX_MAPPINGS>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<const MAX_NODES: usize, const MAX_MAPPINGS: usize>
    RuntimeGraph<MAX_NODES, MAX_MAPPINGS>
{
    /// 创建空的拓扑图
    pub const fn new() -> Self {
        Self {
            nodes: [const { None }; MAX_NODES],
            mappings: [const { None }; MAX_MAPPINGS],
            node_count: 0,
            mapping_count: 0,
        }
    }

    /// 当前节点数
    #[inline]
    pub fn node_count(&self) -> usize {
        self.node_count
    }

    /// 当前映射数
    #[inline]
    pub fn mapping_count(&self) -> usize {
        self.mapping_count
    }

    /// 最大节点容量
    #[inline]
    pub const fn max_nodes(&self) -> usize {
        MAX_NODES
    }

    /// 最大映射容量
    #[inline]
    pub const fn max_mappings(&self) -> usize {
        MAX_MAPPINGS
    }

    /// 是否为空
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.node_count == 0
    }

    /// 添加资源节点
    ///
    /// # Arguments
    /// * `node` - 要添加的资源节点
    ///
    /// # Errors
    /// * `GraphError::NodeCapacityExceeded` - 节点容量已满
    /// * `GraphError::NodeAlreadyExists` - 节点 ID 已存在
    pub fn add_node(&mut self, node: ResourceNode) -> Result<(), GraphError> {
        if self.node_count >= MAX_NODES {
            return Err(GraphError::NodeCapacityExceeded(MAX_NODES));
        }
        if self.nodes.iter().any(|n| n.as_ref().is_some_and(|n| n.id == node.id)) {
            return Err(GraphError::NodeAlreadyExists(node.id));
        }
        let slot = self
            .nodes
            .iter_mut()
            .find(|s| s.is_none())
            .ok_or(GraphError::NodeCapacityExceeded(MAX_NODES))?;
        *slot = Some(node);
        self.node_count += 1;
        Ok(())
    }

    /// 移除资源节点
    ///
    /// # Arguments
    /// * `id` - 要移除的节点 ID
    ///
    /// # Errors
    /// * `GraphError::NodeNotFound` - 节点未找到
    pub fn remove_node(&mut self, id: u64) -> Result<(), GraphError> {
        let slot = self
            .nodes
            .iter_mut()
            .find(|s| s.as_ref().is_some_and(|n| n.id == id))
            .ok_or(GraphError::NodeNotFound(id))?;
        *slot = None;
        self.node_count -= 1;
        Ok(())
    }

    /// 添加队列映射
    ///
    /// # Arguments
    /// * `mapping` - 要添加的队列映射
    ///
    /// # Errors
    /// * `GraphError::MappingCapacityExceeded` - 映射容量已满
    pub fn add_mapping(&mut self, mapping: QueueMapping) -> Result<(), GraphError> {
        if self.mapping_count >= MAX_MAPPINGS {
            return Err(GraphError::MappingCapacityExceeded(MAX_MAPPINGS));
        }
        if self
            .mappings
            .iter()
            .any(|m| m.as_ref().is_some_and(|m| m.queue_id == mapping.queue_id))
        {
            return Err(GraphError::InvalidTopology(
                "duplicate queue_id in mappings",
            ));
        }
        let slot = self
            .mappings
            .iter_mut()
            .find(|s| s.is_none())
            .ok_or(GraphError::MappingCapacityExceeded(MAX_MAPPINGS))?;
        *slot = Some(mapping);
        self.mapping_count += 1;
        Ok(())
    }

    /// 移除队列映射
    ///
    /// # Arguments
    /// * `queue_id` - 要移除的队列 ID
    pub fn remove_mapping(&mut self, queue_id: u32) -> Result<(), GraphError> {
        let slot = self
            .mappings
            .iter_mut()
            .find(|s| s.as_ref().is_some_and(|m| m.queue_id == queue_id))
            .ok_or(GraphError::MappingNotFound(queue_id))?;
        *slot = None;
        self.mapping_count -= 1;
        Ok(())
    }

    /// 查找节点
    #[inline]
    pub fn find_node(&self, id: u64) -> Option<&ResourceNode> {
        self.nodes.iter().find_map(|n| n.as_ref().filter(|n| n.id == id))
    }

    /// 查找映射
    #[inline]
    pub fn find_mapping(&self, queue_id: u32) -> Option<&QueueMapping> {
        self.mappings.iter().find_map(|m| m.as_ref().filter(|m| m.queue_id == queue_id))
    }

    /// 获取指定域的所有节点
    pub fn nodes_in_domain(&self, domain: ExecutionDomain) -> Vec<&ResourceNode> {
        self.nodes
            .iter()
            .filter_map(|n| n.as_ref())
            .filter(|n| n.domain == domain)
            .collect()
    }

    /// 获取在线节点
    pub fn online_nodes(&self) -> Vec<&ResourceNode> {
        self.nodes
            .iter()
            .filter_map(|n| n.as_ref())
            .filter(|n| n.is_available())
            .collect()
    }

    /// 获取指定 NUMA 节点的在线节点
    pub fn online_nodes_in_numa(&self, numa_node: u32) -> Vec<&ResourceNode> {
        self.nodes
            .iter()
            .filter_map(|n| n.as_ref())
            .filter(|n| n.is_available() && n.numa_node == numa_node)
            .collect()
    }

    /// 遍历所有节点
    pub fn iter_nodes(&self) -> impl Iterator<Item = &ResourceNode> {
        self.nodes.iter().filter_map(|n| n.as_ref())
    }

    /// 遍历所有映射
    pub fn iter_mappings(&self) -> impl Iterator<Item = &QueueMapping> {
        self.mappings.iter().filter_map(|m| m.as_ref())
    }

    /// 验证拓扑一致性
    ///
    /// 检查项:
    /// 1. 所有节点资源合法(cpu_cores / memory_mb 非零)
    /// 2. 队列映射一致性:queue_id 全局唯一(重复映射会导致流量归属二义)
    /// 3. 域隔离:一个节点只能属于一个域(由 `add_node` 的 ID 唯一性保证)
    pub fn validate(&self) -> Result<(), GraphError> {
        // 检查节点状态
        for node in self.iter_nodes() {
            if node.cpu_cores == 0 {
                return Err(GraphError::InvalidTopology("node has zero cpu_cores"));
            }
            if node.memory_mb == 0 {
                return Err(GraphError::InvalidTopology("node has zero memory_mb"));
            }
        }
        // 检查映射一致性:queue_id 不得重复(定长数组线性扫描,O(n²) 但 n 受容量限制)
        let mappings: Vec<&QueueMapping> = self.iter_mappings().collect();
        for (i, m) in mappings.iter().enumerate() {
            if mappings[..i].iter().any(|prev| prev.queue_id == m.queue_id) {
                return Err(GraphError::InvalidTopology(
                    "duplicate queue_id in mappings",
                ));
            }
        }
        Ok(())
    }

    /// 规划拓扑(内部方法)
    ///
    /// # Arguments
    /// * `snapshots` - 各域的资源需求快照
    /// * `strategy` - 队列分布策略
    pub fn plan_topology(
        &self,
        snapshots: &[DomainSnapshot],
        strategy: QueueStrategy,
    ) -> Result<PlannedTopology, GraphError> {
        let planner = TopologyPlanner;
        planner.plan(snapshots, self, strategy)
    }

    /// 查找最优布局
    ///
    /// 基于 NUMA 感知和资源效率的综合评分,为给定需求找到最优节点分配。
    ///
    /// # Arguments
    /// * `domain` - 目标域
    /// * `cpu_needed` - 所需 CPU 核心数
    /// * `mem_needed` - 所需内存 MB
    /// * `queues_needed` - 所需 NIC 队列数
    ///
    /// # Returns
    /// * `Vec<u64>` - 分配的节点 ID 列表
    pub fn find_optimal_layout(
        &self,
        domain: ExecutionDomain,
        cpu_needed: u32,
        mem_needed: u32,
        queues_needed: u32,
    ) -> Result<Vec<u64>, GraphError> {
        let available: Vec<&ResourceNode> = self
            .nodes
            .iter()
            .filter_map(|n| n.as_ref())
            .filter(|n| n.is_available() && n.domain == domain)
            .collect();

        if available.is_empty() {
            return Err(GraphError::NoWorkersForDomain(domain));
        }

        let mut selected = Vec::new();
        let mut total_cpu = 0u32;
        let mut total_mem = 0u32;
        let mut total_queues = 0u32;

        // 按 NUMA 节点分组
        let mut numa_groups: Vec<Vec<&ResourceNode>> = Vec::new();
        for node in &available {
            let found = numa_groups.iter_mut().find(|g| {
                g.first().is_some_and(|n| n.numa_node == node.numa_node)
            });
            match found {
                Some(group) => group.push(node),
                None => numa_groups.push(vec![node]),
            }
        }

        // 贪心:优先填充同一 NUMA 节点的节点
        'outer: for group in &numa_groups {
            for node in group {
                if total_cpu >= cpu_needed
                    && total_mem >= mem_needed
                    && total_queues >= queues_needed
                {
                    break 'outer;
                }
                if !selected.contains(&node.id) {
                    selected.push(node.id);
                    total_cpu = total_cpu.saturating_add(node.cpu_cores);
                    total_mem = total_mem.saturating_add(node.memory_mb);
                    total_queues = total_queues.saturating_add(node.nic_queues);
                }
            }
        }

        // 如果 NUMA 分组不够,从剩余节点补充
        if total_cpu < cpu_needed || total_mem < mem_needed || total_queues < queues_needed {
            for node in &available {
                if total_cpu >= cpu_needed
                    && total_mem >= mem_needed
                    && total_queues >= queues_needed
                {
                    break;
                }
                if !selected.contains(&node.id) {
                    selected.push(node.id);
                    total_cpu = total_cpu.saturating_add(node.cpu_cores);
                    total_mem = total_mem.saturating_add(node.memory_mb);
                    total_queues = total_queues.saturating_add(node.nic_queues);
                }
            }
        }

        if total_cpu < cpu_needed || total_mem < mem_needed || total_queues < queues_needed {
            return Err(GraphError::InsufficientResources {
                domain,
                need_cpu: cpu_needed,
                have_cpu: total_cpu,
                need_mem: mem_needed,
                have_mem: total_mem,
            });
        }

        Ok(selected)
    }
}

// ---------------------------------------------------------------------------
// PlannedTopology
// ---------------------------------------------------------------------------

/// 规划后的拓扑结果
///
/// 包含各域的 Worker 分配和队列分布方案。
#[derive(Debug, Clone)]
pub struct PlannedTopology {
    /// 各域的 Worker 分配
    pub domain_assignments: Vec<DomainAssignment>,
    /// 各 Worker 的队列分布
    pub queue_distributions: Vec<QueueDistribution>,
}

impl PlannedTopology {
    /// 域数量
    #[inline]
    pub fn domain_count(&self) -> usize {
        self.domain_assignments.len()
    }

    /// Worker 总数
    #[inline]
    pub fn total_workers(&self) -> usize {
        self.domain_assignments.iter().map(|a| a.workers.len()).sum()
    }

    /// 按域查找分配
    pub fn find_assignment(&self, domain: ExecutionDomain) -> Option<&DomainAssignment> {
        self.domain_assignments.iter().find(|a| a.domain == domain)
    }

    /// 验证拓扑是否满足所有快照需求
    pub fn validate_against(&self, snapshots: &[DomainSnapshot]) -> Result<(), GraphError> {
        for snapshot in snapshots {
            let assignment = self
                .find_assignment(snapshot.domain)
                .ok_or(GraphError::NoWorkersForDomain(snapshot.domain))?;
            if assignment.workers.len() < snapshot.worker_count {
                // 计算总需求 vs 总可用资源(基于每 Worker 的需求 × 数量),
                // 使错误字段语义一致:need_cpu/have_cpu 为 CPU 核心总量,
                // need_mem/have_mem 为内存 MB 总量。
                let need_cpu = snapshot
                    .required_cpu_cores
                    .saturating_mul(snapshot.worker_count as u32);
                let have_cpu = snapshot
                    .required_cpu_cores
                    .saturating_mul(assignment.workers.len() as u32);
                let need_mem = snapshot
                    .required_memory_mb
                    .saturating_mul(snapshot.worker_count as u32);
                let have_mem = snapshot
                    .required_memory_mb
                    .saturating_mul(assignment.workers.len() as u32);
                return Err(GraphError::InsufficientResources {
                    domain: snapshot.domain,
                    need_cpu,
                    have_cpu,
                    need_mem,
                    have_mem,
                });
            }
        }
        Ok(())
    }
}

/// 域分配结果
#[derive(Debug, Clone)]
pub struct DomainAssignment {
    /// 目标域
    pub domain: ExecutionDomain,
    /// 分配的 Worker 列表
    pub workers: Vec<WorkerAssignment>,
}

/// 队列分布结果
#[derive(Debug, Clone)]
pub struct QueueDistribution {
    /// 使用的分布策略
    pub strategy: QueueStrategy,
    /// 队列→Worker 映射列表
    pub mappings: Vec<QueueMapping>,
}

// ---------------------------------------------------------------------------
// TopologyPlanner
// ---------------------------------------------------------------------------

/// 模拟 NIC RSS(Toeplitz)哈希:对队列 ID 计算 FNV-1a 哈希后按 worker 数取模。
///
/// 与 RoundRobin 的 `queue_id % worker_count` 本质区别:
/// - RoundRobin:相邻 queue_id 必然落到相邻 worker(确定性条纹分布)
/// - RssHash:映射由哈希决定,相邻 queue_id 散布到伪随机 worker,
///   且同一 queue_id 在 worker 数不变时恒映射同一 worker(连接亲和性)
#[inline]
fn rss_hash_worker(queue_id: u32, worker_count: u32) -> u32 {
    // FNV-1a 32-bit(wrapping 语义即哈希标准定义,非溢出缺陷)
    let mut hash: u32 = 0x811c_9dc5;
    for byte in queue_id.to_le_bytes() {
        hash = (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193);
    }
    hash % worker_count
}

/// 拓扑规划器
///
/// 负责将域资源需求快照转换为具体的 Worker→节点→队列分配方案。
/// 采用以下算法:
///
/// 1. **域到节点分配**:基于 NUMA 感知的贪心算法,优先在同一 NUMA 节点内完成分配
/// 2. **Worker 分配**:从候选节点中按资源充足性选择,确保每个 Worker 满足域的最低资源要求
/// 3. **队列分布**:根据指定策略(RSS Hash / 轮询 / NUMA 本地)分配队列
#[derive(Debug)]
pub struct TopologyPlanner;

impl TopologyPlanner {
    /// 执行拓扑规划
    ///
    /// # Arguments
    /// * `snapshots` - 各域的资源需求快照
    /// * `graph` - 当前资源拓扑图
    /// * `strategy` - 队列分布策略
    ///
    /// # Returns
    /// * `PlannedTopology` - 规划后的拓扑方案
    pub fn plan<const MAX_NODES: usize, const MAX_MAPPINGS: usize>(
        &self,
        snapshots: &[DomainSnapshot],
        graph: &RuntimeGraph<MAX_NODES, MAX_MAPPINGS>,
        strategy: QueueStrategy,
    ) -> Result<PlannedTopology, GraphError> {
        let mut domain_assignments = Vec::with_capacity(snapshots.len());
        let mut queue_distributions = Vec::with_capacity(snapshots.len());

        for snapshot in snapshots {
            let assignment = self.assign_domain(snapshot, graph)?;
            let distribution = self.distribute_queues(&assignment, graph, strategy);

            domain_assignments.push(assignment);
            queue_distributions.push(distribution);
        }

        Ok(PlannedTopology {
            domain_assignments,
            queue_distributions,
        })
    }

    /// 将一个域的需求分配到具体节点
    fn assign_domain<const MAX_NODES: usize, const MAX_MAPPINGS: usize>(
        &self,
        snapshot: &DomainSnapshot,
        graph: &RuntimeGraph<MAX_NODES, MAX_MAPPINGS>,
    ) -> Result<DomainAssignment, GraphError> {
        let domain_nodes = graph.nodes_in_domain(snapshot.domain);
        let available: Vec<&ResourceNode> = domain_nodes
            .into_iter()
            .filter(|n| n.is_available())
            .collect();

        if available.is_empty() {
            return Err(GraphError::NoWorkersForDomain(snapshot.domain));
        }

        let (per_cpu, per_mem, per_queues) = snapshot.domain.default_requirements();

        let numa_groups = self.group_by_numa(&available);

        let mut workers = Vec::with_capacity(snapshot.worker_count);
        let mut worker_id_counter: u32 = 0;
        // 记录每个节点已占用的 CPU/内存(单节点累计容量,防止超卖)。
        // NIC 队列在组内聚合共享(同组多个 Worker 共享网卡队列),
        // 因此队列按组/全局总量扣减,不做单节点扣减。
        let mut used_cpu: std::collections::HashMap<u64, u32> = std::collections::HashMap::new();
        let mut used_mem: std::collections::HashMap<u64, u32> = std::collections::HashMap::new();
        // 全局队列剩余(回退阶段兜底校验)
        let mut queues_global: u32 = available
            .iter()
            .map(|n| n.nic_queues)
            .fold(0u32, |a, b| a.saturating_add(b));

        // 第一阶段:按 NUMA 分组分配 Worker(每个 Worker 使用 per-worker 需求)
        for group in &numa_groups {
            if workers.len() >= snapshot.worker_count {
                break;
            }

            // 组内队列聚合(共享队列):饱和求和防回绕
            let mut queues_available: u32 = group
                .iter()
                .map(|n| n.nic_queues)
                .fold(0u32, |a, b| a.saturating_add(b));

            loop {
                if workers.len() >= snapshot.worker_count {
                    break;
                }
                if queues_available < per_queues {
                    break;
                }
                // 选择该组内剩余容量满足 per-worker 的节点(允许同一节点承载多个 Worker,
                // 但不得超过其累计 CPU/内存容量,杜绝单节点超卖)。
                // 组内无剩余容量节点 → break,交由第二阶段全局回退。
                let chosen = group.iter().find(|n| {
                    let used_c = used_cpu.get(&n.id).copied().unwrap_or(0);
                    let used_m = used_mem.get(&n.id).copied().unwrap_or(0);
                    n.cpu_cores.saturating_sub(used_c) >= per_cpu
                        && n.memory_mb.saturating_sub(used_m) >= per_mem
                });

                let Some(&node) = chosen else {
                    break;
                };

                *used_cpu.entry(node.id).or_insert(0) += per_cpu;
                *used_mem.entry(node.id).or_insert(0) += per_mem;
                queues_available = queues_available.saturating_sub(per_queues);

                workers.push(WorkerAssignment {
                    worker_id: worker_id_counter,
                    node_id: node.id,
                    domain: snapshot.domain,
                    numa_node: node.numa_node,
                    queue_ids: Vec::new(),
                });

                worker_id_counter = worker_id_counter.saturating_add(1);
            }
        }

        // 第二阶段:从全局可用节点补充(回退,同样遵守单节点累计容量与全局队列总量)
        while workers.len() < snapshot.worker_count {
            if queues_global < per_queues {
                break;
            }
            let chosen = available.iter().find(|n| {
                let used_c = used_cpu.get(&n.id).copied().unwrap_or(0);
                let used_m = used_mem.get(&n.id).copied().unwrap_or(0);
                n.cpu_cores.saturating_sub(used_c) >= per_cpu
                    && n.memory_mb.saturating_sub(used_m) >= per_mem
            });
            let Some(&node) = chosen else {
                break;
            };

            *used_cpu.entry(node.id).or_insert(0) += per_cpu;
            *used_mem.entry(node.id).or_insert(0) += per_mem;
            queues_global = queues_global.saturating_sub(per_queues);

            workers.push(WorkerAssignment {
                worker_id: worker_id_counter,
                node_id: node.id,
                domain: snapshot.domain,
                numa_node: node.numa_node,
                queue_ids: Vec::new(),
            });
            worker_id_counter = worker_id_counter.saturating_add(1);
        }

        if workers.len() < snapshot.worker_count {
            // 语义一致:need/have 均为 CPU 核心总量与内存 MB 总量
            // (参照同文件 validate_against 第 806-817 行的总量语义)
            let need_cpu: u32 = (snapshot.worker_count as u32).saturating_mul(per_cpu);
            let have_cpu: u32 = (workers.len() as u32).saturating_mul(per_cpu);
            let need_mem: u32 = (snapshot.worker_count as u32).saturating_mul(per_mem);
            let have_mem: u32 = (workers.len() as u32).saturating_mul(per_mem);
            return Err(GraphError::InsufficientResources {
                domain: snapshot.domain,
                need_cpu,
                have_cpu,
                need_mem,
                have_mem,
            });
        }

        Ok(DomainAssignment {
            domain: snapshot.domain,
            workers,
        })
    }

    /// 按 NUMA 节点分组
    fn group_by_numa<'a>(
        &self,
        nodes: &[&'a ResourceNode],
    ) -> Vec<Vec<&'a ResourceNode>> {
        let mut groups: Vec<Vec<&ResourceNode>> = Vec::new();
        for node in nodes {
            let found = groups.iter_mut().find(|g| {
                g.first().is_some_and(|n| n.numa_node == node.numa_node)
            });
            match found {
                Some(group) => group.push(node),
                None => groups.push(vec![node]),
            }
        }
        groups
    }

    /// 根据策略分布队列到 Worker
    fn distribute_queues<const MAX_NODES: usize, const MAX_MAPPINGS: usize>(
        &self,
        assignment: &DomainAssignment,
        graph: &RuntimeGraph<MAX_NODES, MAX_MAPPINGS>,
        strategy: QueueStrategy,
    ) -> QueueDistribution {
        if assignment.workers.is_empty() {
            return QueueDistribution {
                strategy,
                mappings: Vec::new(),
            };
        }

        let mut mappings = Vec::new();

        // 从图中获取已有的 NIC 队列信息(基于节点总 NIC 队列数)
        // 去重:多个 worker 共享同一节点时只计一次该节点的队列数
        let mut seen_nodes = std::collections::HashSet::new();
        let total_queues: u32 = assignment
            .workers
            .iter()
            .filter_map(|w| graph.find_node(w.node_id))
            .filter(|n| seen_nodes.insert(n.id))
            .map(|n| n.nic_queues)
            .fold(0u32, |a, b| a.saturating_add(b));

        let worker_count = assignment.workers.len() as u32;

        match strategy {
            QueueStrategy::RssHash => {
                // RSS Hash:模拟网卡 RSS(Toeplitz)语义——队列按哈希值映射到 Worker,
                // 同一 queue_id 恒映射同一 Worker,但分布由哈希决定(非轮询取模)
                for queue_id in 0..total_queues {
                    let worker_id = rss_hash_worker(queue_id, worker_count);
                    mappings.push(QueueMapping {
                        queue_id,
                        worker_id,
                        affinity: AffinityRule::None,
                    });
                }
            }
            QueueStrategy::RoundRobin => {
                // 轮询:队列依次分配给各 Worker(确定性均匀分布)
                for queue_id in 0..total_queues {
                    let worker_id = queue_id % worker_count;
                    mappings.push(QueueMapping {
                        queue_id,
                        worker_id,
                        affinity: AffinityRule::CpuLocal,
                    });
                }
            }
            QueueStrategy::NumaLocal => {
                // NUMA 本地:同 NUMA 节点的队列分配给对应的 Worker。
                // queue_id 全局唯一:跨 worker 使用单调递增的全局计数器分配,
                // 不得每个 worker 从 0 重启(否则 queue_id 重复,流量归属二义)
                let mut next_queue_id: u32 = 0;
                for (idx, worker) in assignment.workers.iter().enumerate() {
                    if let Some(node) = graph.find_node(worker.node_id) {
                        let queues = node.nic_queues;
                        for _q in 0..queues {
                            mappings.push(QueueMapping {
                                queue_id: next_queue_id,
                                worker_id: idx as u32,
                                affinity: AffinityRule::NumaLocal,
                            });
                            next_queue_id = next_queue_id.saturating_add(1);
                        }
                    }
                }
            }
        }

        QueueDistribution {
            strategy,
            mappings,
        }
    }
}

// ---------------------------------------------------------------------------
// 测试
// ---------------------------------------------------------------------------

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

    // -- 辅助函数 --

    fn make_node(id: u64, domain: ExecutionDomain, cpu: u32, mem: u32, queues: u32) -> ResourceNode {
        ResourceNode::new(id, domain, cpu, mem, queues)
    }

    fn make_numa_node(
        id: u64,
        domain: ExecutionDomain,
        cpu: u32,
        mem: u32,
        queues: u32,
        numa: u32,
    ) -> ResourceNode {
        ResourceNode::new(id, domain, cpu, mem, queues).with_numa(numa)
    }

    fn small_graph() -> RuntimeGraph<8, 32> {
        RuntimeGraph::new()
    }

    // -- 测试 1: ExecutionDomain 基本属性 --

    #[test]
    fn test_execution_domain_properties() {
        let dp = ExecutionDomain::DataPlane;
        assert!(dp.is_data_plane());
        assert!(dp.requires_high_cpu());
        assert!(!dp.requires_large_memory());

        let storage = ExecutionDomain::Storage;
        assert!(storage.requires_large_memory());
        assert!(!storage.requires_high_cpu());

        let all = ExecutionDomain::all();
        assert_eq!(all.len(), 6);
    }

    // -- 测试 2: 默认资源需求 --

    #[test]
    fn test_domain_default_requirements() {
        let (cpu, mem, queues) = ExecutionDomain::DataPlane.default_requirements();
        assert_eq!(cpu, 4);
        assert_eq!(mem, 4096);
        assert_eq!(queues, 8);

        let (_cpu, mem, _queues) = ExecutionDomain::Storage.default_requirements();
        assert_eq!(mem, 16384);
    }

    // -- 测试 3: RuntimeGraph 添加/移除节点 --

    #[test]
    fn test_add_and_remove_node() {
        let mut graph = small_graph();
        assert_eq!(graph.node_count(), 0);

        let node = make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4);
        graph.add_node(node).unwrap();
        assert_eq!(graph.node_count(), 1);

        assert!(graph.find_node(1).is_some());
        assert!(graph.find_node(99).is_none());

        graph.remove_node(1).unwrap();
        assert_eq!(graph.node_count(), 0);
        assert!(graph.find_node(1).is_none());
    }

    // -- 测试 4: 重复节点 ID 拒绝 --

    #[test]
    fn test_duplicate_node_id_rejected() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        let err = graph
            .add_node(make_node(1, ExecutionDomain::ControlPlane, 4, 4096, 2))
            .unwrap_err();
        assert!(matches!(err, GraphError::NodeAlreadyExists(1)));
    }

    // -- 测试 5: 容量溢出 --

    #[test]
    fn test_node_capacity_exceeded() {
        let mut graph: RuntimeGraph<2, 8> = RuntimeGraph::new();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph
            .add_node(make_node(2, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        let err = graph
            .add_node(make_node(3, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap_err();
        assert!(matches!(err, GraphError::NodeCapacityExceeded(2)));
    }

    // -- 测试 6: 队列映射管理 --

    #[test]
    fn test_queue_mapping_management() {
        let mut graph = small_graph();
        let m1 = QueueMapping::new(0, 0).with_affinity(AffinityRule::NumaLocal);
        graph.add_mapping(m1).unwrap();
        assert_eq!(graph.mapping_count(), 1);

        assert!(graph.find_mapping(0).is_some());
        assert!(graph.find_mapping(99).is_none());

        graph.remove_mapping(0).unwrap();
        assert_eq!(graph.mapping_count(), 0);
    }

    // -- 测试 7: 域内节点查询 --

    #[test]
    fn test_nodes_in_domain() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph
            .add_node(make_node(2, ExecutionDomain::DataPlane, 4, 4096, 2))
            .unwrap();
        graph
            .add_node(make_node(3, ExecutionDomain::ControlPlane, 2, 2048, 1))
            .unwrap();

        let dp_nodes = graph.nodes_in_domain(ExecutionDomain::DataPlane);
        assert_eq!(dp_nodes.len(), 2);

        let cp_nodes = graph.nodes_in_domain(ExecutionDomain::ControlPlane);
        assert_eq!(cp_nodes.len(), 1);

        let mgmt_nodes = graph.nodes_in_domain(ExecutionDomain::Management);
        assert_eq!(mgmt_nodes.len(), 0);
    }

    // -- 测试 8: 在线节点筛选 --

    #[test]
    fn test_online_nodes_filter() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph
            .add_node(
                ResourceNode::new(2, ExecutionDomain::DataPlane, 4, 4096, 2)
                    .with_status(NodeStatus::Offline),
            )
            .unwrap();
        graph
            .add_node(make_node(3, ExecutionDomain::ControlPlane, 2, 2048, 1))
            .unwrap();

        let online = graph.online_nodes();
        assert_eq!(online.len(), 2); // node 1 + node 3
    }

    // -- 测试 9: find_optimal_layout 基本功能 --

    #[test]
    fn test_find_optimal_layout_basic() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph
            .add_node(make_node(2, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph
            .add_node(make_node(3, ExecutionDomain::ControlPlane, 2, 2048, 1))
            .unwrap();

        let result = graph
            .find_optimal_layout(ExecutionDomain::DataPlane, 4, 4096, 2)
            .unwrap();
        assert!(!result.is_empty());
        // 应选择至少一个 DataPlane 节点
        let node = graph.find_node(result[0]).unwrap();
        assert_eq!(node.domain, ExecutionDomain::DataPlane);
    }

    // -- 测试 10: 资源不足时报错 --

    #[test]
    fn test_insufficient_resources_error() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 2, 1024, 1))
            .unwrap();

        let err = graph
            .find_optimal_layout(ExecutionDomain::DataPlane, 16, 65536, 8)
            .unwrap_err();
        assert!(matches!(err, GraphError::InsufficientResources { .. }));
    }

    // -- 测试 11: NUMA 感知分组 --

    #[test]
    fn test_numa_aware_grouping() {
        let mut graph = small_graph();
        graph
            .add_node(make_numa_node(
                1,
                ExecutionDomain::DataPlane,
                8,
                8192,
                4,
                0,
            ))
            .unwrap();
        graph
            .add_node(make_numa_node(
                2,
                ExecutionDomain::DataPlane,
                8,
                8192,
                4,
                0,
            ))
            .unwrap();
        graph
            .add_node(make_numa_node(
                3,
                ExecutionDomain::DataPlane,
                8,
                8192,
                4,
                1,
            ))
            .unwrap();

        let online_numa0 = graph.online_nodes_in_numa(0);
        assert_eq!(online_numa0.len(), 2);

        let online_numa1 = graph.online_nodes_in_numa(1);
        assert_eq!(online_numa1.len(), 1);
    }

    // -- 测试 12: TopologyPlanner RSS Hash 策略 --

    #[test]
    fn test_planner_rss_hash_strategy() {
        let mut graph = small_graph();
        for i in 0..4 {
            graph
                .add_node(make_numa_node(
                    i,
                    ExecutionDomain::DataPlane,
                    8,
                    8192,
                    4,
                    (i % 2) as u32,
                ))
                .unwrap();
        }

        let snapshot = DomainSnapshot::from_domain(ExecutionDomain::DataPlane, 2);
        let topology = graph
            .plan_topology(&[snapshot], QueueStrategy::RssHash)
            .unwrap();

        assert_eq!(topology.domain_count(), 1);
        assert!(topology.total_workers() >= 2);

        let assignment = topology
            .find_assignment(ExecutionDomain::DataPlane)
            .unwrap();
        assert_eq!(assignment.workers.len(), 2);

        let dist = &topology.queue_distributions[0];
        assert!(dist.mappings.len() >= 4); // 至少一个节点的队列数
    }

    // -- 测试 13: TopologyPlanner RoundRobin 策略 --

    #[test]
    fn test_planner_round_robin_strategy() {
        let mut graph = small_graph();
        for i in 0..3 {
            graph
                .add_node(make_node(i, ExecutionDomain::ControlPlane, 4, 8192, 8))
                .unwrap();
        }

        let snapshot = DomainSnapshot::from_domain(ExecutionDomain::ControlPlane, 3);
        let topology = graph
            .plan_topology(&[snapshot], QueueStrategy::RoundRobin)
            .unwrap();

        let dist = &topology.queue_distributions[0];
        // 轮询:Worker 应均匀分布
        let w0_count = dist.mappings.iter().filter(|m| m.worker_id == 0).count();
        let w1_count = dist.mappings.iter().filter(|m| m.worker_id == 1).count();
        assert!(w0_count >= 1);
        assert!(w1_count >= 1);
    }

    // -- 测试 14: TopologyPlanner NumaLocal 策略 --

    #[test]
    fn test_planner_numa_local_strategy() {
        let mut graph = small_graph();
        graph
            .add_node(make_numa_node(
                0,
                ExecutionDomain::DataPlane,
                8,
                16384,
                12,
                0,
            ))
            .unwrap();
        graph
            .add_node(make_numa_node(
                1,
                ExecutionDomain::DataPlane,
                8,
                16384,
                12,
                0,
            ))
            .unwrap();
        graph
            .add_node(make_numa_node(
                2,
                ExecutionDomain::DataPlane,
                8,
                16384,
                12,
                1,
            ))
            .unwrap();

        let snapshot = DomainSnapshot::from_domain(ExecutionDomain::DataPlane, 3);
        let topology = graph
            .plan_topology(&[snapshot], QueueStrategy::NumaLocal)
            .unwrap();

        let assignment = topology
            .find_assignment(ExecutionDomain::DataPlane)
            .unwrap();
        assert_eq!(assignment.workers.len(), 3);

        // 验证 NUMA 亲和性
        let dist = &topology.queue_distributions[0];
        for mapping in &dist.mappings {
            assert!(matches!(mapping.affinity, AffinityRule::NumaLocal));
        }
    }

    // -- 测试 15: 多域规划 --

    #[test]
    fn test_multi_domain_planning() {
        let mut graph = small_graph();
        graph
            .add_node(make_numa_node(
                0,
                ExecutionDomain::DataPlane,
                16,
                16384,
                8,
                0,
            ))
            .unwrap();
        graph
            .add_node(make_numa_node(
                1,
                ExecutionDomain::DataPlane,
                16,
                16384,
                8,
                1,
            ))
            .unwrap();
        graph
            .add_node(make_numa_node(
                2,
                ExecutionDomain::ControlPlane,
                4,
                8192,
                8,
                0,
            ))
            .unwrap();
        graph
            .add_node(make_numa_node(
                3,
                ExecutionDomain::Observability,
                4,
                16384,
                8,
                1,
            ))
            .unwrap();

        let snapshots = vec![
            DomainSnapshot::from_domain(ExecutionDomain::DataPlane, 2),
            DomainSnapshot::from_domain(ExecutionDomain::ControlPlane, 1),
            DomainSnapshot::from_domain(ExecutionDomain::Observability, 1),
        ];

        let topology = graph
            .plan_topology(&snapshots, QueueStrategy::RssHash)
            .unwrap();

        assert_eq!(topology.domain_count(), 3);
        assert_eq!(topology.total_workers(), 4);

        // 验证各域独立分配
        let dp = topology
            .find_assignment(ExecutionDomain::DataPlane)
            .unwrap();
        assert_eq!(dp.workers.len(), 2);
        let cp = topology
            .find_assignment(ExecutionDomain::ControlPlane)
            .unwrap();
        assert_eq!(cp.workers.len(), 1);
    }

    // -- 测试 16: validate 拓扑一致性 --

    #[test]
    fn test_validate_topology() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph
            .add_node(make_node(2, ExecutionDomain::ControlPlane, 2, 2048, 1))
            .unwrap();

        assert!(graph.validate().is_ok());

        // 添加一个零 CPU 的无效节点
        graph
            .add_node(ResourceNode::new(3, ExecutionDomain::Management, 0, 1024, 1))
            .unwrap();
        let err = graph.validate().unwrap_err();
        assert!(matches!(err, GraphError::InvalidTopology("node has zero cpu_cores")));
    }

    // -- 测试 17: 域隔离强制实施 --

    #[test]
    fn test_domain_isolation() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph
            .add_node(make_node(2, ExecutionDomain::ControlPlane, 4, 4096, 2))
            .unwrap();

        // DataPlane 域应只包含 DataPlane 节点
        let dp_nodes = graph.nodes_in_domain(ExecutionDomain::DataPlane);
        assert_eq!(dp_nodes.len(), 1);
        assert_eq!(dp_nodes[0].id, 1);

        // ControlPlane 域应只包含 ControlPlane 节点
        let cp_nodes = graph.nodes_in_domain(ExecutionDomain::ControlPlane);
        assert_eq!(cp_nodes.len(), 1);
        assert_eq!(cp_nodes[0].id, 2);

        // find_optimal_layout 只在指定域内查找
        let result = graph
            .find_optimal_layout(ExecutionDomain::DataPlane, 4, 2048, 2)
            .unwrap();
        for node_id in &result {
            let node = graph.find_node(*node_id).unwrap();
            assert_eq!(node.domain, ExecutionDomain::DataPlane);
        }
    }

    // -- 测试 18: ResourceNode 资源需求匹配 --

    #[test]
    fn test_resource_node_meets_requirements() {
        let node = ResourceNode::new(1, ExecutionDomain::DataPlane, 8, 8192, 4);
        assert!(node.meets_requirements(4, 4096, 2));
        assert!(node.meets_requirements(8, 8192, 4));
        assert!(!node.meets_requirements(16, 8192, 4));
        assert!(!node.meets_requirements(8, 16384, 4));
        assert!(!node.meets_requirements(8, 8192, 8));
    }

    // -- 测试 19: PlannedTopology 验证 --

    #[test]
    fn test_planned_topology_validate_against() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 16384, 12))
            .unwrap();

        let snapshot = DomainSnapshot::from_domain(ExecutionDomain::DataPlane, 1);
        let topology = graph
            .plan_topology(&[snapshot], QueueStrategy::RssHash)
            .unwrap();

        assert!(topology.validate_against(&[snapshot]).is_ok());

        // 需求超过实际分配
        let insufficient =
            DomainSnapshot::from_domain(ExecutionDomain::DataPlane, 10);
        let err = topology.validate_against(&[insufficient]).unwrap_err();
        assert!(matches!(err, GraphError::InsufficientResources { .. }));
    }

    // -- 测试 20: NodeStatus 可调度性 --

    #[test]
    fn test_node_status_schedulable() {
        assert!(NodeStatus::Online.is_schedulable());
        assert!(!NodeStatus::Offline.is_schedulable());
        assert!(!NodeStatus::Degraded.is_schedulable());
        assert!(!NodeStatus::Maintenance.is_schedulable());

        let node = ResourceNode::new(1, ExecutionDomain::DataPlane, 8, 8192, 4);
        assert!(node.is_available());

        let offline = node.with_status(NodeStatus::Offline);
        assert!(!offline.is_available());
    }

    // -- 测试 21: 空图操作 --

    #[test]
    fn test_empty_graph_operations() {
        let graph: RuntimeGraph<4, 16> = RuntimeGraph::new();
        assert!(graph.is_empty());
        assert_eq!(graph.node_count(), 0);
        assert_eq!(graph.mapping_count(), 0);
        assert_eq!(graph.max_nodes(), 4);
        assert_eq!(graph.max_mappings(), 16);

        let nodes = graph.online_nodes();
        assert!(nodes.is_empty());

        let err = graph
            .find_optimal_layout(ExecutionDomain::DataPlane, 1, 1, 1)
            .unwrap_err();
        assert!(matches!(err, GraphError::NoWorkersForDomain(_)));
    }

    // -- 测试 22: 节点未找到错误 --

    #[test]
    fn test_node_not_found_error() {
        let mut graph = small_graph();
        let err = graph.remove_node(999).unwrap_err();
        assert!(matches!(err, GraphError::NodeNotFound(999)));
    }

    // -- 测试 23: DomainSnapshot 自定义 --

    #[test]
    fn test_domain_snapshot_customization() {
        let snap = DomainSnapshot::from_domain(ExecutionDomain::DataPlane, 4)
            .with_cpu(16)
            .with_memory(32768)
            .with_workers(8);

        assert_eq!(snap.domain, ExecutionDomain::DataPlane);
        assert_eq!(snap.required_cpu_cores, 16);
        assert_eq!(snap.required_memory_mb, 32768);
        assert_eq!(snap.worker_count, 8);
    }

    // -- 测试 24: const 构造函数 --

    #[test]
    fn test_const_constructors() {
        const NODE: ResourceNode =
            ResourceNode::new(1, ExecutionDomain::DataPlane, 8, 8192, 4);
        assert_eq!(NODE.id, 1);
        assert_eq!(NODE.cpu_cores, 8);

        const MAPPING: QueueMapping = QueueMapping::new(0, 0);
        assert_eq!(MAPPING.queue_id, 0);
        assert_eq!(MAPPING.worker_id, 0);

        const GRAPH: RuntimeGraph<16, 64> = RuntimeGraph::new();
        assert_eq!(GRAPH.node_count(), 0);
    }

    // -- 测试 25: ExecutionDomain display --

    #[test]
    fn test_execution_domain_display() {
        let domains = ExecutionDomain::all();
        for d in domains.iter() {
            let display = format!("{}", d);
            assert!(!display.is_empty());
        }
    }

    // -- 测试 26: NodeStatus debug --

    #[test]
    fn test_node_status_debug() {
        let statuses = [
            NodeStatus::Online,
            NodeStatus::Offline,
            NodeStatus::Degraded,
            NodeStatus::Maintenance,
        ];
        for s in statuses.iter() {
            let debug_str = format!("{:?}", s);
            assert!(!debug_str.is_empty());
        }
    }

    // -- 测试 27: GraphError display --

    #[test]
    fn test_graph_error_display() {
        let errors = [
            GraphError::NodeCapacityExceeded(10),
            GraphError::MappingCapacityExceeded(20),
            GraphError::NodeNotFound(42),
            GraphError::NodeAlreadyExists(7),
            GraphError::InvalidTopology("test error"),
            GraphError::NoWorkersForDomain(ExecutionDomain::DataPlane),
        ];
        for e in errors.iter() {
            let display = format!("{}", e);
            assert!(!display.is_empty());
        }
    }

    // -- 测试 28: QueueStrategy --

    #[test]
    fn test_queue_strategy_debug() {
        let strategies = [
            QueueStrategy::RssHash,
            QueueStrategy::RoundRobin,
            QueueStrategy::NumaLocal,
        ];
        for s in strategies.iter() {
            let debug_str = format!("{:?}", s);
            assert!(!debug_str.is_empty());
        }
    }

    // -- 测试 29: AffinityRule --

    #[test]
    fn test_affinity_rule_variants() {
        let rules = [
            AffinityRule::None,
            AffinityRule::NumaLocal,
            AffinityRule::CpuLocal,
            AffinityRule::Exact,
        ];
        assert_eq!(rules.len(), 4);
        for r in rules.iter() {
            let debug_str = format!("{:?}", r);
            assert!(!debug_str.is_empty());
        }
    }

    // -- 测试 30: WorkerAssignment debug --

    #[test]
    fn test_worker_assignment_debug() {
        let assignment = WorkerAssignment {
            worker_id: 0,
            node_id: 1,
            domain: ExecutionDomain::DataPlane,
            numa_node: 0,
            queue_ids: vec![0, 1, 2],
        };
        let debug_str = format!("{:?}", assignment);
        assert!(!debug_str.is_empty());
        assert!(debug_str.contains("DataPlane"));
    }

    // -- 测试 31: PlannedTopology domain_count --

    #[test]
    fn test_planned_topology_domain_count() {
        let topology = PlannedTopology {
            domain_assignments: vec![],
            queue_distributions: vec![],
        };
        assert_eq!(topology.domain_count(), 0);
        assert_eq!(topology.total_workers(), 0);
    }

    // -- 测试 32: ResourceNode with_numa --

    #[test]
    fn test_resource_node_with_numa() {
        let node = ResourceNode::new(1, ExecutionDomain::DataPlane, 8, 8192, 4)
            .with_numa(2);
        assert_eq!(node.numa_node, 2);
    }

    // -- 测试 33: 移除不存在的映射 --

    #[test]
    fn test_remove_nonexistent_mapping() {
        let mut graph: RuntimeGraph<4, 16> = RuntimeGraph::new();
        let result = graph.remove_mapping(999);
        assert!(result.is_err());
    }

    // -- 测试 34: 映射容量边界 --

    #[test]
    fn test_mapping_capacity_boundary() {
        let mut graph: RuntimeGraph<4, 2> = RuntimeGraph::new();
        graph.add_mapping(QueueMapping::new(0, 0)).unwrap();
        graph.add_mapping(QueueMapping::new(1, 1)).unwrap();
        let result = graph.add_mapping(QueueMapping::new(2, 2));
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), GraphError::MappingCapacityExceeded(2)));
    }

    // -- 测试 36: RSS Hash 与 RoundRobin 映射语义区分 --

    #[test]
    fn test_rss_hash_differs_from_round_robin() {
        // RSS 哈希语义:映射由哈希决定,不得退化为 queue_id % worker_count
        let worker_count = 4u32;
        let differs = (0..16u32).any(|q| rss_hash_worker(q, worker_count) != q % worker_count);
        assert!(differs, "RSS 哈希映射与轮询取模完全相同(语义造假)");
        // 同一 queue_id 恒映射同一 worker(连接亲和性)
        for q in 0..16u32 {
            assert_eq!(rss_hash_worker(q, worker_count), rss_hash_worker(q, worker_count));
            assert!(rss_hash_worker(q, worker_count) < worker_count);
        }
    }

    // -- 测试 37: NumaLocal 队列 ID 全局唯一 --

    #[test]
    fn test_numa_local_queue_ids_globally_unique() {
        let mut graph = small_graph();
        graph
            .add_node(make_numa_node(0, ExecutionDomain::DataPlane, 8, 16384, 8, 0))
            .unwrap();
        graph
            .add_node(make_numa_node(1, ExecutionDomain::DataPlane, 8, 16384, 8, 0))
            .unwrap();

        let snapshot = DomainSnapshot::from_domain(ExecutionDomain::DataPlane, 2);
        let topology = graph
            .plan_topology(&[snapshot], QueueStrategy::NumaLocal)
            .unwrap();

        let dist = &topology.queue_distributions[0];
        assert_eq!(dist.mappings.len(), 16);
        let mut ids: Vec<u32> = dist.mappings.iter().map(|m| m.queue_id).collect();
        ids.sort_unstable();
        ids.dedup();
        assert_eq!(
            ids.len(),
            dist.mappings.len(),
            "NumaLocal 映射的 queue_id 必须全局唯一"
        );
    }

    // -- 测试 38: validate 检出重复 queue_id 映射 --

    #[test]
    fn test_add_mapping_rejects_duplicate_queue_id() {
        let mut graph = small_graph();
        graph
            .add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4))
            .unwrap();
        graph.add_mapping(QueueMapping::new(0, 0)).unwrap();
        // 重复 queue_id 在插入时即被拒绝
        let err = graph.add_mapping(QueueMapping::new(0, 1)).unwrap_err();
        assert!(matches!(
            err,
            GraphError::InvalidTopology("duplicate queue_id in mappings")
        ));
    }

    // -- 测试 35: iter_nodes 和 iter_mappings --

    #[test]
    fn test_iterators() {
        let mut graph: RuntimeGraph<8, 16> = RuntimeGraph::new();
        graph.add_node(make_node(1, ExecutionDomain::DataPlane, 8, 8192, 4)).unwrap();
        graph.add_node(make_node(2, ExecutionDomain::ControlPlane, 4, 4096, 2)).unwrap();
        graph.add_mapping(QueueMapping::new(0, 0)).unwrap();

        let nodes: Vec<_> = graph.iter_nodes().collect();
        assert_eq!(nodes.len(), 2);

        let mappings: Vec<_> = graph.iter_mappings().collect();
        assert_eq!(mappings.len(), 1);
    }
}