zenith-foundation 0.1.0

Zenith 核心基础设施:统一错误类型、FrameToken 所有权令牌、FramePool、分层资源账本、恒定时间比较
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
//! Frame 池管理模块
//!
//! 实现极致优化的 FramePool 帧池,核心设计原则:
//! - **单线程持有**:每个 Worker 独占一个 FramePool,零锁竞争
//! - **Free-List 栈式分配器**:Vec<u32> 存储空闲帧索引,LIFO 栈式分配 O(1)
//! - **连续内存存储**:Vec<FrameInfo> 连续存储帧信息,缓存友好
//! - **零堆分配**:热路径无任何堆分配操作
//! - **零锁优先**:无任何 Mutex/RwLock/原子操作
//! - **编译期约束**:通过类型系统保证所有权唯一

use crate::error::{CoreError, CoreResult};
use crate::token::FrameToken;

/// Frame ID
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FrameId(u32);

impl FrameId {
    /// 创建新的 Frame ID
    #[inline]
    pub fn new(id: u32) -> Self {
        FrameId(id)
    }

    /// 获取原始 ID 值
    #[inline]
    pub fn value(&self) -> u32 {
        self.0
    }
}

impl From<u32> for FrameId {
    fn from(id: u32) -> Self {
        FrameId(id)
    }
}

/// Frame 状态
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum FrameState {
    /// 空闲状态
    Free = 0,
    /// 已分配给应用
    Allocated = 1,
    /// 在内核 RX Ring 中
    InRxRing = 2,
    /// 在用户态处理中
    Processing = 3,
    /// 在 TX Ring 中等待发送
    InTxRing = 4,
    /// 在完成队列中等待回收
    InCompletionRing = 5,
    /// 在隔离区(异常状态)
    Quarantine = 6,
}

/// Frame 信息(紧凑布局,面向缓存)
#[derive(Debug, Clone)]
#[repr(C)]
pub struct FrameInfo {
    /// Frame ID (紧凑存储)
    id: u32,
    /// 物理地址
    physical_addr: u64,
    /// 虚拟地址
    virtual_addr: u64,
    /// 大小
    size: u32,
    /// 当前状态
    state: FrameState,
    /// 所属域ID
    domain_id: u32,
    /// 代际号
    generation: u64,
}

impl FrameInfo {
    /// 获取 Frame ID
    #[inline]
    pub fn id(&self) -> FrameId {
        FrameId(self.id)
    }

    /// 获取物理地址
    #[inline]
    pub fn physical_addr(&self) -> u64 {
        self.physical_addr
    }

    /// 获取虚拟地址
    #[inline]
    pub fn virtual_addr(&self) -> u64 {
        self.virtual_addr
    }

    /// 获取大小
    #[inline]
    pub fn size(&self) -> u32 {
        self.size
    }

    /// 获取状态
    #[inline]
    pub fn state(&self) -> FrameState {
        self.state
    }

    /// 获取域ID
    #[inline]
    pub fn domain_id(&self) -> u32 {
        self.domain_id
    }

    /// 获取代际号
    #[inline]
    pub fn generation(&self) -> u64 {
        self.generation
    }
}

/// Frame 池(极致优化版)
///
/// ## 核心设计
/// - **Free-List 栈式分配器**:使用 `Vec<u32>` 作为 LIFO 栈,O(1) 分配/回收
/// - **连续内存存储**:`Vec<FrameInfo>` 连续存储,缓存行友好
/// - **单线程持有**:无锁设计,每个 Worker 独占一个 FramePool
/// - **预分配固定容量**:初始化时一次性分配所有帧,运行期禁止扩容
///
/// ## 性能特征
/// - 分配:O(1),仅一次 Vec push/pop
/// - 回收:O(1),仅一次 Vec push
/// - 守恒校验:O(n),但仅在调试/检查时调用
/// - 热路径零堆分配、零锁、零系统调用
#[derive(Debug)]
pub struct FramePool {
    /// 池名称
    name: String,
    /// 总容量
    capacity: u32,
    /// 帧大小
    frame_size: u32,
    /// Free-List:空闲帧索引栈(LIFO)
    free_stack: Vec<u32>,
    /// 帧信息连续存储
    frames: Vec<FrameInfo>,
    /// 已分配计数
    allocated_count: u32,
    /// 隔离区计数
    quarantined_count: u32,
    /// 当前代际号
    generation: u64,
    /// 当前 Epoch 编号
    epoch: u64,
}

