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
//! 分层资源账本模块
//!
//! 实现根账本 → 域账本 → 队列账本 → 连接账本的四级分层结构。
//! 每层都有硬上限,子账本总配额不超过父账本。
//!
//! 设计原则:
//! - 单一所有者:账本树由一个 Supervisor 独占拥有,无 Arc/Rc 引用计数
//! - 无锁设计:所有操作为 &mut self,Rust 类型系统保证并发安全
//! - 类型化令牌:每种资源类型独立跟踪,编译期安全
//! - 检查算术:所有加减操作使用 checked_*,防止溢出

use std::collections::BTreeMap;

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

/// 资源账本类型层级
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LedgerType {
    /// 根账本(全局唯一)
    Root,
    /// 域账本(每 Worker 一个)
    Domain,
    /// 队列账本(每队列一个)
    Queue,
    /// 连接账本(每连接一个)
    Connection,
}

impl LedgerType {
    /// 获取层级深度(根=0,连接=3)
    pub fn depth(&self) -> u8 {
        match self {
            LedgerType::Root => 0,
            LedgerType::Domain => 1,
            LedgerType::Queue => 2,
            LedgerType::Connection => 3,
        }
    }
}

/// 资源类型(令牌化)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ResourceType {
    /// 内存资源(字节)
    Memory,
    /// Frame 资源(帧数量)
    Frames,
    /// 连接资源(活动连接数)
    Connections,
}

impl ResourceType {
    /// 获取资源类型名称
    pub fn name(&self) -> &'static str {
        match self {
            ResourceType::Memory => "memory",
            ResourceType::Frames => "frames",
            ResourceType::Connections => "connections",
        }
    }
}

/// 账本令牌数据
#[derive(Debug, Clone, Default)]
pub struct LedgerQuota {
    /// 内存配额(字节)
    pub memory_bytes: u64,
    /// Frame 配额
    pub frame_count: u64,
    /// 连接配额
    pub connection_count: u64,
}

impl LedgerQuota {
    /// 创建零配额
    #[inline]
    pub const fn zero() -> Self {
        Self {
            memory_bytes: 0,
            frame_count: 0,
            connection_count: 0,
        }
    }

    /// 创建无限配额(仅用于根账本配置边界)
    #[inline]
    pub const fn unlimited() -> Self {
        Self {
            memory_bytes: u64::MAX,
            frame_count: u64::MAX,
            connection_count: u64::MAX,
        }
    }

    /// 逐项检查子配额是否可以被父账本容纳
    #[inline]
    pub fn can_allocate(&self, child: &LedgerQuota) -> CoreResult<()> {
        if child.memory_bytes > self.memory_bytes {
            return Err(CoreError::quota_exceeded(
                "memory",
                self.memory_bytes,
                child.memory_bytes,
            ));
        }
        if child.frame_count > self.frame_count {
            return Err(CoreError::quota_exceeded(
                "frames",
                self.frame_count,
                child.frame_count,
            ));
        }
        if child.connection_count > self.connection_count {
            return Err(CoreError::quota_exceeded(
                "connections",
                self.connection_count,
                child.connection_count,
            ));
        }
        Ok(())
    }

    /// 消耗指定类型的配额(checked arithmetic)
    #[inline]
    pub fn consume(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
        let field = match resource {
            ResourceType::Memory => &mut self.memory_bytes,
            ResourceType::Frames => &mut self.frame_count,
            ResourceType::Connections => &mut self.connection_count,
        };
        *field = field
            .checked_sub(amount)
            .ok_or_else(|| CoreError::arithmetic_overflow("sub", *field, amount))?;
        Ok(())
    }

    /// 归还指定类型的配额(checked arithmetic)
    #[inline]
    pub fn restore(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
        let field = match resource {
            ResourceType::Memory => &mut self.memory_bytes,
            ResourceType::Frames => &mut self.frame_count,
            ResourceType::Connections => &mut self.connection_count,
        };
        *field = field
            .checked_add(amount)
            .ok_or_else(|| CoreError::arithmetic_overflow("add", *field, amount))?;
        Ok(())
    }

    /// 获取指定类型的值
    #[inline]
    pub fn get(&self, resource: ResourceType) -> u64 {
        match resource {
            ResourceType::Memory => self.memory_bytes,
            ResourceType::Frames => self.frame_count,
            ResourceType::Connections => self.connection_count,
        }
    }

    /// 计算剩余配额 = total - used(饱和减法)
    pub fn remaining(&self, used: &LedgerQuota) -> LedgerQuota {
        LedgerQuota {
            memory_bytes: self.memory_bytes.saturating_sub(used.memory_bytes),
            frame_count: self.frame_count.saturating_sub(used.frame_count),
            connection_count: self.connection_count.saturating_sub(used.connection_count),
        }
    }
}

/// 层级资源账本
///
/// # 设计
/// - 单所有者:整个账本树由一个 Supervisor 独占拥有
/// - 无子账本用 Arc/Rc,所有子账本为 owned 存储
/// - 父账本只通过层级路径索引子账本,不保留反向引用
/// - 所有操作为 `&mut self`,Rust 类型系统自然保证线程安全
#[derive(Debug)]
pub struct ResourceLedger {
    /// 账本名称(唯一 ID)
    name: String,
    /// 账本类型
    ledger_type: LedgerType,
    /// 总配额
    total: LedgerQuota,
    /// 已使用配额(子树汇总:本账本自身直接用量 + 所有子账本 roll-up 用量)
    used: LedgerQuota,
    /// 本账本自身直接分配量(**不含**子账本 roll-up)
    ///
    /// 与 `used` 双轨记账,解决「used 同时承担直接用量与子树汇总两语义」导致的
    /// 双重计数问题:`allocate` 分配校验用 `used_direct + allocated_to_children <= total`,
    /// 而 `used` 保持子树汇总语义(供 `used()`/`remaining()` 返回)。
    used_direct: LedgerQuota,
    /// 已分配给子账本的总配额(用于校验子配额之和不超过父配额)
    allocated_to_children: LedgerQuota,
    /// 子账本集合(按名称有序,使用 BTreeMap 保证迭代确定性)
    children: BTreeMap<String, ResourceLedger>,
}