impl FramePool {
    /// 创建新的 Frame 池(fail-closed 版本)
    ///
    /// 初始化时一次性分配所有数据结构,运行期禁止扩容。
    ///
    /// # Arguments
    /// * `name` - 池名称
    /// * `capacity` - 总容量(帧数)
    /// * `frame_size` - 每个 Frame 的大小(字节)
    ///
    /// # Returns
    /// * `Ok(FramePool)` - 新的 FramePool 实例
    ///
    /// # Errors
    /// * `frame_size == 0` 或 `capacity == 0` → `CoreError::InvalidConfig`
    /// * `capacity * frame_size` 地址空间溢出 u64 → `CoreError::ArithmeticOverflow`
    pub fn try_new(name: impl Into<String>, capacity: u32, frame_size: u32) -> CoreResult<Self> {
        // 参数校验(fail-closed:非法参数直接返回错误,禁止 panic)
        if frame_size == 0 {
            return Err(CoreError::invalid_config(
                "frame_size",
                "frame_size must be greater than 0",
            ));
        }
        if capacity == 0 {
            return Err(CoreError::invalid_config(
                "capacity",
                "capacity must be greater than 0",
            ));
        }
        // 地址空间溢出检查(fail-closed):capacity * frame_size 必须可容纳于 u64,
        // 禁止静默吞溢出(原 unwrap_or_default 会把物理/虚拟地址置 0)
        (capacity as u64)
            .checked_mul(frame_size as u64)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow("mul", capacity as u64, frame_size as u64)
            })?;

        let name = name.into();

        // 预分配帧信息(连续内存)
        let mut frames: Vec<FrameInfo> = Vec::with_capacity(capacity as usize);
        // 预分配 Free-List 栈
        // LIFO:最后推入的最先弹出,利用缓存局部性
        let mut free_stack: Vec<u32> = Vec::with_capacity(capacity as usize);
        for i in 0..capacity {
            // 逐帧地址偏移同样使用 checked 算术;总量已预检,此处不会溢出
            let offset = (i as u64).checked_mul(frame_size as u64).ok_or_else(|| {
                CoreError::arithmetic_overflow("mul", i as u64, frame_size as u64)
            })?;
            frames.push(FrameInfo {
                id: i,
                physical_addr: offset,
                virtual_addr: offset,
                size: frame_size,
                state: FrameState::Free,
                domain_id: 0,
                generation: 0,
            });
            free_stack.push(i);
        }

        Ok(Self {
            name,
            capacity,
            frame_size,
            free_stack,
            frames,
            allocated_count: 0,
            quarantined_count: 0,
            generation: 0,
            epoch: 0,
        })
    }

    /// 创建新的 Frame 池(兼容版本,禁止 panic)
    ///
    /// 参数非法(`frame_size == 0` / `capacity == 0` / 地址空间溢出)时不 panic,
    /// 回退到最小合法配置(capacity=1, frame_size=1),回退前以 `tracing::error!`
    /// 记录完整原因(池名、参数与底层错误),避免静默降级难以排查。
    ///
    /// **推荐使用 [`FramePool::try_new`]**:显式返回错误、可在调用方精确处置;
    /// 本构造函数仅为不便于传播错误的兼容调用方保留。
    ///
    /// # Arguments
    /// * `name` - 池名称
    /// * `capacity` - 总容量(帧数)
    /// * `frame_size` - 每个 Frame 的大小(字节)
    ///
    /// # Returns
    /// 新的 FramePool 实例
    pub fn new(name: impl Into<String>, capacity: u32, frame_size: u32) -> Self {
        let name = name.into();
        match Self::try_new(name.clone(), capacity, frame_size) {
            Ok(pool) => pool,
            // 回退到最小合法配置(fail-closed:1*1 必然合法,无需 unwrap);
            // 先记录完整失败原因,杜绝「参数非法被静默吞掉」
            Err(e) => {
                tracing::error!(
                    pool = %name,
                    capacity,
                    frame_size,
                    error = %e,
                    "FramePool::new 参数非法,回退到 1x1 最小配置;\
                     需要显式错误处理的调用方应改用 FramePool::try_new"
                );
                Self {
                    name,
                    capacity: 1,
                    frame_size: 1,
                    free_stack: vec![0],
                    frames: vec![FrameInfo {
                        id: 0,
                        physical_addr: 0,
                        virtual_addr: 0,
                        size: 1,
                        state: FrameState::Free,
                        domain_id: 0,
                        generation: 0,
                    }],
                    allocated_count: 0,
                    quarantined_count: 0,
                    generation: 0,
                    epoch: 0,
                }
            }
        }
    }

    /// 获取池名称
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// 获取总容量
    #[inline]
    pub fn capacity(&self) -> u32 {
        self.capacity
    }

    /// 获取帧大小
    #[inline]
    pub fn frame_size(&self) -> u32 {
        self.frame_size
    }

    /// 获取已分配数量
    #[inline]
    pub fn allocated_count(&self) -> u32 {
        self.allocated_count
    }

    /// 获取空闲数量
    #[inline]
    pub fn free_count(&self) -> u32 {
        self.free_stack.len() as u32
    }

    /// 获取隔离区数量
    #[inline]
    pub fn quarantined_count(&self) -> u32 {
        self.quarantined_count
    }

    /// 分配一个 Frame(O(1),零锁零堆分配)
    ///
    /// 从 Free-List 栈顶弹出一个空闲帧,标记为已分配。
    ///
    /// # Arguments
    /// * `domain_id` - 域ID
    ///
    /// # Returns
    /// * `Ok(FrameToken)` - 成功分配的所有权令牌
    /// * `Err(CoreError::QuotaExceeded)` - 资源不足
    #[inline]
    pub fn allocate(&mut self, domain_id: u32) -> CoreResult<FrameToken> {
        // 先查看栈顶(LIFO,利用缓存局部性),完成边界检查后再弹出,
        // 避免内部状态损坏时弹出后丢失帧索引
        let frame_idx = *self
            .free_stack
            .last()
            .ok_or_else(|| {
                CoreError::quota_exceeded("frame", self.capacity as u64, 1)
            })?;

        // 边界检查(fail-closed):free_stack 中的索引必须落在帧数组内,禁止越界 panic
        let frame = self
            .frames
            .get_mut(frame_idx as usize)
            .ok_or_else(|| CoreError::resource_not_found(frame_idx as u64, "frame"))?;
        // 运行时状态检查(CORE-006):free_stack 中的帧必须为 Free,否则 fail-closed。
        // 不使用 debug_assert(release 构建不生效),确保状态不变量在任意构建下强制执行。
        if frame.state != FrameState::Free {
            return Err(CoreError::state_conflict(
                format!("frame {} in state {:?}", frame_idx, frame.state),
                "allocate",
            ));
        }

        // 更新帧状态;代际号取自池级单调计数器,
        // 每次成功释放/隔离都会推进,保证旧令牌在帧重新分配后必然校验失败(防 ABA)
        frame.state = FrameState::Allocated;
        frame.domain_id = domain_id;
        frame.generation = self.generation;

        // 边界检查通过,弹出栈顶
        let _ = self.free_stack.pop();

        // 更新计数(checked 算术)
        self.allocated_count = self
            .allocated_count
            .checked_add(1)
            .ok_or_else(|| CoreError::arithmetic_overflow("add", self.allocated_count as u64, 1))?;

        Ok(FrameToken::new(
            FrameId(frame_idx),
            domain_id,
            self.generation,
            self.epoch,
        ))
    }

    /// 归还 Frame(O(1),零锁零堆分配)
    ///
    /// 验证令牌所有权后,将帧放回 Free-List 栈。
    ///
    /// **注意**:即使验证失败(返回 `Err`),`token` 也会被消费(drop),
    /// 对应的帧将永久泄漏。如果需要在失败后保留令牌以便重试或另行处理,
    /// 请使用 [`FramePool::release_recoverable`]。
    ///
    /// # Arguments
    /// * `token` - 所有权令牌(被消费,即使在错误路径上也会被 drop)
    ///
    /// # Returns
    /// * `Ok(())` - 成功归还
    /// * `Err(CoreError::OwnershipViolation)` - 所有权违规(token 已被消费)
    #[inline]
    pub fn release(&mut self, token: FrameToken) -> CoreResult<()> {
        // 失败路径 token 被 drop(不可恢复,与既有语义一致),仅传播错误
        self.do_release(token).map_err(|(_t, e)| e)
    }

    /// 归还 Frame(可恢复版本,O(1))
    ///
    /// 与 [`release`](Self::release) 语义一致,但在验证失败时将 `token`
    /// 随错误一起返回(`Err((token, error))`),调用方可据此重试或另行处理,
    /// 避免验证失败时帧被永久泄漏。
    ///
    /// # Arguments
    /// * `token` - 所有权令牌(成功时被消费,失败时随错误返回)
    ///
    /// # Returns
    /// * `Ok(())` - 成功归还(token 被消费)
    /// * `Err((FrameToken, CoreError))` - 验证失败,token 随错误返回供调用方处置
    #[inline]
    pub fn release_recoverable(&mut self, token: FrameToken) -> Result<(), (FrameToken, CoreError)> {
        self.do_release(token)
    }

    /// 统一的核心归还逻辑(CORE-031)
    ///
    /// 被 [`release`](Self::release) 与 [`release_recoverable`](Self::release_recoverable)
    /// 共同委托,消除两处重复的归还/校验/记账逻辑。
    ///
    /// 成功时 `token` 被消费;失败时 `token` 随错误返回(`Err((token, error))`),
    /// 由调用方决定丢弃或保留。所有校验均在修改状态前完成(fail-closed)。
    ///
    /// # 代际推进说明(CORE-009)
    /// `self.generation` 使用 `saturating_add`。代际为 u64,池内每次释放/隔离/回收
    /// 推进一次,要在实际生命周期内达到 2^64 次推进不可达,因此饱和语义不会隐藏
    /// 真实溢出;此处保持既有行为,不改变公开子签名。
    fn do_release(&mut self, token: FrameToken) -> Result<(), (FrameToken, CoreError)> {
        let frame_idx = token.frame_id().value();

        // 边界检查(fail-closed):越界索引直接返回错误,禁止 panic
        let frame = match self.frames.get_mut(frame_idx as usize) {
            Some(f) => f,
            None => return Err((token, CoreError::resource_not_found(frame_idx as u64, "frame"))),
        };

        // 代际与域所有权校验(§3.3.4 铁律):
        // 旧令牌在帧被释放并重新分配后,代际必然不匹配,校验失败
        if let Err(e) = token.verify_ownership(frame.domain_id, frame.generation) {
            return Err((token, e));
        }

        // 验证帧状态
        if frame.state != FrameState::Allocated {
            return Err((
                token,
                CoreError::ownership_violation("allocated", "not_allocated"),
            ));
        }

        // 预检算术:checked_sub 失败属于内部不变量违例,
        // 在修改状态前返回错误,保证失败路径状态不被破坏
        let new_count = match self.allocated_count.checked_sub(1) {
            Some(c) => c,
            None => {
                return Err((
                    token,
                    CoreError::arithmetic_overflow("sub", self.allocated_count as u64, 1),
                ))
            }
        };

        // 所有校验通过,开始修改状态
        frame.state = FrameState::Free;

        // 推进代际(防 ABA):使所有指向本帧的旧令牌立即失效
        self.generation = self.generation.saturating_add(1);
        frame.generation = self.generation;

        // 放回 Free-List 栈顶
        self.free_stack.push(frame_idx);

        // 更新计数
        self.allocated_count = new_count;

        // 令牌被消费
        let _ = token;
        Ok(())
    }

    /// 将 Frame 移入隔离区
    ///
    /// 隔离区帧不会被自动回收,需要手动调用 `recover_from_quarantine`。
    ///
    /// # Arguments
    /// * `token` - 所有权令牌(被消费)
    /// * `reason` - 隔离原因
    ///
    /// # Returns
    /// * `Ok(())` - 成功隔离
    pub fn quarantine(&mut self, token: FrameToken, reason: impl Into<String>) -> CoreResult<()> {
        let frame_idx = token.frame_id().value();

        // 边界检查(fail-closed):越界索引直接返回错误,禁止 panic
        let frame = self
            .frames
            .get_mut(frame_idx as usize)
            .ok_or_else(|| CoreError::resource_not_found(frame_idx as u64, "frame"))?;

        // 代际与域所有权校验(§3.3.4 铁律)
        token.verify_ownership(frame.domain_id, frame.generation)?;

        // 仅允许从 Allocated 状态隔离(fail-closed:先校验后变更,避免部分状态污染)
        if frame.state != FrameState::Allocated {
            return Err(CoreError::ownership_violation("allocated", "not_allocated"));
        }

        // 更新状态
        frame.state = FrameState::Quarantine;

        // 推进代际(防 ABA):使所有指向本帧的旧令牌立即失效
        self.generation = self.generation.saturating_add(1);
        frame.generation = self.generation;

        // 更新计数
        self.allocated_count = self
            .allocated_count
            .checked_sub(1)
            .ok_or_else(|| CoreError::arithmetic_overflow("sub", self.allocated_count as u64, 1))?;
        self.quarantined_count = self
            .quarantined_count
            .checked_add(1)
            .ok_or_else(|| CoreError::arithmetic_overflow("add", self.quarantined_count as u64, 1))?;

        // 隔离原因不再静默丢弃:以 debug 级结构化日志记录,便于事后审计定位
        tracing::debug!(
            pool = %self.name,
            frame_id = frame_idx,
            reason = %reason.into(),
            "frame quarantined"
        );
        // 令牌被消费(token 在函数结束时自动释放所有权)
        let _ = token;
        Ok(())
    }

    /// 从隔离区回收 Frame
    ///
    /// **注意**:本方法仅凭 `frame_id` 回收,**不**验证代际(CORE-008)。
    /// 仅适用于调用方可确认帧未被回收重新分配的内部安全场景。
    /// 数据面路径(持有 frame_id + expected_generation)应使用
    /// [`recover_from_quarantine_by_id`](Self::recover_from_quarantine_by_id),
    /// 以代际验证防止陈旧 FrameId 被复用。
    ///
    /// # Arguments
    /// * `frame_id` - Frame ID
    ///
    /// # Returns
    /// * `Ok(())` - 成功回收
    /// * `Err(CoreError::ResourceNotFound)` - Frame 不在隔离区
    pub fn recover_from_quarantine(&mut self, frame_id: FrameId) -> CoreResult<()> {
        let frame_idx = frame_id.value();

        // 边界检查
        if (frame_idx as usize) >= self.frames.len() {
            return Err(CoreError::resource_not_found(frame_idx as u64, "frame"));
        }

        let frame = &mut self.frames[frame_idx as usize];
        if frame.state != FrameState::Quarantine {
            return Err(CoreError::resource_not_found(frame_idx as u64, "frame"));
        }

        // 更新状态
        frame.state = FrameState::Free;

        // 推进代际(防 ABA):与 release/quarantine 一致的写法,
        // 「隔离 → 回收 → 重新分配」链路中旧代际句柄必然校验失败,
        // 关闭回收不推进代际留下的窄 ABA 窗口
        self.generation = self.generation.saturating_add(1);
        frame.generation = self.generation;

        // 放回 Free-List 栈
        self.free_stack.push(frame_idx);

        // 更新计数
        self.quarantined_count = self
            .quarantined_count
            .checked_sub(1)
            .ok_or_else(|| CoreError::arithmetic_overflow("sub", self.quarantined_count as u64, 1))?;

        Ok(())
    }

    /// 从隔离区回收 Frame(代际验证版本,CORE-008)
    ///
    /// 与 [`recover_from_quarantine`](Self::recover_from_quarantine) 语义一致,
    /// 额外校验期望代际号与当前帧代际一致,防止陈旧 FrameId 被恶意复用到
    /// 新帧上(防 ABA)。适用于 Worker 数据面等持有 frame_id + expected_generation
    /// 的调用路径。
    ///
    /// # Arguments
    /// * `frame_id` - Frame ID
    /// * `expected_generation` - 期望的代际号(必须匹配当前帧的代际)
    ///
    /// # Returns
    /// * `Ok(())` - 成功回收
    /// * `Err(CoreError::ResourceNotFound)` - Frame 不在隔离区
    /// * `Err(CoreError::OwnershipViolation)` - 代际不匹配
    pub fn recover_from_quarantine_by_id(
        &mut self,
        frame_id: FrameId,
        expected_generation: u64,
    ) -> CoreResult<()> {
        let frame_idx = frame_id.value();

        // 边界检查
        if (frame_idx as usize) >= self.frames.len() {
            return Err(CoreError::resource_not_found(frame_idx as u64, "frame"));
        }

        let frame = &mut self.frames[frame_idx as usize];
        if frame.state != FrameState::Quarantine {
            return Err(CoreError::resource_not_found(frame_idx as u64, "frame"));
        }

        // 代际验证:防止陈旧 FrameID 被复用到新帧
        if frame.generation != expected_generation {
            return Err(CoreError::ownership_violation(
                "valid generation",
                "invalid generation",
            ));
        }

        // 更新状态
        frame.state = FrameState::Free;

        // 推进代际(防 ABA):与 release/quarantine 一致的写法
        self.generation = self.generation.saturating_add(1);
        frame.generation = self.generation;

        // 放回 Free-List 栈
        self.free_stack.push(frame_idx);

        // 更新计数
        self.quarantined_count = self
            .quarantined_count
            .checked_sub(1)
            .ok_or_else(|| CoreError::arithmetic_overflow("sub", self.quarantined_count as u64, 1))?;

        Ok(())
    }

    /// 通过 Frame ID 隔离帧(无 Token 场景)
    ///
    /// 当 FrameToken 已被消费(如通过 Ring 传递给内核)时,
    /// 只能通过 Frame ID 来隔离帧。此方法用于 Worker 数据面循环
    /// 中的解析错误和准入拒绝场景。
    ///
    /// # 安全保证
    /// 必须传入期望的代际号,用于验证帧未被回收重新分配。
    /// 这防止了陈旧 FrameID 被恶意复用到新帧上。
    ///
    /// # 状态转换
    /// Allocated/Processing/InRxRing/InTxRing/InCompletionRing → Quarantine
    ///
    /// # Arguments
    /// * `frame_id` - Frame ID
    /// * `expected_generation` - 期望的代际号(必须匹配当前帧的代际)
    /// * `reason` - 隔离原因
    ///
    /// # Returns
    /// * `Ok(())` - 成功隔离
    /// * `Err(CoreError::OwnershipViolation)` - 代际不匹配或状态非法
    pub fn quarantine_by_id(
        &mut self,
        frame_id: FrameId,
        expected_generation: u64,
        reason: impl Into<String>,
    ) -> CoreResult<()> {
        let frame_idx = frame_id.value();

        // 边界检查
        if (frame_idx as usize) >= self.frames.len() {
            return Err(CoreError::resource_not_found(frame_idx as u64, "frame"));
        }

        let frame = &mut self.frames[frame_idx as usize];

        // 代际验证:防止陈旧 FrameID 被复用到新帧
        if frame.generation != expected_generation {
            return Err(CoreError::ownership_violation(
                "valid generation",
                "invalid generation",
            ));
        }

        // 仅允许从活跃状态转换到隔离状态
        match frame.state {
            FrameState::Allocated
            | FrameState::Processing
            | FrameState::InRxRing
            | FrameState::InTxRing
            | FrameState::InCompletionRing => {
                // 所有 in-use 状态(Allocated/Processing/InRxRing/InTxRing/InCompletionRing)
                // 均由 allocated_count 跟踪(分配时经 allocate 计入),隔离时必须一律扣减,
                // 否则守恒不变量 free + allocated + quarantined == capacity 被破坏。
                // 不变量:这些状态只能由 allocate 产生,故 allocated_count 恒 ≥ 隔离前各帧
                // 在 in-use 状态中者;此处 checked_sub 防 underflow 兜底不变量损坏场景。
                self.allocated_count = self
                    .allocated_count
                    .checked_sub(1)
                    .ok_or_else(|| CoreError::arithmetic_overflow("sub", self.allocated_count as u64, 1))?;
            }
            _ => {
                return Err(CoreError::state_conflict(
                    format!("frame {} in state {:?}", frame_idx, frame.state),
                    "quarantine",
                ));
            }
        }

        frame.state = FrameState::Quarantine;

        // 推进代际(防 ABA):帧被隔离后再恢复/重分配时,旧代际句柄必然失效
        self.generation = self.generation.saturating_add(1);
        frame.generation = self.generation;

        self.quarantined_count = self
            .quarantined_count
            .checked_add(1)
            .ok_or_else(|| CoreError::arithmetic_overflow("add", self.quarantined_count as u64, 1))?;

        // 隔离原因不再静默丢弃:以 debug 级结构化日志记录,便于事后审计定位
        tracing::debug!(
            pool = %self.name,
            frame_id = frame_idx,
            reason = %reason.into(),
            "frame quarantined by id"
        );
        Ok(())
    }

    /// 推进代际号
    ///
    /// 代际号用于在热更新期间区分新旧资源,防止跨代际访问。
    ///
    /// # 溢出说明(CORE-009)
    /// 使用 `saturating_add`:代际为 u64,每次分配/释放/隔离/回收推进一次,
    /// 要在实际生命周期内达到 2^64 次推进不可达,故饱和语义不会隐藏真实溢出,
    /// 保持既有行为(不改变 `-> u64` 签名引入错误传播)。
    ///
    /// # Returns
    /// 新的代际号
    #[inline]
    pub fn advance_generation(&mut self) -> u64 {
        self.generation = self.generation.saturating_add(1);
        self.generation
    }

    /// 获取当前代际号
    #[inline]
    pub fn current_generation(&self) -> u64 {
        self.generation
    }

    /// 推进 Epoch
    ///
    /// Epoch 用于标识配置快照的唯一版本,防止过期操作。
    ///
    /// # 溢出说明(CORE-009)
    /// `saturating_add`:与代际同理,u64 在实际生命周期内不可达溢出。
    ///
    /// # Returns
    /// 新的 Epoch 编号
    #[inline]
    pub fn advance_epoch(&mut self) -> u64 {
        self.epoch = self.epoch.saturating_add(1);
        self.epoch
    }

    /// 获取当前 Epoch 编号
    #[inline]
    pub fn current_epoch(&self) -> u64 {
        self.epoch
    }

    /// 获取 Frame 信息(返回克隆副本)
    ///
    /// # Arguments
    /// * `frame_id` - Frame ID
    ///
    /// # Returns
    /// * `Some(FrameInfo)` - Frame 信息副本
    /// * `None` - 未找到
    #[inline]
    pub fn get_frame_info(&self, frame_id: FrameId) -> Option<FrameInfo> {
        self.frames.get(frame_id.value() as usize).cloned()
    }

    /// 批量分配 Frame
    ///
    /// 一次性分配多个 Frame,减少函数调用开销。
    /// 返回的令牌需要逐个归还。
    ///
    /// # Arguments
    /// * `domain_id` - 域ID
    /// * `count` - 要分配的数量
    ///
    /// # Returns
    /// * `Ok(Vec<FrameToken>)` - 成功分配的令牌列表
    /// * `Err(CoreError::QuotaExceeded)` - 资源不足(部分分配时已分配帧全部回滚)
    pub fn allocate_batch(&mut self, domain_id: u32, count: u32) -> CoreResult<Vec<FrameToken>> {
        // 预检查容量
        if self.free_stack.len() < count as usize {
            return Err(CoreError::quota_exceeded(
                "frame",
                self.free_stack.len() as u64,
                count as u64,
            ));
        }

        let mut tokens = Vec::with_capacity(count as usize);
        for _ in 0..count {
            match self.allocate(domain_id) {
                Ok(t) => tokens.push(t),
                Err(e) => {
                    // 回滚:归还已分配的帧,避免 FrameToken drop 时不归还帧的泄漏。
                    // 使用 release_recoverable:即使某个帧归还失败(不应发生),
                    // 也尽力归还其余帧,且不 panic(CORE-024)。
                    for t in tokens {
                        if let Err((_t, re)) = self.release_recoverable(t) {
                            tracing::error!(
                                pool = %self.name,
                                error = %re,
                                "allocate_batch 回滚归还帧失败(尽力回滚,帧可能泄漏)"
                            );
                        }
                    }
                    return Err(e);
                }
            }
        }
        Ok(tokens)
    }

    /// 批量归还 Frame
    ///
    /// # Arguments
    /// * `tokens` - 所有权令牌列表(全部被消费)
    ///
    /// # Returns
    /// * `Ok(())` - 成功归还
    /// * `Err(CoreError)` - 某帧归还失败(剩余帧仍尽力归还,返回首个错误)
    pub fn release_batch(&mut self, tokens: Vec<FrameToken>) -> CoreResult<()> {
        let mut first_err: Option<CoreError> = None;
        for token in tokens {
            // 使用 release_recoverable:失败时 token 随错误返回,
            // 避免 token 被 drop 导致帧永久泄漏
            if let Err((_token, e)) = self.release_recoverable(token)
                && first_err.is_none()
            {
                first_err = Some(e);
            }
        }
        match first_err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// 验证所有权守恒
    ///
    /// 恒等式:空闲 + 已分配 + 隔离 = 总容量
    ///
    /// # Returns
    /// * `Ok(())` - 守恒
    /// * `Err(CoreError::Internal)` - 不守恒
    #[inline]
    pub fn verify_conservation(&self) -> CoreResult<()> {
        let free = self.free_stack.len() as u64;
        let allocated = self.allocated_count as u64;
        let quarantined = self.quarantined_count as u64;

        let total = free
            .checked_add(allocated)
            .and_then(|v| v.checked_add(quarantined))
            .ok_or_else(|| CoreError::arithmetic_overflow("add", free, allocated))?;

        if total != self.capacity as u64 {
            return Err(CoreError::internal(format!(
                "conservation violation: total={}, capacity={}, free={}, allocated={}, quarantined={}",
                total, self.capacity, free, allocated, quarantined
            )));
        }

        Ok(())
    }

    /// 通过 Frame ID 归还 Frame(O(1),用于环形队列回收路径)
    ///
    /// 此方法用于 AF_XDP 环形队列完成回收路径,
    /// 通过帧索引直接归还帧,无需 FrameToken。
    ///
    /// # 安全保证
    /// 必须传入期望的代际号,用于验证帧未被回收重新分配。
    /// 同时验证帧必须处于 Allocated 状态。
    ///
    /// # 安全约束
    /// - 帧必须处于 Allocated 状态
    /// - 代际号必须匹配当前帧的代际
    /// - 调用者必须确保没有其他持有者在使用该帧
    ///
    /// # Arguments
    /// * `frame_id` - Frame ID
    /// * `expected_generation` - 期望的代际号(必须匹配当前帧的代际)
    ///
    /// # Returns
    /// * `Ok(())` - 成功归还
    /// * `Err(CoreError::OwnershipViolation)` - 帧不在 Allocated 状态或代际不匹配
    #[inline]
    pub fn release_by_id(&mut self, frame_id: FrameId, expected_generation: u64) -> CoreResult<()> {
        let frame_idx = frame_id.value();

        // 边界检查(fail-closed):越界索引直接返回错误,禁止 panic
        let frame = self
            .frames
            .get_mut(frame_idx as usize)
            .ok_or_else(|| CoreError::resource_not_found(frame_idx as u64, "frame"))?;

        // 代际验证:防止陈旧 FrameID 被复用到新帧
        if frame.generation != expected_generation {
            return Err(CoreError::ownership_violation(
                "valid generation",
                "invalid generation",
            ));
        }

        if frame.state != FrameState::Allocated {
            return Err(CoreError::ownership_violation("allocated", "not_allocated"));
        }

        frame.state = FrameState::Free;

        // 推进代际(防 ABA):与 release/quarantine 一致,
        // 使所有指向本帧的旧代际句柄在帧重新分配后必然校验失败
        self.generation = self.generation.saturating_add(1);
        frame.generation = self.generation;

        self.free_stack.push(frame_idx);

        self.allocated_count = self
            .allocated_count
            .checked_sub(1)
            .ok_or_else(|| CoreError::arithmetic_overflow("sub", self.allocated_count as u64, 1))?;

        Ok(())
    }

    /// 获取底层帧信息切片(用于批量操作)
    ///
    /// # Returns
    /// 帧信息的切片引用
    #[inline]
    pub fn frames(&self) -> &[FrameInfo] {
        &self.frames
    }

    /// 获取 Free-List 栈的剩余容量
    ///
    /// # Returns
    /// 栈中剩余的空闲帧数
    #[inline]
    pub fn remaining_free(&self) -> u32 {
        self.free_stack.len() as u32
    }
}

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

    const TEST_CAPACITY: u32 = 100;
    const TEST_FRAME_SIZE: u32 = 2048;

    fn create_test_pool() -> FramePool {
        FramePool::new("test_pool", TEST_CAPACITY, TEST_FRAME_SIZE)
    }

    #[test]
    fn test_pool_creation() {
        let pool = create_test_pool();
        assert_eq!(pool.name(), "test_pool");
        assert_eq!(pool.capacity(), TEST_CAPACITY);
        assert_eq!(pool.frame_size(), TEST_FRAME_SIZE);
        assert_eq!(pool.free_count(), TEST_CAPACITY);
        assert_eq!(pool.allocated_count(), 0);
        assert_eq!(pool.quarantined_count(), 0);
    }

    #[test]
    fn test_allocate_and_release() {
        let mut pool = create_test_pool();

        // 分配
        let token = pool.allocate(0).unwrap();
        assert_eq!(pool.allocated_count(), 1);
        assert_eq!(pool.free_count(), TEST_CAPACITY - 1);

        // 验证所有权
        assert!(token.verify_ownership(0, 0).is_ok());

        // 归还
        pool.release(token).unwrap();
        assert_eq!(pool.allocated_count(), 0);
        assert_eq!(pool.free_count(), TEST_CAPACITY);
    }

    #[test]
    fn test_allocate_exhausted() {
        let mut pool = FramePool::new("small_pool", 2, TEST_FRAME_SIZE);

        let token1 = pool.allocate(0).unwrap();
        let token2 = pool.allocate(0).unwrap();

        // 第三次分配应该失败
        let result = pool.allocate(0);
        assert!(result.is_err());

        // 归还后应该可以再分配
        pool.release(token1).unwrap();
        let token3 = pool.allocate(0).unwrap();
        // ABA 修复:release 推进了代际,重新分配的令牌代际必然递增,
        // 旧代际 (0) 校验必须失败,新代际校验必须成功
        assert_ne!(token3.generation(), 0);
        assert!(token3.verify_ownership(0, 0).is_err());
        assert!(token3.verify_ownership(0, token3.generation()).is_ok());

        pool.release(token2).unwrap();
        pool.release(token3).unwrap();
    }

    #[test]
    fn test_quarantine_and_recover() {
        let mut pool = create_test_pool();

        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();

        // 隔离
        pool.quarantine(token, "test reason").unwrap();
        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.allocated_count(), 0);
        assert_eq!(pool.free_count(), TEST_CAPACITY - 1);

        // 回收
        pool.recover_from_quarantine(frame_id).unwrap();
        assert_eq!(pool.quarantined_count(), 0);
        assert_eq!(pool.free_count(), TEST_CAPACITY);
    }

    #[test]
    fn test_quarantine_nonexistent() {
        let mut pool = create_test_pool();
        let result = pool.recover_from_quarantine(FrameId::new(999));
        assert!(result.is_err());
    }

    #[test]
    fn test_generation_management() {
        let mut pool = create_test_pool();
        assert_eq!(pool.current_generation(), 0);

        let generation = pool.advance_generation();
        assert_eq!(generation, 1);
        assert_eq!(pool.current_generation(), 1);
    }

    #[test]
    fn test_epoch_management() {
        let mut pool = create_test_pool();
        assert_eq!(pool.current_epoch(), 0);

        let epoch = pool.advance_epoch();
        assert_eq!(epoch, 1);
        assert_eq!(pool.current_epoch(), 1);
    }

    #[test]
    fn test_verify_conservation() {
        let mut pool = create_test_pool();

        // 初始状态守恒
        assert!(pool.verify_conservation().is_ok());

        // 分配后守恒
        let token = pool.allocate(0).unwrap();
        assert!(pool.verify_conservation().is_ok());

        // 归还后守恒
        pool.release(token).unwrap();
        assert!(pool.verify_conservation().is_ok());

        // 隔离后守恒
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        pool.quarantine(token, "test").unwrap();
        assert!(pool.verify_conservation().is_ok());

        // 从隔离区回收后守恒(使用正确的 frame_id)
        pool.recover_from_quarantine(frame_id).unwrap();
        assert!(pool.verify_conservation().is_ok());
    }

    #[test]
    fn test_get_frame_info() {
        let pool = create_test_pool();

        let info = pool.get_frame_info(FrameId::new(0)).unwrap();
        assert_eq!(info.id(), FrameId::new(0));
        assert_eq!(info.size(), TEST_FRAME_SIZE);
        assert_eq!(info.state(), FrameState::Free);
    }

    #[test]
    fn test_allocate_batch() {
        let mut pool = create_test_pool();

        // 批量分配10个
        let tokens = pool.allocate_batch(0, 10).unwrap();
        assert_eq!(tokens.len(), 10);
        assert_eq!(pool.allocated_count(), 10);
        assert_eq!(pool.free_count(), TEST_CAPACITY - 10);

        // 批量归还
        pool.release_batch(tokens).unwrap();
        assert_eq!(pool.allocated_count(), 0);
        assert_eq!(pool.free_count(), TEST_CAPACITY);
    }

    #[test]
    fn test_allocate_batch_exhausted() {
        let mut pool = FramePool::new("tiny_pool", 5, TEST_FRAME_SIZE);

        // 尝试批量分配超过容量
        let result = pool.allocate_batch(0, 10);
        assert!(result.is_err());

        // 确保没有部分分配
        assert_eq!(pool.allocated_count(), 0);
        assert_eq!(pool.free_count(), 5);
    }

    #[test]
    fn test_release_wrong_state() {
        let mut pool = create_test_pool();

        // 尝试归还一个空闲帧的 token(直接构造无效token)
        // 这在实际使用中不可能发生,因为 FrameToken 只能通过 allocate 获取
        // 但我们测试一下状态检查
        let token = pool.allocate(0).unwrap();
        let frame_idx = token.frame_id().value();

        // 先正常归还
        pool.release(token).unwrap();

        // 现在该帧是 Free 状态
        // 如果我们能构造一个 FrameToken(实际不能,因为 pub(crate) 构造函数)
        // 这里仅验证 get_frame_info 返回正确状态
        let info = pool.get_frame_info(FrameId::new(frame_idx)).unwrap();
        assert_eq!(info.state(), FrameState::Free);
    }

    #[test]
    fn test_free_list_lifo_order() {
        let mut pool = FramePool::new("lifo_test", 3, TEST_FRAME_SIZE);

        // 分配全部
        let t0 = pool.allocate(0).unwrap(); // 弹出栈顶(idx=2)
        let t1 = pool.allocate(0).unwrap(); // 弹出栈顶(idx=1)
        let t2 = pool.allocate(0).unwrap(); // 弹出栈顶(idx=0)

        assert_eq!(t0.frame_id().value(), 2);
        assert_eq!(t1.frame_id().value(), 1);
        assert_eq!(t2.frame_id().value(), 0);

        // 归还第一个分配的帧
        pool.release(t0).unwrap(); // 压入栈顶(idx=2)
        let t3 = pool.allocate(0).unwrap(); // 弹出栈顶(idx=2)
        assert_eq!(t3.frame_id().value(), 2);

        pool.release(t1).unwrap();
        pool.release(t2).unwrap();
        pool.release(t3).unwrap();
    }

    #[test]
    fn test_domain_isolation() {
        let mut pool = create_test_pool();

        // 域0分配
        let token0 = pool.allocate(0).unwrap();
        assert_eq!(token0.domain_id(), 0);
        assert!(token0.verify_ownership(0, 0).is_ok());
        assert!(token0.verify_ownership(1, 0).is_err());

        // 域1分配
        let token1 = pool.allocate(1).unwrap();
        assert_eq!(token1.domain_id(), 1);
        assert!(token1.verify_ownership(1, 0).is_ok());
        assert!(token1.verify_ownership(0, 0).is_err());

        pool.release(token0).unwrap();
        pool.release(token1).unwrap();
    }

    #[test]
    fn test_release_by_id() {
        let mut pool = create_test_pool();

        // 分配一个帧
        let token = pool.allocate(42).unwrap();
        let frame_id = token.frame_id();
        let token_gen = token.generation();
        assert_eq!(pool.allocated_count(), 1);

        // 使用 release_by_id 归还
        pool.release_by_id(frame_id, token_gen).unwrap();
        assert_eq!(pool.allocated_count(), 0);
        assert!(pool.verify_conservation().is_ok());

        // 再次释放应该失败(帧已空闲)
        let result = pool.release_by_id(frame_id, token_gen);
        assert!(result.is_err());
    }

    #[test]
    fn test_release_by_id_with_wrong_state() {
        let mut pool = create_test_pool();

        // 尝试释放空闲帧(应该失败)
        let result = pool.release_by_id(FrameId::new(0), pool.current_generation());
        assert!(result.is_err());
    }

    #[test]
    fn test_release_by_id_out_of_bounds() {
        let mut pool = create_test_pool();

        // 越界索引必须 fail-closed 返回错误,禁止 panic
        let result = pool.release_by_id(FrameId::new(TEST_CAPACITY), pool.current_generation());
        assert!(result.is_err());

        let result = pool.release_by_id(FrameId::new(u32::MAX), pool.current_generation());
        assert!(result.is_err());

        // 池状态未被破坏
        assert!(pool.verify_conservation().is_ok());
    }

    #[test]
    fn test_release_by_id_aba_protection() {
        let mut pool = FramePool::new("aba_test", 1, TEST_FRAME_SIZE);

        // 分配唯一的帧并记录代际
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let gen_v1 = token.generation();
        let _ = token;

        // 通过 release_by_id 归还:代际必须推进
        pool.release_by_id(frame_id, gen_v1).unwrap();

        // 旧代际句柄立即失效(帧已空闲,且代际已推进)
        assert!(pool.release_by_id(frame_id, gen_v1).is_err());

        // 帧重新分配后获得新代际,旧句柄 (frame_id, gen_v1) 依然失效(防 ABA)
        let token2 = pool.allocate(0).unwrap();
        let gen_v2 = token2.generation();
        assert_ne!(gen_v1, gen_v2);
        assert!(pool.release_by_id(frame_id, gen_v1).is_err());

        // 新代际句柄正常工作
        pool.release_by_id(frame_id, gen_v2).unwrap();
        assert!(pool.verify_conservation().is_ok());
    }

    #[test]
    fn test_release_token_aba_protection() {
        let mut pool = FramePool::new("aba_token", 1, TEST_FRAME_SIZE);

        // 分配后归还,令牌被消费;帧重新分配后旧代际必然失配
        let token = pool.allocate(0).unwrap();
        let gen_v1 = token.generation();
        pool.release(token).unwrap();

        let token2 = pool.allocate(0).unwrap();
        // 重新分配后帧代际已推进,与首次分配不同
        assert_ne!(token2.generation(), gen_v1);
        pool.release(token2).unwrap();
        assert!(pool.verify_conservation().is_ok());
    }

    // ===== quarantine_by_id 状态转换测试 =====

    fn set_frame_state(pool: &mut FramePool, frame_id: u32, state: FrameState) {
        let current_gen = pool.current_generation();
        let frame = &mut pool.frames[frame_id as usize];
        frame.state = state;
        frame.generation = current_gen;
    }

    #[test]
    fn test_quarantine_by_id_from_allocated() {
        let mut pool = create_test_pool();
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let token_gen = token.generation();
        let _ = token;

        assert_eq!(pool.allocated_count(), 1);
        assert_eq!(pool.quarantined_count(), 0);

        pool.quarantine_by_id(frame_id, token_gen, "test").unwrap();

        assert_eq!(pool.allocated_count(), 0);
        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.get_frame_info(frame_id).unwrap().state(), FrameState::Quarantine);
        assert!(pool.verify_conservation().is_ok());
    }

    #[test]
    fn test_quarantine_by_id_from_processing() {
        let mut pool = create_test_pool();
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let idx = frame_id.value();
        let token_gen = token.generation();
        let _ = token;

        set_frame_state(&mut pool, idx, FrameState::Processing);
        pool.quarantine_by_id(frame_id, token_gen, "test").unwrap();

        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.get_frame_info(frame_id).unwrap().state(), FrameState::Quarantine);
    }

    // ===== CORE-007:Processing 状态帧隔离后守恒等式仍成立 =====

    #[test]
    fn test_quarantine_by_id_processing_conservation() {
        let mut pool = create_test_pool();
        // 分配多个帧,其中一帧进入 Processing 状态
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let idx = frame_id.value();
        let token_gen = token.generation();
        let _ = token;

        set_frame_state(&mut pool, idx, FrameState::Processing);
        // 隔离前守恒
        assert!(pool.verify_conservation().is_ok());

        pool.quarantine_by_id(frame_id, token_gen, "processing-conflict").unwrap();

        // 隔离后守恒等式 free + allocated + quarantined == capacity 仍成立
        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.allocated_count(), 0);
        assert!(pool.verify_conservation().is_ok());
    }

    // ===== CORE-008:recover_from_quarantine_by_id 代际验证 =====

    #[test]
    fn test_recover_from_quarantine_by_id_generation_mismatch() {
        let mut pool = create_test_pool();
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        pool.quarantine(token, "test").unwrap(); // 隔离推进代际

        let correct_gen = pool.get_frame_info(frame_id).unwrap().generation();

        // 错误代际:回收必须失败,帧保持隔离,守恒不被破坏
        assert!(pool
            .recover_from_quarantine_by_id(frame_id, correct_gen + 1)
            .is_err());
        assert_eq!(pool.quarantined_count(), 1);
        assert!(pool.verify_conservation().is_ok());

        // 正确代际:回收成功
        pool.recover_from_quarantine_by_id(frame_id, correct_gen).unwrap();
        assert_eq!(pool.quarantined_count(), 0);
        assert_eq!(pool.free_count(), TEST_CAPACITY);
        assert!(pool.verify_conservation().is_ok());
    }

    #[test]
    fn test_quarantine_by_id_from_in_rx_ring() {
        let mut pool = create_test_pool();
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let idx = frame_id.value();
        let token_gen = token.generation();
        let _ = token;

        set_frame_state(&mut pool, idx, FrameState::InRxRing);
        pool.quarantine_by_id(frame_id, token_gen, "test").unwrap();

        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.get_frame_info(frame_id).unwrap().state(), FrameState::Quarantine);
    }

    #[test]
    fn test_quarantine_by_id_from_in_tx_ring() {
        let mut pool = create_test_pool();
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let idx = frame_id.value();
        let token_gen = token.generation();
        let _ = token;

        set_frame_state(&mut pool, idx, FrameState::InTxRing);
        pool.quarantine_by_id(frame_id, token_gen, "test").unwrap();

        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.get_frame_info(frame_id).unwrap().state(), FrameState::Quarantine);
    }

    #[test]
    fn test_quarantine_by_id_from_in_completion_ring() {
        let mut pool = create_test_pool();
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let idx = frame_id.value();
        let token_gen = token.generation();
        let _ = token;

        set_frame_state(&mut pool, idx, FrameState::InCompletionRing);
        pool.quarantine_by_id(frame_id, token_gen, "test").unwrap();

        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.get_frame_info(frame_id).unwrap().state(), FrameState::Quarantine);
    }

    // ===== quarantine_by_id 状态冲突测试 =====

    #[test]
    fn test_quarantine_by_id_from_free_fails() {
        let mut pool = create_test_pool();
        let result = pool.quarantine_by_id(FrameId::new(0), pool.current_generation(), "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_quarantine_by_id_from_quarantine_fails() {
        let mut pool = create_test_pool();
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        pool.quarantine(token, "first").unwrap();

        let result = pool.quarantine_by_id(frame_id, pool.current_generation(), "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_quarantine_by_id_out_of_bounds() {
        let mut pool = create_test_pool();
        let result = pool.quarantine_by_id(FrameId::new(9999), pool.current_generation(), "test");
        assert!(result.is_err());
    }

    // ===== FrameState 变体值/排序测试 =====

    #[test]
    fn test_frame_state_discriminant_values() {
        assert_eq!(FrameState::Free as u8, 0);
        assert_eq!(FrameState::Allocated as u8, 1);
        assert_eq!(FrameState::InRxRing as u8, 2);
        assert_eq!(FrameState::Processing as u8, 3);
        assert_eq!(FrameState::InTxRing as u8, 4);
        assert_eq!(FrameState::InCompletionRing as u8, 5);
        assert_eq!(FrameState::Quarantine as u8, 6);
    }

    #[test]
    fn test_frame_state_equality() {
        assert_eq!(FrameState::Free, FrameState::Free);
        assert_ne!(FrameState::Free, FrameState::Allocated);
        assert_ne!(FrameState::Allocated, FrameState::Processing);
    }

    #[test]
    fn test_frame_state_clone_copy() {
        let s = FrameState::Processing;
        let s2 = s;
        assert_eq!(s, s2);
        let s3 = s;
        assert_eq!(s, s3);
    }

    #[test]
    fn test_frame_state_debug() {
        let s = format!("{:?}", FrameState::Quarantine);
        assert_eq!(s, "Quarantine");
    }

    // ===== 边界条件测试 =====

    #[test]
    fn test_pool_capacity_one() {
        let mut pool = FramePool::new("single", 1, 4096);
        assert_eq!(pool.capacity(), 1);
        assert_eq!(pool.free_count(), 1);
        assert_eq!(pool.allocated_count(), 0);

        let token = pool.allocate(0).unwrap();
        assert_eq!(pool.free_count(), 0);
        assert_eq!(pool.allocated_count(), 1);

        let result = pool.allocate(0);
        assert!(result.is_err());

        pool.release(token).unwrap();
        assert_eq!(pool.free_count(), 1);
        assert_eq!(pool.allocated_count(), 0);
        assert!(pool.verify_conservation().is_ok());
    }

    #[test]
    fn test_capacity_one_quarantine_and_recover() {
        let mut pool = FramePool::new("single_q", 1, 4096);
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();

        pool.quarantine(token, "test").unwrap();
        assert_eq!(pool.quarantined_count(), 1);
        assert_eq!(pool.free_count(), 0);

        pool.recover_from_quarantine(frame_id).unwrap();
        assert_eq!(pool.quarantined_count(), 0);
        assert_eq!(pool.free_count(), 1);
        assert!(pool.verify_conservation().is_ok());
    }

    #[test]
    fn test_frame_id_value_boundaries() {
        let id_zero = FrameId::new(0);
        assert_eq!(id_zero.value(), 0);

        let id_max = FrameId::new(u32::MAX);
        assert_eq!(id_max.value(), u32::MAX);
    }

    // ===== get_frame_info 越界测试 =====

    #[test]
    fn test_get_frame_info_out_of_bounds() {
        let pool = create_test_pool();
        assert!(pool.get_frame_info(FrameId::new(TEST_CAPACITY)).is_none());
        assert!(pool.get_frame_info(FrameId::new(u32::MAX)).is_none());
    }

    #[test]
    fn test_get_frame_info_valid_boundary() {
        let pool = create_test_pool();
        assert!(pool.get_frame_info(FrameId::new(0)).is_some());
        assert!(pool.get_frame_info(FrameId::new(TEST_CAPACITY - 1)).is_some());
    }

    // ===== FrameId From<u32> trait 测试 =====

    #[test]
    fn test_frame_id_from_u32() {
        let id: FrameId = 42u32.into();
        assert_eq!(id.value(), 42);
        assert_eq!(id, FrameId::new(42));
    }

    // ===== FrameInfo 字段测试 =====

    #[test]
    fn test_frame_info_fields() {
        let pool = create_test_pool();
        let info = pool.get_frame_info(FrameId::new(5)).unwrap();
        assert_eq!(info.id(), FrameId::new(5));
        assert_eq!(info.size(), TEST_FRAME_SIZE);
        assert_eq!(info.state(), FrameState::Free);
        assert_eq!(info.domain_id(), 0);
        assert_eq!(info.generation(), 0);
        assert_eq!(info.physical_addr(), 5 * TEST_FRAME_SIZE as u64);
        assert_eq!(info.virtual_addr(), 5 * TEST_FRAME_SIZE as u64);
    }

    // ===== 零堆分配验证(热路径测试) =====

    #[test]
    fn test_allocate_release_no_panic() {
        let mut pool = create_test_pool();
        for _ in 0..1000 {
            let token = pool.allocate(0).unwrap();
            assert_eq!(token.domain_id(), 0);
            pool.release(token).unwrap();
        }
        assert_eq!(pool.allocated_count(), 0);
        assert_eq!(pool.free_count(), TEST_CAPACITY);
        assert!(pool.verify_conservation().is_ok());
    }

    // ===== recover_from_quarantine 代际推进(防 ABA 回归测试) =====

    #[test]
    fn test_recover_from_quarantine_advances_generation() {
        let mut pool = FramePool::new("aba_recover", 1, TEST_FRAME_SIZE);

        // 分配并隔离,记录隔离后的帧代际
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        pool.quarantine(token, "test").unwrap();
        let gen_quarantined = pool.get_frame_info(frame_id).unwrap().generation();

        // 回收必须推进代际,与 release/quarantine 行为一致
        pool.recover_from_quarantine(frame_id).unwrap();
        let gen_recovered = pool.get_frame_info(frame_id).unwrap().generation();
        assert_ne!(gen_quarantined, gen_recovered);
    }

    #[test]
    fn test_recover_from_quarantine_stale_handle_rejected() {
        let mut pool = FramePool::new("aba_recover2", 1, TEST_FRAME_SIZE);

        // 隔离 → 读出隔离态代际(回收前)→ 回收 → 重新分配
        let token = pool.allocate(0).unwrap();
        let frame_id = token.frame_id();
        let gen_v1 = token.generation();
        pool.quarantine(token, "test").unwrap();
        let gen_quarantined = pool.get_frame_info(frame_id).unwrap().generation();
        pool.recover_from_quarantine(frame_id).unwrap();
        let token2 = pool.allocate(0).unwrap();
        let gen_v2 = token2.generation();
        let _ = token2;

        // 代际经历 隔离→回收 两次推进,三个采样点互不相同
        assert_ne!(gen_v1, gen_quarantined);
        assert_ne!(gen_quarantined, gen_v2);
        assert_ne!(gen_v1, gen_v2);

        // 旧代际句柄(首次分配代际与隔离态代际)必须全部失效
        assert!(pool.release_by_id(frame_id, gen_v1).is_err());
        assert!(pool.quarantine_by_id(frame_id, gen_v1, "stale").is_err());
        assert!(pool.quarantine_by_id(frame_id, gen_quarantined, "stale").is_err());

        // 新代际句柄正常工作
        pool.release_by_id(frame_id, gen_v2).unwrap();
        assert!(pool.verify_conservation().is_ok());
    }

    // ===== FramePool::new 非法参数回退(行为保持 + 不 panic) =====

    #[test]
    fn test_new_invalid_params_fallback_no_panic() {
        // capacity == 0 / frame_size == 0:回退 1x1,不 panic,且功能可用
        let mut pool = FramePool::new("fallback_cap", 0, TEST_FRAME_SIZE);
        assert_eq!(pool.capacity(), 1);
        assert_eq!(pool.frame_size(), 1);
        let token = pool.allocate(0).unwrap();
        pool.release(token).unwrap();

        let pool = FramePool::new("fallback_size", TEST_CAPACITY, 0);
        assert_eq!(pool.capacity(), 1);
        assert_eq!(pool.frame_size(), 1);

        // try_new 显式路径保持报错
        assert!(FramePool::try_new("t", 0, 1).is_err());
        assert!(FramePool::try_new("t", 1, 0).is_err());
    }
}