impl ResourceLedger {
    /// 创建新的资源账本(Root 级)
    pub fn new(name: impl Into<String>, ledger_type: LedgerType, total: LedgerQuota) -> Self {
        Self {
            name: name.into(),
            ledger_type,
            total,
            used: LedgerQuota::zero(),
            used_direct: LedgerQuota::zero(),
            allocated_to_children: LedgerQuota::zero(),
            children: BTreeMap::new(),
        }
    }

    /// 创建根账本
    pub fn root(total: LedgerQuota) -> Self {
        Self::new("root", LedgerType::Root, total)
    }

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

    /// 获取账本类型
    #[inline]
    pub fn ledger_type(&self) -> LedgerType {
        self.ledger_type
    }

    /// 获取层级深度
    #[inline]
    pub fn depth(&self) -> u8 {
        self.ledger_type.depth()
    }

    /// 获取总配额
    #[inline]
    pub fn total(&self) -> &LedgerQuota {
        &self.total
    }

    /// 获取已使用配额
    #[inline]
    pub fn used(&self) -> &LedgerQuota {
        &self.used
    }

    /// 获取已分配给子账本的配额
    #[inline]
    pub fn allocated_to_children(&self) -> &LedgerQuota {
        &self.allocated_to_children
    }

    /// 获取子账本数量
    #[inline]
    pub fn child_count(&self) -> usize {
        self.children.len()
    }

    /// 迭代子账本名称
    pub fn child_names(&self) -> impl Iterator<Item = &str> {
        self.children.keys().map(|s| s.as_str())
    }

    /// 查找子账本(不可变)
    pub fn get_child(&self, name: &str) -> Option<&ResourceLedger> {
        self.children.get(name)
    }

    /// 查找子账本(可变)
    pub fn get_child_mut(&mut self, name: &str) -> Option<&mut ResourceLedger> {
        self.children.get_mut(name)
    }

    /// 在当前账本下创建子账本
    ///
    /// 父账本校验(fail-closed,逐项资源):
    /// `allocated_to_children + child_quota <= total - used`
    ///
    /// 即「已承诺给现有子账本的配额 + 新子账本配额」不得超过父账本
    /// 扣除自身已用后的剩余配额,防止多子账本配额之和超卖父账本。
    ///
    /// # 失败
    /// - 配额不足(含兄弟账本已占用部分)→ CoreError::QuotaExceeded
    /// - 子账本名称已存在 → CoreError::ResourceAlreadyExists
    /// - 子账本全零配额 → CoreError::InvalidConfig(静默失败防护)
    pub fn create_child(
        &mut self,
        name: impl Into<String>,
        ledger_type: LedgerType,
        quota: LedgerQuota,
    ) -> CoreResult<&mut ResourceLedger> {
        let name: String = name.into();

        // 零配额防护:三项全零的子账本无任何可用资源,必然导致后续 allocate 静默失败
        if quota.memory_bytes == 0
            && quota.frame_count == 0
            && quota.connection_count == 0
        {
            return Err(CoreError::invalid_config(
                "LedgerQuota",
                "all quota fields are zero; a child ledger with zero total quota can never allocate any resource",
            ));
        }

        if self.children.contains_key(&name) {
            return Err(CoreError::resource_already_exists(
                0,
                "ledger",
            ));
        }

        // 超卖防护(checked 算术,逐项资源):
        // allocated_to_children + child_quota <= total - used
        for resource in [ResourceType::Memory, ResourceType::Frames, ResourceType::Connections] {
            let committed = self
                .allocated_to_children
                .get(resource)
                .checked_add(quota.get(resource))
                .ok_or_else(|| {
                    CoreError::arithmetic_overflow(
                        "add",
                        self.allocated_to_children.get(resource),
                        quota.get(resource),
                    )
                })?;
            // used <= total 由 allocate 的校验保证;checked_sub 兜底不变量损坏场景
            let available = self
                .total
                .get(resource)
                .checked_sub(self.used.get(resource))
                .ok_or_else(|| {
                    CoreError::arithmetic_overflow(
                        "sub",
                        self.total.get(resource),
                        self.used.get(resource),
                    )
                })?;
            if committed > available {
                return Err(CoreError::quota_exceeded(
                    resource.name(),
                    available,
                    committed,
                ));
            }
        }

        // 累加子账本配额;溢出错误必须上报真实操作数(allocated_to_children
        // 当前值),禁止硬编码 u64::MAX 谎报现场,便于事后审计定位
        self.allocated_to_children.memory_bytes = self
            .allocated_to_children
            .memory_bytes
            .checked_add(quota.memory_bytes)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "add",
                    self.allocated_to_children.memory_bytes,
                    quota.memory_bytes,
                )
            })?;
        self.allocated_to_children.frame_count = self
            .allocated_to_children
            .frame_count
            .checked_add(quota.frame_count)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "add",
                    self.allocated_to_children.frame_count,
                    quota.frame_count,
                )
            })?;
        self.allocated_to_children.connection_count = self
            .allocated_to_children
            .connection_count
            .checked_add(quota.connection_count)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "add",
                    self.allocated_to_children.connection_count,
                    quota.connection_count,
                )
            })?;

        let child = ResourceLedger::new(name.clone(), ledger_type, quota);
        self.children.insert(name.clone(), child);

        self.children.get_mut(&name).ok_or_else(|| CoreError::internal("child ledger not found after insertion"))
    }

    /// 注销子账本(回收其配额)
    ///
    /// 子账本的 `total` 配额会从父账本的 `allocated_to_children` 中扣除。
    /// 同时回滚子树曾向父账本 roll-up 的使用量(`used`):
    /// 子树被移除后其占用的资源视为全部释放,父账本不再为其记账。
    /// 回滚采用饱和语义——仅回收父账本实际记账的部分
    /// (子树未经 `allocate_in_child` roll-up 的使用本就不在父账本账上)。
    pub fn remove_child(&mut self, name: &str) -> CoreResult<()> {
        let child = self
            .children
            .remove(name)
            .ok_or_else(|| CoreError::resource_not_found(0, "ledger"))?;

        // 回滚子树 roll-up 到本账本的使用量(checked_sub 防 underflow:
        // 子树 roll-up 用量必然 ≤ 本账本记账,underflow 说明内部状态损坏,fail-closed 上报)
        // used_direct 不受影响:子账本不占父账本直接用量。
        self.used.memory_bytes = self
            .used
            .memory_bytes
            .checked_sub(child.used.memory_bytes)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "sub",
                    self.used.memory_bytes,
                    child.used.memory_bytes,
                )
            })?;
        self.used.frame_count = self
            .used
            .frame_count
            .checked_sub(child.used.frame_count)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "sub",
                    self.used.frame_count,
                    child.used.frame_count,
                )
            })?;
        self.used.connection_count = self
            .used
            .connection_count
            .checked_sub(child.used.connection_count)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "sub",
                    self.used.connection_count,
                    child.used.connection_count,
                )
            })?;

        // 回滚已分配给子账本的配额
        self.allocated_to_children.memory_bytes = self
            .allocated_to_children
            .memory_bytes
            .checked_sub(child.total.memory_bytes)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "sub",
                    self.allocated_to_children.memory_bytes,
                    child.total.memory_bytes,
                )
            })?;
        self.allocated_to_children.frame_count = self
            .allocated_to_children
            .frame_count
            .checked_sub(child.total.frame_count)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "sub",
                    self.allocated_to_children.frame_count,
                    child.total.frame_count,
                )
            })?;
        self.allocated_to_children.connection_count = self
            .allocated_to_children
            .connection_count
            .checked_sub(child.total.connection_count)
            .ok_or_else(|| {
                CoreError::arithmetic_overflow(
                    "sub",
                    self.allocated_to_children.connection_count,
                    child.total.connection_count,
                )
            })?;

        Ok(())
    }

    /// 在当前账本上分配资源(checked arithmetic)
    ///
    /// # 超卖防护
    /// 本账本自身的直接用量(`used_direct`)+ 已承诺给子账本的配额不得超过 `total`。
    /// 否则父账本可直接分配耗尽 `total`,与子账本承诺配额叠加造成
    /// "子账本配额 + 父自身用量 > total" 的分层配额超卖。
    ///
    /// # 双重计数修复(CORE-013)
    /// 传统实现用 `used`(子树汇总)参与分配校验,会把子账本实际 roll-up 用量
    /// 与 `allocated_to_children` 配额重复计算,导致子账本用量 < 其配额时父账本
    /// 合法分配被误拒。修复后校验仅依赖 `used_direct`(本账本自身直接用量),
    /// 与子账本已承诺配额做加法,不再叠加子账本实际用量。
    pub fn allocate(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
        let direct = self.used_direct.get(resource);
        let total = self.total.get(resource);
        let new_direct = direct
            .checked_add(amount)
            .ok_or_else(|| CoreError::arithmetic_overflow("add", direct, amount))?;

        // 已承诺给子账本的配额需从父账本可分配预算中预留
        let committed = self.allocated_to_children.get(resource);
        let total_need = new_direct
            .checked_add(committed)
            .ok_or_else(|| CoreError::arithmetic_overflow("add", new_direct, committed))?;
        if total_need > total {
            return Err(CoreError::quota_exceeded(resource.name(), total, total_need));
        }

        // 双轨记账:直接用量计入 used_direct,同时计入 used(子树汇总)
        self.used_direct.restore(resource, amount)?;
        self.used.restore(resource, amount)?;
        Ok(())
    }

    /// 祖先 roll-up 专用分配(**不**检查 `allocated_to_children`)。
    ///
    /// 子账本的实际用量已由其自身配额约束(该配额已计入父账本
    /// `allocated_to_children`),故 roll-up 仅需保证不超过 `total`。
    /// 直接分配一律走 [`allocate`](Self::allocate)(含超卖防护)。
    fn allocate_rollup(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
        let current = self.used.get(resource);
        let total = self.total.get(resource);
        let new_used = current
            .checked_add(amount)
            .ok_or_else(|| CoreError::arithmetic_overflow("add", current, amount))?;
        if new_used > total {
            return Err(CoreError::quota_exceeded(resource.name(), total, new_used));
        }
        self.used.restore(resource, amount)?;
        Ok(())
    }

    /// 在当前账本上释放资源(直接释放,与 [`allocate`](Self::allocate) 互逆)
    ///
    /// 双轨回滚:`used_direct`(本账本直接用量)与 `used`(子树汇总)同时扣减。
    /// 祖先 roll-up 回滚请使用 [`release_rollup`](Self::release_rollup),勿在本方法误用。
    pub fn release(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
        self.used_direct.consume(resource, amount)?;
        self.used.consume(resource, amount)?;
        Ok(())
    }

    /// 祖先 roll-up 回滚专用释放(**不**更新 `used_direct`)。
    ///
    /// 与 [`allocate_rollup`](Self::allocate_rollup) 互逆:roll-up 只增加 `used`
    /// (子树汇总),因此回滚只扣减 `used`,避免误扣未发生的父账本直接用量。
    fn release_rollup(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
        self.used.consume(resource, amount)?;
        Ok(())
    }

    /// 在指定子账本(按名称路径逐层下钻)上分配资源,并沿路径向所有祖先 roll-up
    ///
    /// 分层配额语义:子孙的实际使用同时消耗路径上每一层祖先的配额,
    /// 因此祖先账本的 `used` 始终反映其整棵子树的使用量。
    ///
    /// # 原子性
    /// 路径上任一层配额不足或路径不存在时,已完成的祖先 roll-up 会逐层回滚,
    /// 调用前后账本树保持一致(fail-closed,不产生部分提交)。
    ///
    /// # Arguments
    /// * `child_path` - 子账本名称路径(空路径等价于 `self.allocate`)
    /// * `resource` - 资源类型
    /// * `amount` - 分配数量
    ///
    /// # 失败
    /// - 路径不存在 → CoreError::ResourceNotFound
    /// - 任一层配额不足 → CoreError::QuotaExceeded
    pub fn allocate_in_child(
        &mut self,
        child_path: &[&str],
        resource: ResourceType,
        amount: u64,
    ) -> CoreResult<()> {
        match child_path.split_first() {
            None => self.allocate(resource, amount),
            Some((head, rest)) => {
                // 子账本存在性预检(fail-closed:避免祖先 roll-up 后才发现路径不存在)
                if !self.children.contains_key(*head) {
                    return Err(CoreError::resource_not_found(0, "ledger"));
                }
                // 祖先层先 roll-up:祖先配额不足直接失败,子树零变更。
                // 用 allocate_rollup(不检查 allocated_to_children),
                // 避免与子账本已承诺配额重复计数导致合法分配被误拒。
                self.allocate_rollup(resource, amount)?;
                let child = self
                    .children
                    .get_mut(*head)
                    .ok_or_else(|| CoreError::internal("child ledger not found after existence check"))?;
                match child.allocate_in_child(rest, resource, amount) {
                    Ok(()) => Ok(()),
                    Err(e) => {
                        // 子树分配失败 → 回滚祖先层 roll-up,保持账本树守恒
                        // (不变量:刚加上的 amount 必然能减回;回滚失败说明内部状态损坏,优先上报)
                        // 祖先层 roll-up 只增加过 used,故用 release_rollup 只扣 used,
                        // 避免误扣 used_direct
                        self.release_rollup(resource, amount)?;
                        Err(e)
                    }
                }
            }
        }
    }

    /// 在指定子账本(按名称路径逐层下钻)上释放资源,并沿路径回滚所有祖先的 roll-up
    ///
    /// 与 [`ResourceLedger::allocate_in_child`] 互逆:释放时逐层扣减路径上
    /// 每个账本的 `used`,保证祖先账本记账与子树实际使用一致。
    ///
    /// # 原子性
    /// 路径不存在或任一层 `used` 不足时,已回滚的祖先层会逐层恢复,
    /// 调用前后账本树保持一致(fail-closed,不产生部分提交)。
    ///
    /// # 失败
    /// - 路径不存在 → CoreError::ResourceNotFound
    /// - 任一层 `used` 不足(释放量超过已分配量)→ CoreError::ArithmeticOverflow
    pub fn release_in_child(
        &mut self,
        child_path: &[&str],
        resource: ResourceType,
        amount: u64,
    ) -> CoreResult<()> {
        match child_path.split_first() {
            None => self.release(resource, amount),
            Some((head, rest)) => {
                // 子账本存在性预检(fail-closed)
                if !self.children.contains_key(*head) {
                    return Err(CoreError::resource_not_found(0, "ledger"));
                }
                // 祖先层先回滚(used 不足直接失败,子树零变更)
                // 祖先层用量由 roll-up 计入 `used`,不占 `used_direct`,故用 release_rollup
                self.release_rollup(resource, amount)?;
                let child = self
                    .children
                    .get_mut(*head)
                    .ok_or_else(|| CoreError::internal("child ledger not found after existence check"))?;
                match child.release_in_child(rest, resource, amount) {
                    Ok(()) => Ok(()),
                    Err(e) => {
                        // 子树释放失败 → 恢复祖先层记账,保持账本树守恒
                        // (不变量:刚减去的 amount 加回后等于原值,必然不溢出)
                        self.used.restore(resource, amount)?;
                        Err(e)
                    }
                }
            }
        }
    }

    /// 检查是否可以分配指定资源
    ///
    /// 与 [`allocate`](Self::allocate) 的校验一致:`used_direct + amount + allocated_to_children <= total`。
    /// 使用 checked_add 判断,加法溢出(不可容纳于 u64)时返回 false(fail-closed,CORE-012)。
    #[inline]
    pub fn can_allocate(&self, resource: ResourceType, amount: u64) -> bool {
        let direct = self.used_direct.get(resource);
        let total = self.total.get(resource);
        let committed = self.allocated_to_children.get(resource);
        match direct
            .checked_add(amount)
            .and_then(|v| v.checked_add(committed))
        {
            Some(need) => need <= total,
            // 溢出 → 必然超限,fail-closed 返回 false
            None => false,
        }
    }

    /// 计算剩余配额
    pub fn remaining(&self) -> LedgerQuota {
        self.total.remaining(&self.used)
    }

    /// 递归深度(用于调试)
    pub fn max_depth(&self) -> u8 {
        let mut max = self.depth();
        for child in self.children.values() {
            max = max.max(child.max_depth());
        }
        max
    }

    /// 账本树节点总数(用于完整性检查)
    pub fn node_count(&self) -> u64 {
        // 饱和累加:BTreeMap 子节点数为 usize,四层分层结构下
        // u64 求和实际不可达溢出;saturating_add 仅为满足
        // 「生产路径禁止裸算术」的兜底防御
        self.children
            .values()
            .map(ResourceLedger::node_count)
            .fold(1u64, u64::saturating_add)
    }
}

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

    fn make_quota(mem: u64, frames: u64, conns: u64) -> LedgerQuota {
        LedgerQuota {
            memory_bytes: mem,
            frame_count: frames,
            connection_count: conns,
        }
    }

    #[test]
    fn test_root_ledger_create() {
        let root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
        assert_eq!(root.name(), "root");
        assert_eq!(root.ledger_type(), LedgerType::Root);
        assert_eq!(root.depth(), 0);
        assert_eq!(root.total().memory_bytes, 1 << 30);
        assert_eq!(root.used().memory_bytes, 0);
        assert_eq!(root.child_count(), 0);
        assert_eq!(root.node_count(), 1);
    }

    #[test]
    fn test_create_domain_child() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));

        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
            .unwrap();

        assert_eq!(root.child_count(), 1);
        assert!(root.get_child("domain_0").is_some());

        let domain = root.get_child("domain_0").unwrap();
        assert_eq!(domain.ledger_type(), LedgerType::Domain);
        assert_eq!(domain.depth(), 1);
        assert_eq!(domain.total().frame_count, 10_000);
        assert_eq!(root.node_count(), 2);
    }

    #[test]
    fn test_create_child_quota_exceeded() {
        let mut root = ResourceLedger::root(make_quota(1024, 100, 10));

        // 尝试创建超出父账本配额的子账本
        let result = root.create_child("big", LedgerType::Domain, make_quota(2048, 0, 0));
        assert!(result.is_err());

        // 父账本不受影响
        assert_eq!(root.child_count(), 0);
        assert_eq!(root.total().memory_bytes, 1024);
    }

    #[test]
    fn test_duplicate_child_name() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));

        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
            .unwrap();

        let result = root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000));
        assert!(result.is_err());
    }

    #[test]
    fn test_allocate_and_release() {
        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(4096, 100, 10));

        // 分配内存
        ledger.allocate(ResourceType::Memory, 1024).unwrap();
        assert_eq!(ledger.used().memory_bytes, 1024);

        // 归还
        ledger.release(ResourceType::Memory, 512).unwrap();
        assert_eq!(ledger.used().memory_bytes, 512);

        // 剩余配额
        let remaining = ledger.remaining();
        assert_eq!(remaining.memory_bytes, 4096 - 512);
    }

    #[test]
    fn test_allocate_quota_exceeded() {
        let mut ledger = ResourceLedger::new("small", LedgerType::Queue, make_quota(1024, 0, 0));

        ledger.allocate(ResourceType::Memory, 512).unwrap();

        let result = ledger.allocate(ResourceType::Memory, 1024);
        assert!(result.is_err());
    }

    #[test]
    fn test_allocate_overflow() {
        let mut ledger = ResourceLedger::new("max", LedgerType::Queue, make_quota(u64::MAX, 0, 0));

        ledger.allocate(ResourceType::Memory, u64::MAX).unwrap();

        let result = ledger.allocate(ResourceType::Memory, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_frames_and_connections() {
        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 1000, 50));

        ledger.allocate(ResourceType::Frames, 500).unwrap();
        assert_eq!(ledger.used().frame_count, 500);

        ledger.allocate(ResourceType::Connections, 10).unwrap();
        assert_eq!(ledger.used().connection_count, 10);

        ledger.release(ResourceType::Frames, 200).unwrap();
        assert_eq!(ledger.used().frame_count, 300);
    }

    #[test]
    fn test_can_allocate() {
        let ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1 << 30, 0, 0));

        assert!(ledger.can_allocate(ResourceType::Memory, 1024));
        assert!(ledger.can_allocate(ResourceType::Memory, 1 << 30));
        assert!(!ledger.can_allocate(ResourceType::Memory, (1 << 30) + 1));
    }

    #[test]
    fn test_nested_hierarchy() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));

        //        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 24, 50_000, 5_000))
            .unwrap();

        // 在域下创建队列
        root.get_child_mut("domain_0").unwrap()
            .create_child("queue_0", LedgerType::Queue, make_quota(1 << 20, 10_000, 1_000))
            .unwrap();

        // 在队列下创建连接
        root.get_child_mut("domain_0").unwrap()
            .get_child_mut("queue_0").unwrap()
            .create_child("conn_0", LedgerType::Connection, make_quota(1 << 16, 100, 10))
            .unwrap();

        // 验证层级深度
        let conn = root.get_child("domain_0").unwrap()
            .get_child("queue_0").unwrap()
            .get_child("conn_0").unwrap();
        assert_eq!(conn.depth(), 3);
        assert_eq!(conn.ledger_type(), LedgerType::Connection);
        assert_eq!(root.max_depth(), 3);
        assert_eq!(root.node_count(), 4);

        // 在连接上分配资源(需要可变访问)
        root.get_child_mut("domain_0").unwrap()
            .get_child_mut("queue_0").unwrap()
            .get_child_mut("conn_0").unwrap()
            .allocate(ResourceType::Memory, 1024)
            .unwrap();

        assert_eq!(
            root.get_child("domain_0").unwrap()
                .get_child("queue_0").unwrap()
                .get_child("conn_0").unwrap()
                .used()
                .memory_bytes,
            1024
        );
    }

    #[test]
    fn test_remove_child_reclaims_quota() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));

        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
            .unwrap();

        // 在域下创建队列并分配资源(域自身的 used 被增加)
        root.get_child_mut("domain_0").unwrap()
            .create_child("queue_0", LedgerType::Queue, make_quota(1 << 16, 1000, 100))
            .unwrap();

        root.get_child_mut("domain_0").unwrap()
            .get_child_mut("queue_0").unwrap()
            .allocate(ResourceType::Memory, 4096)
            .unwrap();

        // 验证子账本的 used 正确追踪
        let queue_used = root.get_child("domain_0").unwrap()
            .get_child("queue_0").unwrap()
            .used().memory_bytes;
        assert_eq!(queue_used, 4096);

        // 父账本的 used = 所有子孙的 used 之和,在 remove_child 时统一回收
        // 回收域的 total 配额
        root.remove_child("domain_0").unwrap();

        assert_eq!(root.child_count(), 0);
        // allocated_to_children 已清零(域的 total 已回收)
        assert_eq!(root.allocated_to_children().memory_bytes, 0);
    }

    #[test]
    fn test_remove_nonexistent_child() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 0, 0));
        let result = root.remove_child("nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_list_child_names() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));

        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
            .unwrap();
        root.create_child("domain_1", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
            .unwrap();

        let names: Vec<&str> = root.child_names().collect();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"domain_0"));
        assert!(names.contains(&"domain_1"));
    }

    #[test]
    fn test_allocations_accounted_in_parent() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));

        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
            .unwrap();

        // 子账本消耗资源
        root.get_child_mut("domain_0").unwrap()
            .allocate(ResourceType::Memory, 8192)
            .unwrap();

        // 父账本看到子账本的使用
        assert_eq!(root.get_child("domain_0").unwrap().used().memory_bytes, 8192);

        // 但子账本自身的 used 也被正确跟踪
        let domain = root.get_child("domain_0").unwrap();
        assert!(domain.can_allocate(ResourceType::Memory, (1 << 20) - 8192));
        assert!(!domain.can_allocate(ResourceType::Memory, (1 << 20) - 8191));
    }

    // ===== LedgerQuota: zero()/unlimited()/can_allocate 测试 =====

    #[test]
    fn test_ledger_quota_zero() {
        let q = LedgerQuota::zero();
        assert_eq!(q.memory_bytes, 0);
        assert_eq!(q.frame_count, 0);
        assert_eq!(q.connection_count, 0);
    }

    #[test]
    fn test_ledger_quota_unlimited() {
        let q = LedgerQuota::unlimited();
        assert_eq!(q.memory_bytes, u64::MAX);
        assert_eq!(q.frame_count, u64::MAX);
        assert_eq!(q.connection_count, u64::MAX);
    }

    #[test]
    fn test_ledger_quota_can_allocate_memory() {
        let parent = make_quota(1024, 0, 0);
        let child_ok = make_quota(512, 0, 0);
        let child_exceed = make_quota(2048, 0, 0);

        assert!(parent.can_allocate(&child_ok).is_ok());
        assert!(parent.can_allocate(&child_exceed).is_err());
    }

    #[test]
    fn test_ledger_quota_can_allocate_frames() {
        let parent = make_quota(0, 100, 0);
        let child_ok = make_quota(0, 50, 0);
        let child_exceed = make_quota(0, 200, 0);

        assert!(parent.can_allocate(&child_ok).is_ok());
        assert!(parent.can_allocate(&child_exceed).is_err());
    }

    #[test]
    fn test_ledger_quota_can_allocate_connections() {
        let parent = make_quota(0, 0, 10);
        let child_ok = make_quota(0, 0, 5);
        let child_exceed = make_quota(0, 0, 20);

        assert!(parent.can_allocate(&child_ok).is_ok());
        assert!(parent.can_allocate(&child_exceed).is_err());
    }

    #[test]
    fn test_ledger_quota_can_allocate_exact() {
        let parent = make_quota(100, 200, 300);
        let child_exact = make_quota(100, 200, 300);
        assert!(parent.can_allocate(&child_exact).is_ok());
    }

    #[test]
    fn test_ledger_quota_consume_and_restore() {
        let mut q = make_quota(1000, 100, 10);

        q.consume(ResourceType::Memory, 500).unwrap();
        assert_eq!(q.memory_bytes, 500);

        q.restore(ResourceType::Memory, 300).unwrap();
        assert_eq!(q.memory_bytes, 800);
    }

    #[test]
    fn test_ledger_quota_consume_underflow() {
        let mut q = make_quota(100, 0, 0);
        let result = q.consume(ResourceType::Memory, 200);
        assert!(result.is_err());
    }

    #[test]
    fn test_ledger_quota_restore_overflow() {
        let mut q = make_quota(u64::MAX, 0, 0);
        let result = q.restore(ResourceType::Memory, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_ledger_quota_get() {
        let q = make_quota(10, 20, 30);
        assert_eq!(q.get(ResourceType::Memory), 10);
        assert_eq!(q.get(ResourceType::Frames), 20);
        assert_eq!(q.get(ResourceType::Connections), 30);
    }

    #[test]
    fn test_ledger_quota_remaining() {
        let total = make_quota(1000, 100, 50);
        let used = make_quota(400, 30, 10);
        let remaining = total.remaining(&used);
        assert_eq!(remaining.memory_bytes, 600);
        assert_eq!(remaining.frame_count, 70);
        assert_eq!(remaining.connection_count, 40);
    }

    #[test]
    fn test_ledger_quota_remaining_saturating() {
        let total = make_quota(100, 0, 0);
        let used = make_quota(200, 0, 0);
        let remaining = total.remaining(&used);
        assert_eq!(remaining.memory_bytes, 0);
    }

    // ===== LedgerType: depth() 所有变体测试 =====

    #[test]
    fn test_ledger_type_depth() {
        assert_eq!(LedgerType::Root.depth(), 0);
        assert_eq!(LedgerType::Domain.depth(), 1);
        assert_eq!(LedgerType::Queue.depth(), 2);
        assert_eq!(LedgerType::Connection.depth(), 3);
    }

    #[test]
    fn test_ledger_type_equality() {
        assert_eq!(LedgerType::Root, LedgerType::Root);
        assert_ne!(LedgerType::Root, LedgerType::Domain);
    }

    #[test]
    fn test_ledger_type_debug() {
        assert_eq!(format!("{:?}", LedgerType::Root), "Root");
        assert_eq!(format!("{:?}", LedgerType::Connection), "Connection");
    }

    // ===== ResourceType: name() 所有变体测试 =====

    #[test]
    fn test_resource_type_name() {
        assert_eq!(ResourceType::Memory.name(), "memory");
        assert_eq!(ResourceType::Frames.name(), "frames");
        assert_eq!(ResourceType::Connections.name(), "connections");
    }

    #[test]
    fn test_resource_type_equality() {
        assert_eq!(ResourceType::Memory, ResourceType::Memory);
        assert_ne!(ResourceType::Memory, ResourceType::Frames);
    }

    #[test]
    fn test_resource_type_debug() {
        assert_eq!(format!("{:?}", ResourceType::Memory), "Memory");
        assert_eq!(format!("{:?}", ResourceType::Frames), "Frames");
    }

    // ===== ResourceLedger: 多层嵌套配额守恒检查 =====

    #[test]
    fn test_multiple_children_quota_sum() {
        let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));

        root.create_child("d0", LedgerType::Domain, make_quota(3000, 300, 30)).unwrap();
        root.create_child("d1", LedgerType::Domain, make_quota(2000, 200, 20)).unwrap();
        root.create_child("d2", LedgerType::Domain, make_quota(5000, 500, 50)).unwrap();

        let allocated = root.allocated_to_children();
        assert_eq!(allocated.memory_bytes, 10000);
        assert_eq!(allocated.frame_count, 1000);
        assert_eq!(allocated.connection_count, 100);
    }

    #[test]
    fn test_nested_three_level_quota_conservation() {
        let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));

        root.create_child("d0", LedgerType::Domain, make_quota(5000, 500, 50)).unwrap();

        root.get_child_mut("d0").unwrap()
            .create_child("q0", LedgerType::Queue, make_quota(2000, 200, 20)).unwrap();
        root.get_child_mut("d0").unwrap()
            .create_child("q1", LedgerType::Queue, make_quota(3000, 300, 30)).unwrap();

        let domain_allocated = root.get_child("d0").unwrap().allocated_to_children();
        assert_eq!(domain_allocated.memory_bytes, 5000);
        assert_eq!(domain_allocated.frame_count, 500);
        assert_eq!(domain_allocated.connection_count, 50);

        let root_allocated = root.allocated_to_children();
        assert_eq!(root_allocated.memory_bytes, 5000);
    }

    #[test]
    fn test_child_quota_exceeds_parent_total() {
        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));

        let result = root.create_child("big", LedgerType::Domain, make_quota(2000, 200, 20));
        assert!(result.is_err());

        assert_eq!(root.child_count(), 0);
        assert_eq!(root.allocated_to_children().memory_bytes, 0);
    }

    #[test]
    fn test_child_quota_exceeds_parent_used_remaining() {
        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));

        root.allocate(ResourceType::Memory, 600).unwrap();
        root.allocate(ResourceType::Frames, 60).unwrap();
        root.allocate(ResourceType::Connections, 6).unwrap();

        let result = root.create_child("d0", LedgerType::Domain, make_quota(500, 50, 5));
        assert!(result.is_err());

        assert_eq!(root.child_count(), 0);
    }

    // ===== release 导致 underflow 的 checked arithmetic =====

    #[test]
    fn test_release_underflow_memory() {
        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1000, 0, 0));
        ledger.allocate(ResourceType::Memory, 500).unwrap();
        ledger.release(ResourceType::Memory, 300).unwrap();
        assert_eq!(ledger.used().memory_bytes, 200);
    }

    #[test]
    fn test_release_underflow_frames() {
        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 100, 0));
        ledger.allocate(ResourceType::Frames, 50).unwrap();
        let result = ledger.release(ResourceType::Frames, 100);
        assert!(result.is_err());
    }

    #[test]
    fn test_release_underflow_connections() {
        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 0, 10));
        let result = ledger.release(ResourceType::Connections, 1);
        assert!(result.is_err());
    }

    // ===== allocated_to_children 的正确性校验 =====

    #[test]
    fn test_allocated_to_children_after_remove() {
        let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));

        root.create_child("d0", LedgerType::Domain, make_quota(3000, 300, 30)).unwrap();
        root.create_child("d1", LedgerType::Domain, make_quota(2000, 200, 20)).unwrap();

        assert_eq!(root.allocated_to_children().memory_bytes, 5000);
        assert_eq!(root.allocated_to_children().frame_count, 500);
        assert_eq!(root.allocated_to_children().connection_count, 50);

        root.remove_child("d0").unwrap();

        assert_eq!(root.allocated_to_children().memory_bytes, 2000);
        assert_eq!(root.allocated_to_children().frame_count, 200);
        assert_eq!(root.allocated_to_children().connection_count, 20);
    }

    #[test]
    fn test_allocated_to_children_zero_initially() {
        let root = ResourceLedger::root(make_quota(1000, 100, 10));
        assert_eq!(root.allocated_to_children().memory_bytes, 0);
        assert_eq!(root.allocated_to_children().frame_count, 0);
        assert_eq!(root.allocated_to_children().connection_count, 0);
    }

    // ===== LedgerQuota Default 实现 =====

    #[test]
    fn test_ledger_quota_default() {
        let q = LedgerQuota::default();
        assert_eq!(q.memory_bytes, 0);
        assert_eq!(q.frame_count, 0);
        assert_eq!(q.connection_count, 0);
    }

    // ===== ResourceLedger remaining =====

    #[test]
    fn test_ledger_remaining() {
        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1000, 100, 10));
        ledger.allocate(ResourceType::Memory, 400).unwrap();
        ledger.allocate(ResourceType::Frames, 30).unwrap();
        ledger.allocate(ResourceType::Connections, 5).unwrap();

        let remaining = ledger.remaining();
        assert_eq!(remaining.memory_bytes, 600);
        assert_eq!(remaining.frame_count, 70);
        assert_eq!(remaining.connection_count, 5);
    }

    // ===== 深层嵌套 4 级完整链路 =====

    #[test]
    fn test_four_level_hierarchy_allocated_to_children() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));

        root.create_child("d0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000)).unwrap();

        root.get_child_mut("d0").unwrap()
            .create_child("q0", LedgerType::Queue, make_quota(1 << 15, 1_000, 100)).unwrap();

        root.get_child_mut("d0").unwrap().get_child_mut("q0").unwrap()
            .create_child("c0", LedgerType::Connection, make_quota(1 << 10, 100, 10)).unwrap();

        assert_eq!(root.max_depth(), 3);
        assert_eq!(root.node_count(), 4);

        let conn = root.get_child("d0").unwrap().get_child("q0").unwrap().get_child("c0").unwrap();
        assert_eq!(conn.ledger_type(), LedgerType::Connection);
        assert_eq!(conn.depth(), 3);
    }

    // ===== create_child 超卖防护(allocated_to_children 计入校验) =====

    #[test]
    fn test_create_child_oversubscription_rejected() {
        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));

        // 第一个子账本占 600:通过
        root.create_child("c1", LedgerType::Domain, make_quota(600, 60, 6)).unwrap();
        // 第二个子账本再要 600:600 + 600 = 1200 > 1000,必须拒绝(旧实现会放过)
        let result = root.create_child("c2", LedgerType::Domain, make_quota(600, 0, 0));
        assert!(result.is_err());
        assert_eq!(root.child_count(), 1);

        // 400 恰好分完:600 + 400 = 1000 <= 1000,通过
        root.create_child("c2", LedgerType::Domain, make_quota(400, 40, 4)).unwrap();
        assert_eq!(root.child_count(), 2);
        assert_eq!(root.allocated_to_children().memory_bytes, 1000);

        // 配额已分完,任何非零子账本都必须拒绝
        assert!(root.create_child("c3", LedgerType::Domain, make_quota(1, 0, 0)).is_err());
    }

    #[test]
    fn test_create_child_accounts_parent_used() {
        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));

        // 父账本自身使用 400 后,子账本配额之和不得超过 600
        root.allocate(ResourceType::Memory, 400).unwrap();
        root.create_child("c1", LedgerType::Domain, make_quota(600, 0, 0)).unwrap();
        assert!(root.create_child("c2", LedgerType::Domain, make_quota(1, 0, 0)).is_err());
    }

    // ===== allocate_in_child / release_in_child 分层 roll-up =====

    #[test]
    fn test_allocate_in_child_rolls_up_to_ancestors() {
        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
        root.create_child("d0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000)).unwrap();
        root.get_child_mut("d0").unwrap()
            .create_child("q0", LedgerType::Queue, make_quota(1 << 15, 1_000, 100)).unwrap();

        // 在队列账本上分配 1024:路径上每层祖先都必须记账
        root.allocate_in_child(&["d0", "q0"], ResourceType::Memory, 1024).unwrap();

        assert_eq!(root.used().memory_bytes, 1024);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 1024);
        assert_eq!(
            root.get_child("d0").unwrap().get_child("q0").unwrap().used().memory_bytes,
            1024
        );

        // 释放时逐层回滚
        root.release_in_child(&["d0", "q0"], ResourceType::Memory, 1024).unwrap();
        assert_eq!(root.used().memory_bytes, 0);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
        assert_eq!(
            root.get_child("d0").unwrap().get_child("q0").unwrap().used().memory_bytes,
            0
        );
    }

    #[test]
    fn test_allocate_in_child_ancestor_quota_enforced() {
        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();

        // 超卖防护:父账本直接分配受子账本已承诺配额约束。
        // 直接用 600 + 已承诺 500 = 1100 > total 1000 → 拒绝
        assert!(root.allocate(ResourceType::Memory, 600).is_err());
        // 直接用 500 + 已承诺 500 = 1000 <= total → 允许
        root.allocate(ResourceType::Memory, 500).unwrap();

        // 子树分配:子账本自身配额 500 决定其上限;祖先 roll-up 在父 total 内成功
        root.allocate_in_child(&["d0"], ResourceType::Memory, 500).unwrap();
        assert_eq!(root.used().memory_bytes, 1000);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 500);

        // 超额分配:父 total 已占满(1000),子树再分配 100 → 祖先 roll-up 失败,原子回滚
        let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 100);
        assert!(result.is_err());
        assert_eq!(root.used().memory_bytes, 1000);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 500);
    }

    #[test]
    fn test_allocate_in_child_rollback_on_descendant_failure() {
        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();

        // 子账本配额只有 500,分配 600:子树失败,祖先 roll-up 必须回滚
        let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 600);
        assert!(result.is_err());
        assert_eq!(root.used().memory_bytes, 0);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
    }

    // ===== CORE-013 双重计数回归测试 =====

    #[test]
    fn test_allocate_not_double_counted_with_child_usage() {
        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();

        // 子账本实际使用 200(roll-up 到 root.used;root.used_direct 仍为 0)
        root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
        assert_eq!(root.used().memory_bytes, 200);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);

        // 修复前:used(200)+400+committed(500)=1100>1000 → 误拒(把子用量与配额重复计数)
        // 修复后:used_direct(0)+400+committed(500)=900<=1000 → 成功
        // 实际 root 自身 400 + d0 用 200 = 600 <= 1000,且 d0 配额余量 300
        root.allocate(ResourceType::Memory, 400).unwrap();

        assert_eq!(root.used().memory_bytes, 600);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);
        // 根账本剩余 = total - used = 1000 - 600 = 400
        assert_eq!(root.remaining().memory_bytes, 400);
    }

    #[test]
    fn test_allocate_in_child_rollback_does_not_touch_used_direct() {
        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();

        // 子账本分配失败(配额超限):祖先 roll-up 用 release_rollup 回滚,
        // 不得误扣父账本 used_direct
        root.allocate(ResourceType::Memory, 300).unwrap();
        let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 600);
        assert!(result.is_err());
        // 父账本 used 回到仅含自身直接用量 300(回滚未越界、未误扣)
        assert_eq!(root.used().memory_bytes, 300);
    }

    #[test]
    fn test_allocate_in_child_unknown_path() {
        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();

        // 路径不存在:任何一层都不得变更
        assert!(root.allocate_in_child(&["nope"], ResourceType::Memory, 100).is_err());
        assert!(root.allocate_in_child(&["d0", "nope"], ResourceType::Memory, 100).is_err());
        assert_eq!(root.used().memory_bytes, 0);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
    }

    #[test]
    fn test_release_in_child_restores_on_descendant_failure() {
        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();

        root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();

        // 子树已分配 200,释放 300:子树 used 不足,祖先已回滚的 300 必须恢复
        let result = root.release_in_child(&["d0"], ResourceType::Memory, 300);
        assert!(result.is_err());
        assert_eq!(root.used().memory_bytes, 200);
        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);

        // 正常释放路径不受影响
        root.release_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
        assert_eq!(root.used().memory_bytes, 0);
    }

    #[test]
    fn test_remove_child_reclaims_rolled_up_usage() {
        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
        root.create_child("d0", LedgerType::Domain, make_quota(500, 50, 5)).unwrap();

        // 子树通过 roll-up 使用 200:父账本记账 200
        root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
        assert_eq!(root.used().memory_bytes, 200);

        // 移除子账本:配额与 roll-up 使用量都必须回收,父账本不得泄漏记账
        root.remove_child("d0").unwrap();
        assert_eq!(root.used().memory_bytes, 0);
        assert_eq!(root.allocated_to_children().memory_bytes, 0);

        // 回收后配额可重新分配
        root.create_child("d1", LedgerType::Domain, make_quota(1000, 100, 10)).unwrap();
    }
}