Skip to main content

zenith_foundation/
ledger.rs

1//! 分层资源账本模块
2//!
3//! 实现根账本 → 域账本 → 队列账本 → 连接账本的四级分层结构。
4//! 每层都有硬上限,子账本总配额不超过父账本。
5//!
6//! 设计原则:
7//! - 单一所有者:账本树由一个 Supervisor 独占拥有,无 Arc/Rc 引用计数
8//! - 无锁设计:所有操作为 &mut self,Rust 类型系统保证并发安全
9//! - 类型化令牌:每种资源类型独立跟踪,编译期安全
10//! - 检查算术:所有加减操作使用 checked_*,防止溢出
11
12use std::collections::BTreeMap;
13
14use crate::error::{CoreError, CoreResult};
15
16/// 资源账本类型层级
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum LedgerType {
19    /// 根账本(全局唯一)
20    Root,
21    /// 域账本(每 Worker 一个)
22    Domain,
23    /// 队列账本(每队列一个)
24    Queue,
25    /// 连接账本(每连接一个)
26    Connection,
27}
28
29impl LedgerType {
30    /// 获取层级深度(根=0,连接=3)
31    pub fn depth(&self) -> u8 {
32        match self {
33            LedgerType::Root => 0,
34            LedgerType::Domain => 1,
35            LedgerType::Queue => 2,
36            LedgerType::Connection => 3,
37        }
38    }
39}
40
41/// 资源类型(令牌化)
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum ResourceType {
44    /// 内存资源(字节)
45    Memory,
46    /// Frame 资源(帧数量)
47    Frames,
48    /// 连接资源(活动连接数)
49    Connections,
50}
51
52impl ResourceType {
53    /// 获取资源类型名称
54    pub fn name(&self) -> &'static str {
55        match self {
56            ResourceType::Memory => "memory",
57            ResourceType::Frames => "frames",
58            ResourceType::Connections => "connections",
59        }
60    }
61}
62
63/// 账本令牌数据
64#[derive(Debug, Clone, Default)]
65pub struct LedgerQuota {
66    /// 内存配额(字节)
67    pub memory_bytes: u64,
68    /// Frame 配额
69    pub frame_count: u64,
70    /// 连接配额
71    pub connection_count: u64,
72}
73
74impl LedgerQuota {
75    /// 创建零配额
76    #[inline]
77    pub const fn zero() -> Self {
78        Self {
79            memory_bytes: 0,
80            frame_count: 0,
81            connection_count: 0,
82        }
83    }
84
85    /// 创建无限配额(仅用于根账本配置边界)
86    #[inline]
87    pub const fn unlimited() -> Self {
88        Self {
89            memory_bytes: u64::MAX,
90            frame_count: u64::MAX,
91            connection_count: u64::MAX,
92        }
93    }
94
95    /// 逐项检查子配额是否可以被父账本容纳
96    #[inline]
97    pub fn can_allocate(&self, child: &LedgerQuota) -> CoreResult<()> {
98        if child.memory_bytes > self.memory_bytes {
99            return Err(CoreError::quota_exceeded(
100                "memory",
101                self.memory_bytes,
102                child.memory_bytes,
103            ));
104        }
105        if child.frame_count > self.frame_count {
106            return Err(CoreError::quota_exceeded(
107                "frames",
108                self.frame_count,
109                child.frame_count,
110            ));
111        }
112        if child.connection_count > self.connection_count {
113            return Err(CoreError::quota_exceeded(
114                "connections",
115                self.connection_count,
116                child.connection_count,
117            ));
118        }
119        Ok(())
120    }
121
122    /// 消耗指定类型的配额(checked arithmetic)
123    #[inline]
124    pub fn consume(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
125        let field = match resource {
126            ResourceType::Memory => &mut self.memory_bytes,
127            ResourceType::Frames => &mut self.frame_count,
128            ResourceType::Connections => &mut self.connection_count,
129        };
130        *field = field
131            .checked_sub(amount)
132            .ok_or_else(|| CoreError::arithmetic_overflow("sub", *field, amount))?;
133        Ok(())
134    }
135
136    /// 归还指定类型的配额(checked arithmetic)
137    #[inline]
138    pub fn restore(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
139        let field = match resource {
140            ResourceType::Memory => &mut self.memory_bytes,
141            ResourceType::Frames => &mut self.frame_count,
142            ResourceType::Connections => &mut self.connection_count,
143        };
144        *field = field
145            .checked_add(amount)
146            .ok_or_else(|| CoreError::arithmetic_overflow("add", *field, amount))?;
147        Ok(())
148    }
149
150    /// 获取指定类型的值
151    #[inline]
152    pub fn get(&self, resource: ResourceType) -> u64 {
153        match resource {
154            ResourceType::Memory => self.memory_bytes,
155            ResourceType::Frames => self.frame_count,
156            ResourceType::Connections => self.connection_count,
157        }
158    }
159
160    /// 计算剩余配额 = total - used(饱和减法)
161    pub fn remaining(&self, used: &LedgerQuota) -> LedgerQuota {
162        LedgerQuota {
163            memory_bytes: self.memory_bytes.saturating_sub(used.memory_bytes),
164            frame_count: self.frame_count.saturating_sub(used.frame_count),
165            connection_count: self.connection_count.saturating_sub(used.connection_count),
166        }
167    }
168}
169
170/// 层级资源账本
171///
172/// # 设计
173/// - 单所有者:整个账本树由一个 Supervisor 独占拥有
174/// - 无子账本用 Arc/Rc,所有子账本为 owned 存储
175/// - 父账本只通过层级路径索引子账本,不保留反向引用
176/// - 所有操作为 `&mut self`,Rust 类型系统自然保证线程安全
177#[derive(Debug)]
178pub struct ResourceLedger {
179    /// 账本名称(唯一 ID)
180    name: String,
181    /// 账本类型
182    ledger_type: LedgerType,
183    /// 总配额
184    total: LedgerQuota,
185    /// 已使用配额(子树汇总:本账本自身直接用量 + 所有子账本 roll-up 用量)
186    used: LedgerQuota,
187    /// 本账本自身直接分配量(**不含**子账本 roll-up)
188    ///
189    /// 与 `used` 双轨记账,解决「used 同时承担直接用量与子树汇总两语义」导致的
190    /// 双重计数问题:`allocate` 分配校验用 `used_direct + allocated_to_children <= total`,
191    /// 而 `used` 保持子树汇总语义(供 `used()`/`remaining()` 返回)。
192    used_direct: LedgerQuota,
193    /// 已分配给子账本的总配额(用于校验子配额之和不超过父配额)
194    allocated_to_children: LedgerQuota,
195    /// 子账本集合(按名称有序,使用 BTreeMap 保证迭代确定性)
196    children: BTreeMap<String, ResourceLedger>,
197}
198
199impl ResourceLedger {
200    /// 创建新的资源账本(Root 级)
201    pub fn new(name: impl Into<String>, ledger_type: LedgerType, total: LedgerQuota) -> Self {
202        Self {
203            name: name.into(),
204            ledger_type,
205            total,
206            used: LedgerQuota::zero(),
207            used_direct: LedgerQuota::zero(),
208            allocated_to_children: LedgerQuota::zero(),
209            children: BTreeMap::new(),
210        }
211    }
212
213    /// 创建根账本
214    pub fn root(total: LedgerQuota) -> Self {
215        Self::new("root", LedgerType::Root, total)
216    }
217
218    /// 获取账本名称
219    #[inline]
220    pub fn name(&self) -> &str {
221        &self.name
222    }
223
224    /// 获取账本类型
225    #[inline]
226    pub fn ledger_type(&self) -> LedgerType {
227        self.ledger_type
228    }
229
230    /// 获取层级深度
231    #[inline]
232    pub fn depth(&self) -> u8 {
233        self.ledger_type.depth()
234    }
235
236    /// 获取总配额
237    #[inline]
238    pub fn total(&self) -> &LedgerQuota {
239        &self.total
240    }
241
242    /// 获取已使用配额
243    #[inline]
244    pub fn used(&self) -> &LedgerQuota {
245        &self.used
246    }
247
248    /// 获取已分配给子账本的配额
249    #[inline]
250    pub fn allocated_to_children(&self) -> &LedgerQuota {
251        &self.allocated_to_children
252    }
253
254    /// 获取子账本数量
255    #[inline]
256    pub fn child_count(&self) -> usize {
257        self.children.len()
258    }
259
260    /// 迭代子账本名称
261    pub fn child_names(&self) -> impl Iterator<Item = &str> {
262        self.children.keys().map(|s| s.as_str())
263    }
264
265    /// 查找子账本(不可变)
266    pub fn get_child(&self, name: &str) -> Option<&ResourceLedger> {
267        self.children.get(name)
268    }
269
270    /// 查找子账本(可变)
271    pub fn get_child_mut(&mut self, name: &str) -> Option<&mut ResourceLedger> {
272        self.children.get_mut(name)
273    }
274
275    /// 在当前账本下创建子账本
276    ///
277    /// 父账本校验(fail-closed,逐项资源):
278    /// `allocated_to_children + child_quota <= total - used`
279    ///
280    /// 即「已承诺给现有子账本的配额 + 新子账本配额」不得超过父账本
281    /// 扣除自身已用后的剩余配额,防止多子账本配额之和超卖父账本。
282    ///
283    /// # 失败
284    /// - 配额不足(含兄弟账本已占用部分)→ CoreError::QuotaExceeded
285    /// - 子账本名称已存在 → CoreError::ResourceAlreadyExists
286    /// - 子账本全零配额 → CoreError::InvalidConfig(静默失败防护)
287    pub fn create_child(
288        &mut self,
289        name: impl Into<String>,
290        ledger_type: LedgerType,
291        quota: LedgerQuota,
292    ) -> CoreResult<&mut ResourceLedger> {
293        let name: String = name.into();
294
295        // 零配额防护:三项全零的子账本无任何可用资源,必然导致后续 allocate 静默失败
296        if quota.memory_bytes == 0
297            && quota.frame_count == 0
298            && quota.connection_count == 0
299        {
300            return Err(CoreError::invalid_config(
301                "LedgerQuota",
302                "all quota fields are zero; a child ledger with zero total quota can never allocate any resource",
303            ));
304        }
305
306        if self.children.contains_key(&name) {
307            return Err(CoreError::resource_already_exists(
308                0,
309                "ledger",
310            ));
311        }
312
313        // 超卖防护(checked 算术,逐项资源):
314        // allocated_to_children + child_quota <= total - used
315        for resource in [ResourceType::Memory, ResourceType::Frames, ResourceType::Connections] {
316            let committed = self
317                .allocated_to_children
318                .get(resource)
319                .checked_add(quota.get(resource))
320                .ok_or_else(|| {
321                    CoreError::arithmetic_overflow(
322                        "add",
323                        self.allocated_to_children.get(resource),
324                        quota.get(resource),
325                    )
326                })?;
327            // used <= total 由 allocate 的校验保证;checked_sub 兜底不变量损坏场景
328            let available = self
329                .total
330                .get(resource)
331                .checked_sub(self.used.get(resource))
332                .ok_or_else(|| {
333                    CoreError::arithmetic_overflow(
334                        "sub",
335                        self.total.get(resource),
336                        self.used.get(resource),
337                    )
338                })?;
339            if committed > available {
340                return Err(CoreError::quota_exceeded(
341                    resource.name(),
342                    available,
343                    committed,
344                ));
345            }
346        }
347
348        // 累加子账本配额;溢出错误必须上报真实操作数(allocated_to_children
349        // 当前值),禁止硬编码 u64::MAX 谎报现场,便于事后审计定位
350        self.allocated_to_children.memory_bytes = self
351            .allocated_to_children
352            .memory_bytes
353            .checked_add(quota.memory_bytes)
354            .ok_or_else(|| {
355                CoreError::arithmetic_overflow(
356                    "add",
357                    self.allocated_to_children.memory_bytes,
358                    quota.memory_bytes,
359                )
360            })?;
361        self.allocated_to_children.frame_count = self
362            .allocated_to_children
363            .frame_count
364            .checked_add(quota.frame_count)
365            .ok_or_else(|| {
366                CoreError::arithmetic_overflow(
367                    "add",
368                    self.allocated_to_children.frame_count,
369                    quota.frame_count,
370                )
371            })?;
372        self.allocated_to_children.connection_count = self
373            .allocated_to_children
374            .connection_count
375            .checked_add(quota.connection_count)
376            .ok_or_else(|| {
377                CoreError::arithmetic_overflow(
378                    "add",
379                    self.allocated_to_children.connection_count,
380                    quota.connection_count,
381                )
382            })?;
383
384        let child = ResourceLedger::new(name.clone(), ledger_type, quota);
385        self.children.insert(name.clone(), child);
386
387        self.children.get_mut(&name).ok_or_else(|| CoreError::internal("child ledger not found after insertion"))
388    }
389
390    /// 注销子账本(回收其配额)
391    ///
392    /// 子账本的 `total` 配额会从父账本的 `allocated_to_children` 中扣除。
393    /// 同时回滚子树曾向父账本 roll-up 的使用量(`used`):
394    /// 子树被移除后其占用的资源视为全部释放,父账本不再为其记账。
395    /// 回滚采用 checked 语义——子树 roll-up 用量必然 ≤ 本账本记账;
396    /// underflow 说明内部状态损坏,fail-closed 上报。
397    ///
398    /// # 原子性(无部分提交)
399    /// 全部回滚算术先在只读阶段预检完成,任一失败即整体返回 `Err`,
400    /// 子账本保持原位、父账本记账不变——杜绝"子账本已摘除但配额未回收"
401    /// 的永久配额泄漏窗口。
402    pub fn remove_child(&mut self, name: &str) -> CoreResult<()> {
403        // 阶段一:只读预检全部回滚算术(对 &child 计算差值),全部成功后才有提交资格
404        let (new_used, new_allocated) = {
405            let child = self
406                .children
407                .get(name)
408                .ok_or_else(|| CoreError::resource_not_found(0, "ledger"))?;
409
410            // 回滚子树 roll-up 到本账本的使用量(used_direct 不受影响:
411            // 子账本不占父账本直接用量)
412            let new_used = LedgerQuota {
413                memory_bytes: self.used.memory_bytes.checked_sub(child.used.memory_bytes).ok_or_else(
414                    || {
415                        CoreError::arithmetic_overflow(
416                            "sub",
417                            self.used.memory_bytes,
418                            child.used.memory_bytes,
419                        )
420                    },
421                )?,
422                frame_count: self
423                    .used
424                    .frame_count
425                    .checked_sub(child.used.frame_count)
426                    .ok_or_else(|| {
427                        CoreError::arithmetic_overflow(
428                            "sub",
429                            self.used.frame_count,
430                            child.used.frame_count,
431                        )
432                    })?,
433                connection_count: self
434                    .used
435                    .connection_count
436                    .checked_sub(child.used.connection_count)
437                    .ok_or_else(|| {
438                        CoreError::arithmetic_overflow(
439                            "sub",
440                            self.used.connection_count,
441                            child.used.connection_count,
442                        )
443                    })?,
444            };
445            // 回滚已分配给子账本的配额
446            let new_allocated = LedgerQuota {
447                memory_bytes: self
448                    .allocated_to_children
449                    .memory_bytes
450                    .checked_sub(child.total.memory_bytes)
451                    .ok_or_else(|| {
452                        CoreError::arithmetic_overflow(
453                            "sub",
454                            self.allocated_to_children.memory_bytes,
455                            child.total.memory_bytes,
456                        )
457                    })?,
458                frame_count: self
459                    .allocated_to_children
460                    .frame_count
461                    .checked_sub(child.total.frame_count)
462                    .ok_or_else(|| {
463                        CoreError::arithmetic_overflow(
464                            "sub",
465                            self.allocated_to_children.frame_count,
466                            child.total.frame_count,
467                        )
468                    })?,
469                connection_count: self
470                    .allocated_to_children
471                    .connection_count
472                    .checked_sub(child.total.connection_count)
473                    .ok_or_else(|| {
474                        CoreError::arithmetic_overflow(
475                            "sub",
476                            self.allocated_to_children.connection_count,
477                            child.total.connection_count,
478                        )
479                    })?,
480            };
481            (new_used, new_allocated)
482        };
483
484        // 阶段二:全部算术成功,原子提交(此后无任何可失败操作)
485        self.children.remove(name);
486        self.used = new_used;
487        self.allocated_to_children = new_allocated;
488        Ok(())
489    }
490
491    /// 在当前账本上分配资源(checked arithmetic)
492    ///
493    /// # 超卖防护
494    /// 本账本自身的直接用量(`used_direct`)+ 已承诺给子账本的配额不得超过 `total`。
495    /// 否则父账本可直接分配耗尽 `total`,与子账本承诺配额叠加造成
496    /// "子账本配额 + 父自身用量 > total" 的分层配额超卖。
497    ///
498    /// # 双重计数修复(CORE-013)
499    /// 传统实现用 `used`(子树汇总)参与分配校验,会把子账本实际 roll-up 用量
500    /// 与 `allocated_to_children` 配额重复计算,导致子账本用量 < 其配额时父账本
501    /// 合法分配被误拒。修复后校验仅依赖 `used_direct`(本账本自身直接用量),
502    /// 与子账本已承诺配额做加法,不再叠加子账本实际用量。
503    pub fn allocate(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
504        let direct = self.used_direct.get(resource);
505        let total = self.total.get(resource);
506        let new_direct = direct
507            .checked_add(amount)
508            .ok_or_else(|| CoreError::arithmetic_overflow("add", direct, amount))?;
509
510        // 已承诺给子账本的配额需从父账本可分配预算中预留
511        let committed = self.allocated_to_children.get(resource);
512        let total_need = new_direct
513            .checked_add(committed)
514            .ok_or_else(|| CoreError::arithmetic_overflow("add", new_direct, committed))?;
515        if total_need > total {
516            return Err(CoreError::quota_exceeded(resource.name(), total, total_need));
517        }
518
519        // 双轨记账:直接用量计入 used_direct,同时计入 used(子树汇总)
520        self.used_direct.restore(resource, amount)?;
521        self.used.restore(resource, amount)?;
522        Ok(())
523    }
524
525    /// 祖先 roll-up 专用分配(**不**检查 `allocated_to_children`)。
526    ///
527    /// 子账本的实际用量已由其自身配额约束(该配额已计入父账本
528    /// `allocated_to_children`),故 roll-up 仅需保证不超过 `total`。
529    /// 直接分配一律走 [`allocate`](Self::allocate)(含超卖防护)。
530    fn allocate_rollup(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
531        let current = self.used.get(resource);
532        let total = self.total.get(resource);
533        let new_used = current
534            .checked_add(amount)
535            .ok_or_else(|| CoreError::arithmetic_overflow("add", current, amount))?;
536        if new_used > total {
537            return Err(CoreError::quota_exceeded(resource.name(), total, new_used));
538        }
539        self.used.restore(resource, amount)?;
540        Ok(())
541    }
542
543    /// 在当前账本上释放资源(直接释放,与 [`allocate`](Self::allocate) 互逆)
544    ///
545    /// 双轨回滚:`used_direct`(本账本直接用量)与 `used`(子树汇总)同时扣减。
546    /// 祖先 roll-up 回滚请使用 [`release_rollup`](Self::release_rollup),勿在本方法误用。
547    pub fn release(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
548        self.used_direct.consume(resource, amount)?;
549        self.used.consume(resource, amount)?;
550        Ok(())
551    }
552
553    /// 祖先 roll-up 回滚专用释放(**不**更新 `used_direct`)。
554    ///
555    /// 与 [`allocate_rollup`](Self::allocate_rollup) 互逆:roll-up 只增加 `used`
556    /// (子树汇总),因此回滚只扣减 `used`,避免误扣未发生的父账本直接用量。
557    fn release_rollup(&mut self, resource: ResourceType, amount: u64) -> CoreResult<()> {
558        self.used.consume(resource, amount)?;
559        Ok(())
560    }
561
562    /// 在指定子账本(按名称路径逐层下钻)上分配资源,并沿路径向所有祖先 roll-up
563    ///
564    /// 分层配额语义:子孙的实际使用同时消耗路径上每一层祖先的配额,
565    /// 因此祖先账本的 `used` 始终反映其整棵子树的使用量。
566    ///
567    /// # 原子性
568    /// 路径上任一层配额不足或路径不存在时,已完成的祖先 roll-up 会逐层回滚,
569    /// 调用前后账本树保持一致(fail-closed,不产生部分提交)。
570    ///
571    /// # Arguments
572    /// * `child_path` - 子账本名称路径(空路径等价于 `self.allocate`)
573    /// * `resource` - 资源类型
574    /// * `amount` - 分配数量
575    ///
576    /// # 失败
577    /// - 路径不存在 → CoreError::ResourceNotFound
578    /// - 任一层配额不足 → CoreError::QuotaExceeded
579    pub fn allocate_in_child(
580        &mut self,
581        child_path: &[&str],
582        resource: ResourceType,
583        amount: u64,
584    ) -> CoreResult<()> {
585        match child_path.split_first() {
586            None => self.allocate(resource, amount),
587            Some((head, rest)) => {
588                // 子账本存在性预检(fail-closed:避免祖先 roll-up 后才发现路径不存在)
589                if !self.children.contains_key(*head) {
590                    return Err(CoreError::resource_not_found(0, "ledger"));
591                }
592                // 祖先层先 roll-up:祖先配额不足直接失败,子树零变更。
593                // 用 allocate_rollup(不检查 allocated_to_children),
594                // 避免与子账本已承诺配额重复计数导致合法分配被误拒。
595                self.allocate_rollup(resource, amount)?;
596                let child = self
597                    .children
598                    .get_mut(*head)
599                    .ok_or_else(|| CoreError::internal("child ledger not found after existence check"))?;
600                match child.allocate_in_child(rest, resource, amount) {
601                    Ok(()) => Ok(()),
602                    Err(e) => {
603                        // 子树分配失败 → 回滚祖先层 roll-up,保持账本树守恒
604                        // (不变量:刚加上的 amount 必然能减回;回滚失败说明内部状态损坏,优先上报)
605                        // 祖先层 roll-up 只增加过 used,故用 release_rollup 只扣 used,
606                        // 避免误扣 used_direct
607                        self.release_rollup(resource, amount)?;
608                        Err(e)
609                    }
610                }
611            }
612        }
613    }
614
615    /// 在指定子账本(按名称路径逐层下钻)上释放资源,并沿路径回滚所有祖先的 roll-up
616    ///
617    /// 与 [`ResourceLedger::allocate_in_child`] 互逆:释放时逐层扣减路径上
618    /// 每个账本的 `used`,保证祖先账本记账与子树实际使用一致。
619    ///
620    /// # 原子性
621    /// 路径不存在或任一层 `used` 不足时,已回滚的祖先层会逐层恢复,
622    /// 调用前后账本树保持一致(fail-closed,不产生部分提交)。
623    ///
624    /// # 失败
625    /// - 路径不存在 → CoreError::ResourceNotFound
626    /// - 任一层 `used` 不足(释放量超过已分配量)→ CoreError::ArithmeticOverflow
627    pub fn release_in_child(
628        &mut self,
629        child_path: &[&str],
630        resource: ResourceType,
631        amount: u64,
632    ) -> CoreResult<()> {
633        match child_path.split_first() {
634            None => self.release(resource, amount),
635            Some((head, rest)) => {
636                // 子账本存在性预检(fail-closed)
637                if !self.children.contains_key(*head) {
638                    return Err(CoreError::resource_not_found(0, "ledger"));
639                }
640                // 祖先层先回滚(used 不足直接失败,子树零变更)
641                // 祖先层用量由 roll-up 计入 `used`,不占 `used_direct`,故用 release_rollup
642                self.release_rollup(resource, amount)?;
643                let child = self
644                    .children
645                    .get_mut(*head)
646                    .ok_or_else(|| CoreError::internal("child ledger not found after existence check"))?;
647                match child.release_in_child(rest, resource, amount) {
648                    Ok(()) => Ok(()),
649                    Err(e) => {
650                        // 子树释放失败 → 恢复祖先层记账,保持账本树守恒
651                        // (不变量:刚减去的 amount 加回后等于原值,必然不溢出)
652                        self.used.restore(resource, amount)?;
653                        Err(e)
654                    }
655                }
656            }
657        }
658    }
659
660    /// 检查是否可以分配指定资源
661    ///
662    /// 与 [`allocate`](Self::allocate) 的校验一致:`used_direct + amount + allocated_to_children <= total`。
663    /// 使用 checked_add 判断,加法溢出(不可容纳于 u64)时返回 false(fail-closed,CORE-012)。
664    #[inline]
665    pub fn can_allocate(&self, resource: ResourceType, amount: u64) -> bool {
666        let direct = self.used_direct.get(resource);
667        let total = self.total.get(resource);
668        let committed = self.allocated_to_children.get(resource);
669        match direct
670            .checked_add(amount)
671            .and_then(|v| v.checked_add(committed))
672        {
673            Some(need) => need <= total,
674            // 溢出 → 必然超限,fail-closed 返回 false
675            None => false,
676        }
677    }
678
679    /// 计算剩余配额
680    pub fn remaining(&self) -> LedgerQuota {
681        self.total.remaining(&self.used)
682    }
683
684    /// 递归深度(用于调试)
685    pub fn max_depth(&self) -> u8 {
686        let mut max = self.depth();
687        for child in self.children.values() {
688            max = max.max(child.max_depth());
689        }
690        max
691    }
692
693    /// 账本树节点总数(用于完整性检查)
694    pub fn node_count(&self) -> u64 {
695        // 饱和累加:BTreeMap 子节点数为 usize,四层分层结构下
696        // u64 求和实际不可达溢出;saturating_add 仅为满足
697        // 「生产路径禁止裸算术」的兜底防御
698        self.children
699            .values()
700            .map(ResourceLedger::node_count)
701            .fold(1u64, u64::saturating_add)
702    }
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    fn make_quota(mem: u64, frames: u64, conns: u64) -> LedgerQuota {
710        LedgerQuota {
711            memory_bytes: mem,
712            frame_count: frames,
713            connection_count: conns,
714        }
715    }
716
717    #[test]
718    fn test_root_ledger_create() {
719        let root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
720        assert_eq!(root.name(), "root");
721        assert_eq!(root.ledger_type(), LedgerType::Root);
722        assert_eq!(root.depth(), 0);
723        assert_eq!(root.total().memory_bytes, 1 << 30);
724        assert_eq!(root.used().memory_bytes, 0);
725        assert_eq!(root.child_count(), 0);
726        assert_eq!(root.node_count(), 1);
727    }
728
729    #[test]
730    fn test_create_domain_child() {
731        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
732
733        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
734            .unwrap();
735
736        assert_eq!(root.child_count(), 1);
737        assert!(root.get_child("domain_0").is_some());
738
739        let domain = root.get_child("domain_0").unwrap();
740        assert_eq!(domain.ledger_type(), LedgerType::Domain);
741        assert_eq!(domain.depth(), 1);
742        assert_eq!(domain.total().frame_count, 10_000);
743        assert_eq!(root.node_count(), 2);
744    }
745
746    #[test]
747    fn test_create_child_quota_exceeded() {
748        let mut root = ResourceLedger::root(make_quota(1024, 100, 10));
749
750        // 尝试创建超出父账本配额的子账本
751        let result = root.create_child("big", LedgerType::Domain, make_quota(2048, 0, 0));
752        assert!(result.is_err());
753
754        // 父账本不受影响
755        assert_eq!(root.child_count(), 0);
756        assert_eq!(root.total().memory_bytes, 1024);
757    }
758
759    #[test]
760    fn test_duplicate_child_name() {
761        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
762
763        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
764            .unwrap();
765
766        let result = root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000));
767        assert!(result.is_err());
768    }
769
770    #[test]
771    fn test_allocate_and_release() {
772        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(4096, 100, 10));
773
774        // 分配内存
775        ledger.allocate(ResourceType::Memory, 1024).unwrap();
776        assert_eq!(ledger.used().memory_bytes, 1024);
777
778        // 归还
779        ledger.release(ResourceType::Memory, 512).unwrap();
780        assert_eq!(ledger.used().memory_bytes, 512);
781
782        // 剩余配额
783        let remaining = ledger.remaining();
784        assert_eq!(remaining.memory_bytes, 4096 - 512);
785    }
786
787    #[test]
788    fn test_allocate_quota_exceeded() {
789        let mut ledger = ResourceLedger::new("small", LedgerType::Queue, make_quota(1024, 0, 0));
790
791        ledger.allocate(ResourceType::Memory, 512).unwrap();
792
793        let result = ledger.allocate(ResourceType::Memory, 1024);
794        assert!(result.is_err());
795    }
796
797    #[test]
798    fn test_allocate_overflow() {
799        let mut ledger = ResourceLedger::new("max", LedgerType::Queue, make_quota(u64::MAX, 0, 0));
800
801        ledger.allocate(ResourceType::Memory, u64::MAX).unwrap();
802
803        let result = ledger.allocate(ResourceType::Memory, 1);
804        assert!(result.is_err());
805    }
806
807    #[test]
808    fn test_frames_and_connections() {
809        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 1000, 50));
810
811        ledger.allocate(ResourceType::Frames, 500).unwrap();
812        assert_eq!(ledger.used().frame_count, 500);
813
814        ledger.allocate(ResourceType::Connections, 10).unwrap();
815        assert_eq!(ledger.used().connection_count, 10);
816
817        ledger.release(ResourceType::Frames, 200).unwrap();
818        assert_eq!(ledger.used().frame_count, 300);
819    }
820
821    #[test]
822    fn test_can_allocate() {
823        let ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1 << 30, 0, 0));
824
825        assert!(ledger.can_allocate(ResourceType::Memory, 1024));
826        assert!(ledger.can_allocate(ResourceType::Memory, 1 << 30));
827        assert!(!ledger.can_allocate(ResourceType::Memory, (1 << 30) + 1));
828    }
829
830    #[test]
831    fn test_nested_hierarchy() {
832        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
833
834        // 域
835        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 24, 50_000, 5_000))
836            .unwrap();
837
838        // 在域下创建队列
839        root.get_child_mut("domain_0").unwrap()
840            .create_child("queue_0", LedgerType::Queue, make_quota(1 << 20, 10_000, 1_000))
841            .unwrap();
842
843        // 在队列下创建连接
844        root.get_child_mut("domain_0").unwrap()
845            .get_child_mut("queue_0").unwrap()
846            .create_child("conn_0", LedgerType::Connection, make_quota(1 << 16, 100, 10))
847            .unwrap();
848
849        // 验证层级深度
850        let conn = root.get_child("domain_0").unwrap()
851            .get_child("queue_0").unwrap()
852            .get_child("conn_0").unwrap();
853        assert_eq!(conn.depth(), 3);
854        assert_eq!(conn.ledger_type(), LedgerType::Connection);
855        assert_eq!(root.max_depth(), 3);
856        assert_eq!(root.node_count(), 4);
857
858        // 在连接上分配资源(需要可变访问)
859        root.get_child_mut("domain_0").unwrap()
860            .get_child_mut("queue_0").unwrap()
861            .get_child_mut("conn_0").unwrap()
862            .allocate(ResourceType::Memory, 1024)
863            .unwrap();
864
865        assert_eq!(
866            root.get_child("domain_0").unwrap()
867                .get_child("queue_0").unwrap()
868                .get_child("conn_0").unwrap()
869                .used()
870                .memory_bytes,
871            1024
872        );
873    }
874
875    #[test]
876    fn test_remove_child_reclaims_quota() {
877        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
878
879        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
880            .unwrap();
881
882        // 在域下创建队列并分配资源(域自身的 used 被增加)
883        root.get_child_mut("domain_0").unwrap()
884            .create_child("queue_0", LedgerType::Queue, make_quota(1 << 16, 1000, 100))
885            .unwrap();
886
887        root.get_child_mut("domain_0").unwrap()
888            .get_child_mut("queue_0").unwrap()
889            .allocate(ResourceType::Memory, 4096)
890            .unwrap();
891
892        // 验证子账本的 used 正确追踪
893        let queue_used = root.get_child("domain_0").unwrap()
894            .get_child("queue_0").unwrap()
895            .used().memory_bytes;
896        assert_eq!(queue_used, 4096);
897
898        // 父账本的 used = 所有子孙的 used 之和,在 remove_child 时统一回收
899        // 回收域的 total 配额
900        root.remove_child("domain_0").unwrap();
901
902        assert_eq!(root.child_count(), 0);
903        // allocated_to_children 已清零(域的 total 已回收)
904        assert_eq!(root.allocated_to_children().memory_bytes, 0);
905    }
906
907    #[test]
908    fn test_remove_nonexistent_child() {
909        let mut root = ResourceLedger::root(make_quota(1 << 30, 0, 0));
910        let result = root.remove_child("nonexistent");
911        assert!(result.is_err());
912    }
913
914    #[test]
915    fn test_list_child_names() {
916        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
917
918        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
919            .unwrap();
920        root.create_child("domain_1", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
921            .unwrap();
922
923        let names: Vec<&str> = root.child_names().collect();
924        assert_eq!(names.len(), 2);
925        assert!(names.contains(&"domain_0"));
926        assert!(names.contains(&"domain_1"));
927    }
928
929    #[test]
930    fn test_allocations_accounted_in_parent() {
931        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
932
933        root.create_child("domain_0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000))
934            .unwrap();
935
936        // 子账本消耗资源
937        root.get_child_mut("domain_0").unwrap()
938            .allocate(ResourceType::Memory, 8192)
939            .unwrap();
940
941        // 父账本看到子账本的使用
942        assert_eq!(root.get_child("domain_0").unwrap().used().memory_bytes, 8192);
943
944        // 但子账本自身的 used 也被正确跟踪
945        let domain = root.get_child("domain_0").unwrap();
946        assert!(domain.can_allocate(ResourceType::Memory, (1 << 20) - 8192));
947        assert!(!domain.can_allocate(ResourceType::Memory, (1 << 20) - 8191));
948    }
949
950    // ===== LedgerQuota: zero()/unlimited()/can_allocate 测试 =====
951
952    #[test]
953    fn test_ledger_quota_zero() {
954        let q = LedgerQuota::zero();
955        assert_eq!(q.memory_bytes, 0);
956        assert_eq!(q.frame_count, 0);
957        assert_eq!(q.connection_count, 0);
958    }
959
960    #[test]
961    fn test_ledger_quota_unlimited() {
962        let q = LedgerQuota::unlimited();
963        assert_eq!(q.memory_bytes, u64::MAX);
964        assert_eq!(q.frame_count, u64::MAX);
965        assert_eq!(q.connection_count, u64::MAX);
966    }
967
968    #[test]
969    fn test_ledger_quota_can_allocate_memory() {
970        let parent = make_quota(1024, 0, 0);
971        let child_ok = make_quota(512, 0, 0);
972        let child_exceed = make_quota(2048, 0, 0);
973
974        assert!(parent.can_allocate(&child_ok).is_ok());
975        assert!(parent.can_allocate(&child_exceed).is_err());
976    }
977
978    #[test]
979    fn test_ledger_quota_can_allocate_frames() {
980        let parent = make_quota(0, 100, 0);
981        let child_ok = make_quota(0, 50, 0);
982        let child_exceed = make_quota(0, 200, 0);
983
984        assert!(parent.can_allocate(&child_ok).is_ok());
985        assert!(parent.can_allocate(&child_exceed).is_err());
986    }
987
988    #[test]
989    fn test_ledger_quota_can_allocate_connections() {
990        let parent = make_quota(0, 0, 10);
991        let child_ok = make_quota(0, 0, 5);
992        let child_exceed = make_quota(0, 0, 20);
993
994        assert!(parent.can_allocate(&child_ok).is_ok());
995        assert!(parent.can_allocate(&child_exceed).is_err());
996    }
997
998    #[test]
999    fn test_ledger_quota_can_allocate_exact() {
1000        let parent = make_quota(100, 200, 300);
1001        let child_exact = make_quota(100, 200, 300);
1002        assert!(parent.can_allocate(&child_exact).is_ok());
1003    }
1004
1005    #[test]
1006    fn test_ledger_quota_consume_and_restore() {
1007        let mut q = make_quota(1000, 100, 10);
1008
1009        q.consume(ResourceType::Memory, 500).unwrap();
1010        assert_eq!(q.memory_bytes, 500);
1011
1012        q.restore(ResourceType::Memory, 300).unwrap();
1013        assert_eq!(q.memory_bytes, 800);
1014    }
1015
1016    #[test]
1017    fn test_ledger_quota_consume_underflow() {
1018        let mut q = make_quota(100, 0, 0);
1019        let result = q.consume(ResourceType::Memory, 200);
1020        assert!(result.is_err());
1021    }
1022
1023    #[test]
1024    fn test_ledger_quota_restore_overflow() {
1025        let mut q = make_quota(u64::MAX, 0, 0);
1026        let result = q.restore(ResourceType::Memory, 1);
1027        assert!(result.is_err());
1028    }
1029
1030    #[test]
1031    fn test_ledger_quota_get() {
1032        let q = make_quota(10, 20, 30);
1033        assert_eq!(q.get(ResourceType::Memory), 10);
1034        assert_eq!(q.get(ResourceType::Frames), 20);
1035        assert_eq!(q.get(ResourceType::Connections), 30);
1036    }
1037
1038    #[test]
1039    fn test_ledger_quota_remaining() {
1040        let total = make_quota(1000, 100, 50);
1041        let used = make_quota(400, 30, 10);
1042        let remaining = total.remaining(&used);
1043        assert_eq!(remaining.memory_bytes, 600);
1044        assert_eq!(remaining.frame_count, 70);
1045        assert_eq!(remaining.connection_count, 40);
1046    }
1047
1048    #[test]
1049    fn test_ledger_quota_remaining_saturating() {
1050        let total = make_quota(100, 0, 0);
1051        let used = make_quota(200, 0, 0);
1052        let remaining = total.remaining(&used);
1053        assert_eq!(remaining.memory_bytes, 0);
1054    }
1055
1056    // ===== LedgerType: depth() 所有变体测试 =====
1057
1058    #[test]
1059    fn test_ledger_type_depth() {
1060        assert_eq!(LedgerType::Root.depth(), 0);
1061        assert_eq!(LedgerType::Domain.depth(), 1);
1062        assert_eq!(LedgerType::Queue.depth(), 2);
1063        assert_eq!(LedgerType::Connection.depth(), 3);
1064    }
1065
1066    #[test]
1067    fn test_ledger_type_equality() {
1068        assert_eq!(LedgerType::Root, LedgerType::Root);
1069        assert_ne!(LedgerType::Root, LedgerType::Domain);
1070    }
1071
1072    #[test]
1073    fn test_ledger_type_debug() {
1074        assert_eq!(format!("{:?}", LedgerType::Root), "Root");
1075        assert_eq!(format!("{:?}", LedgerType::Connection), "Connection");
1076    }
1077
1078    // ===== ResourceType: name() 所有变体测试 =====
1079
1080    #[test]
1081    fn test_resource_type_name() {
1082        assert_eq!(ResourceType::Memory.name(), "memory");
1083        assert_eq!(ResourceType::Frames.name(), "frames");
1084        assert_eq!(ResourceType::Connections.name(), "connections");
1085    }
1086
1087    #[test]
1088    fn test_resource_type_equality() {
1089        assert_eq!(ResourceType::Memory, ResourceType::Memory);
1090        assert_ne!(ResourceType::Memory, ResourceType::Frames);
1091    }
1092
1093    #[test]
1094    fn test_resource_type_debug() {
1095        assert_eq!(format!("{:?}", ResourceType::Memory), "Memory");
1096        assert_eq!(format!("{:?}", ResourceType::Frames), "Frames");
1097    }
1098
1099    // ===== ResourceLedger: 多层嵌套配额守恒检查 =====
1100
1101    #[test]
1102    fn test_multiple_children_quota_sum() {
1103        let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));
1104
1105        root.create_child("d0", LedgerType::Domain, make_quota(3000, 300, 30)).unwrap();
1106        root.create_child("d1", LedgerType::Domain, make_quota(2000, 200, 20)).unwrap();
1107        root.create_child("d2", LedgerType::Domain, make_quota(5000, 500, 50)).unwrap();
1108
1109        let allocated = root.allocated_to_children();
1110        assert_eq!(allocated.memory_bytes, 10000);
1111        assert_eq!(allocated.frame_count, 1000);
1112        assert_eq!(allocated.connection_count, 100);
1113    }
1114
1115    #[test]
1116    fn test_nested_three_level_quota_conservation() {
1117        let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));
1118
1119        root.create_child("d0", LedgerType::Domain, make_quota(5000, 500, 50)).unwrap();
1120
1121        root.get_child_mut("d0").unwrap()
1122            .create_child("q0", LedgerType::Queue, make_quota(2000, 200, 20)).unwrap();
1123        root.get_child_mut("d0").unwrap()
1124            .create_child("q1", LedgerType::Queue, make_quota(3000, 300, 30)).unwrap();
1125
1126        let domain_allocated = root.get_child("d0").unwrap().allocated_to_children();
1127        assert_eq!(domain_allocated.memory_bytes, 5000);
1128        assert_eq!(domain_allocated.frame_count, 500);
1129        assert_eq!(domain_allocated.connection_count, 50);
1130
1131        let root_allocated = root.allocated_to_children();
1132        assert_eq!(root_allocated.memory_bytes, 5000);
1133    }
1134
1135    #[test]
1136    fn test_child_quota_exceeds_parent_total() {
1137        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1138
1139        let result = root.create_child("big", LedgerType::Domain, make_quota(2000, 200, 20));
1140        assert!(result.is_err());
1141
1142        assert_eq!(root.child_count(), 0);
1143        assert_eq!(root.allocated_to_children().memory_bytes, 0);
1144    }
1145
1146    #[test]
1147    fn test_child_quota_exceeds_parent_used_remaining() {
1148        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1149
1150        root.allocate(ResourceType::Memory, 600).unwrap();
1151        root.allocate(ResourceType::Frames, 60).unwrap();
1152        root.allocate(ResourceType::Connections, 6).unwrap();
1153
1154        let result = root.create_child("d0", LedgerType::Domain, make_quota(500, 50, 5));
1155        assert!(result.is_err());
1156
1157        assert_eq!(root.child_count(), 0);
1158    }
1159
1160    // ===== release 导致 underflow 的 checked arithmetic =====
1161
1162    #[test]
1163    fn test_release_underflow_memory() {
1164        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1000, 0, 0));
1165        ledger.allocate(ResourceType::Memory, 500).unwrap();
1166        ledger.release(ResourceType::Memory, 300).unwrap();
1167        assert_eq!(ledger.used().memory_bytes, 200);
1168    }
1169
1170    #[test]
1171    fn test_release_underflow_frames() {
1172        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 100, 0));
1173        ledger.allocate(ResourceType::Frames, 50).unwrap();
1174        let result = ledger.release(ResourceType::Frames, 100);
1175        assert!(result.is_err());
1176    }
1177
1178    #[test]
1179    fn test_release_underflow_connections() {
1180        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(0, 0, 10));
1181        let result = ledger.release(ResourceType::Connections, 1);
1182        assert!(result.is_err());
1183    }
1184
1185    // ===== allocated_to_children 的正确性校验 =====
1186
1187    #[test]
1188    fn test_allocated_to_children_after_remove() {
1189        let mut root = ResourceLedger::root(make_quota(10000, 1000, 100));
1190
1191        root.create_child("d0", LedgerType::Domain, make_quota(3000, 300, 30)).unwrap();
1192        root.create_child("d1", LedgerType::Domain, make_quota(2000, 200, 20)).unwrap();
1193
1194        assert_eq!(root.allocated_to_children().memory_bytes, 5000);
1195        assert_eq!(root.allocated_to_children().frame_count, 500);
1196        assert_eq!(root.allocated_to_children().connection_count, 50);
1197
1198        root.remove_child("d0").unwrap();
1199
1200        assert_eq!(root.allocated_to_children().memory_bytes, 2000);
1201        assert_eq!(root.allocated_to_children().frame_count, 200);
1202        assert_eq!(root.allocated_to_children().connection_count, 20);
1203    }
1204
1205    #[test]
1206    fn test_allocated_to_children_zero_initially() {
1207        let root = ResourceLedger::root(make_quota(1000, 100, 10));
1208        assert_eq!(root.allocated_to_children().memory_bytes, 0);
1209        assert_eq!(root.allocated_to_children().frame_count, 0);
1210        assert_eq!(root.allocated_to_children().connection_count, 0);
1211    }
1212
1213    // ===== LedgerQuota Default 实现 =====
1214
1215    #[test]
1216    fn test_ledger_quota_default() {
1217        let q = LedgerQuota::default();
1218        assert_eq!(q.memory_bytes, 0);
1219        assert_eq!(q.frame_count, 0);
1220        assert_eq!(q.connection_count, 0);
1221    }
1222
1223    // ===== ResourceLedger remaining =====
1224
1225    #[test]
1226    fn test_ledger_remaining() {
1227        let mut ledger = ResourceLedger::new("test", LedgerType::Queue, make_quota(1000, 100, 10));
1228        ledger.allocate(ResourceType::Memory, 400).unwrap();
1229        ledger.allocate(ResourceType::Frames, 30).unwrap();
1230        ledger.allocate(ResourceType::Connections, 5).unwrap();
1231
1232        let remaining = ledger.remaining();
1233        assert_eq!(remaining.memory_bytes, 600);
1234        assert_eq!(remaining.frame_count, 70);
1235        assert_eq!(remaining.connection_count, 5);
1236    }
1237
1238    // ===== 深层嵌套 4 级完整链路 =====
1239
1240    #[test]
1241    fn test_four_level_hierarchy_allocated_to_children() {
1242        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
1243
1244        root.create_child("d0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000)).unwrap();
1245
1246        root.get_child_mut("d0").unwrap()
1247            .create_child("q0", LedgerType::Queue, make_quota(1 << 15, 1_000, 100)).unwrap();
1248
1249        root.get_child_mut("d0").unwrap().get_child_mut("q0").unwrap()
1250            .create_child("c0", LedgerType::Connection, make_quota(1 << 10, 100, 10)).unwrap();
1251
1252        assert_eq!(root.max_depth(), 3);
1253        assert_eq!(root.node_count(), 4);
1254
1255        let conn = root.get_child("d0").unwrap().get_child("q0").unwrap().get_child("c0").unwrap();
1256        assert_eq!(conn.ledger_type(), LedgerType::Connection);
1257        assert_eq!(conn.depth(), 3);
1258    }
1259
1260    // ===== create_child 超卖防护(allocated_to_children 计入校验) =====
1261
1262    #[test]
1263    fn test_create_child_oversubscription_rejected() {
1264        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1265
1266        // 第一个子账本占 600:通过
1267        root.create_child("c1", LedgerType::Domain, make_quota(600, 60, 6)).unwrap();
1268        // 第二个子账本再要 600:600 + 600 = 1200 > 1000,必须拒绝(旧实现会放过)
1269        let result = root.create_child("c2", LedgerType::Domain, make_quota(600, 0, 0));
1270        assert!(result.is_err());
1271        assert_eq!(root.child_count(), 1);
1272
1273        // 400 恰好分完:600 + 400 = 1000 <= 1000,通过
1274        root.create_child("c2", LedgerType::Domain, make_quota(400, 40, 4)).unwrap();
1275        assert_eq!(root.child_count(), 2);
1276        assert_eq!(root.allocated_to_children().memory_bytes, 1000);
1277
1278        // 配额已分完,任何非零子账本都必须拒绝
1279        assert!(root.create_child("c3", LedgerType::Domain, make_quota(1, 0, 0)).is_err());
1280    }
1281
1282    #[test]
1283    fn test_create_child_accounts_parent_used() {
1284        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1285
1286        // 父账本自身使用 400 后,子账本配额之和不得超过 600
1287        root.allocate(ResourceType::Memory, 400).unwrap();
1288        root.create_child("c1", LedgerType::Domain, make_quota(600, 0, 0)).unwrap();
1289        assert!(root.create_child("c2", LedgerType::Domain, make_quota(1, 0, 0)).is_err());
1290    }
1291
1292    // ===== allocate_in_child / release_in_child 分层 roll-up =====
1293
1294    #[test]
1295    fn test_allocate_in_child_rolls_up_to_ancestors() {
1296        let mut root = ResourceLedger::root(make_quota(1 << 30, 100_000, 10_000));
1297        root.create_child("d0", LedgerType::Domain, make_quota(1 << 20, 10_000, 1_000)).unwrap();
1298        root.get_child_mut("d0").unwrap()
1299            .create_child("q0", LedgerType::Queue, make_quota(1 << 15, 1_000, 100)).unwrap();
1300
1301        // 在队列账本上分配 1024:路径上每层祖先都必须记账
1302        root.allocate_in_child(&["d0", "q0"], ResourceType::Memory, 1024).unwrap();
1303
1304        assert_eq!(root.used().memory_bytes, 1024);
1305        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 1024);
1306        assert_eq!(
1307            root.get_child("d0").unwrap().get_child("q0").unwrap().used().memory_bytes,
1308            1024
1309        );
1310
1311        // 释放时逐层回滚
1312        root.release_in_child(&["d0", "q0"], ResourceType::Memory, 1024).unwrap();
1313        assert_eq!(root.used().memory_bytes, 0);
1314        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
1315        assert_eq!(
1316            root.get_child("d0").unwrap().get_child("q0").unwrap().used().memory_bytes,
1317            0
1318        );
1319    }
1320
1321    #[test]
1322    fn test_allocate_in_child_ancestor_quota_enforced() {
1323        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1324        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1325
1326        // 超卖防护:父账本直接分配受子账本已承诺配额约束。
1327        // 直接用 600 + 已承诺 500 = 1100 > total 1000 → 拒绝
1328        assert!(root.allocate(ResourceType::Memory, 600).is_err());
1329        // 直接用 500 + 已承诺 500 = 1000 <= total → 允许
1330        root.allocate(ResourceType::Memory, 500).unwrap();
1331
1332        // 子树分配:子账本自身配额 500 决定其上限;祖先 roll-up 在父 total 内成功
1333        root.allocate_in_child(&["d0"], ResourceType::Memory, 500).unwrap();
1334        assert_eq!(root.used().memory_bytes, 1000);
1335        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 500);
1336
1337        // 超额分配:父 total 已占满(1000),子树再分配 100 → 祖先 roll-up 失败,原子回滚
1338        let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 100);
1339        assert!(result.is_err());
1340        assert_eq!(root.used().memory_bytes, 1000);
1341        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 500);
1342    }
1343
1344    #[test]
1345    fn test_allocate_in_child_rollback_on_descendant_failure() {
1346        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1347        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1348
1349        // 子账本配额只有 500,分配 600:子树失败,祖先 roll-up 必须回滚
1350        let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 600);
1351        assert!(result.is_err());
1352        assert_eq!(root.used().memory_bytes, 0);
1353        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
1354    }
1355
1356    // ===== CORE-013 双重计数回归测试 =====
1357
1358    #[test]
1359    fn test_allocate_not_double_counted_with_child_usage() {
1360        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1361        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1362
1363        // 子账本实际使用 200(roll-up 到 root.used;root.used_direct 仍为 0)
1364        root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1365        assert_eq!(root.used().memory_bytes, 200);
1366        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);
1367
1368        // 修复前:used(200)+400+committed(500)=1100>1000 → 误拒(把子用量与配额重复计数)
1369        // 修复后:used_direct(0)+400+committed(500)=900<=1000 → 成功
1370        // 实际 root 自身 400 + d0 用 200 = 600 <= 1000,且 d0 配额余量 300
1371        root.allocate(ResourceType::Memory, 400).unwrap();
1372
1373        assert_eq!(root.used().memory_bytes, 600);
1374        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);
1375        // 根账本剩余 = total - used = 1000 - 600 = 400
1376        assert_eq!(root.remaining().memory_bytes, 400);
1377    }
1378
1379    #[test]
1380    fn test_allocate_in_child_rollback_does_not_touch_used_direct() {
1381        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1382        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1383
1384        // 子账本分配失败(配额超限):祖先 roll-up 用 release_rollup 回滚,
1385        // 不得误扣父账本 used_direct
1386        root.allocate(ResourceType::Memory, 300).unwrap();
1387        let result = root.allocate_in_child(&["d0"], ResourceType::Memory, 600);
1388        assert!(result.is_err());
1389        // 父账本 used 回到仅含自身直接用量 300(回滚未越界、未误扣)
1390        assert_eq!(root.used().memory_bytes, 300);
1391    }
1392
1393    #[test]
1394    fn test_allocate_in_child_unknown_path() {
1395        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1396        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1397
1398        // 路径不存在:任何一层都不得变更
1399        assert!(root.allocate_in_child(&["nope"], ResourceType::Memory, 100).is_err());
1400        assert!(root.allocate_in_child(&["d0", "nope"], ResourceType::Memory, 100).is_err());
1401        assert_eq!(root.used().memory_bytes, 0);
1402        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 0);
1403    }
1404
1405    #[test]
1406    fn test_release_in_child_restores_on_descendant_failure() {
1407        let mut root = ResourceLedger::root(make_quota(1000, 0, 0));
1408        root.create_child("d0", LedgerType::Domain, make_quota(500, 0, 0)).unwrap();
1409
1410        root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1411
1412        // 子树已分配 200,释放 300:子树 used 不足,祖先已回滚的 300 必须恢复
1413        let result = root.release_in_child(&["d0"], ResourceType::Memory, 300);
1414        assert!(result.is_err());
1415        assert_eq!(root.used().memory_bytes, 200);
1416        assert_eq!(root.get_child("d0").unwrap().used().memory_bytes, 200);
1417
1418        // 正常释放路径不受影响
1419        root.release_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1420        assert_eq!(root.used().memory_bytes, 0);
1421    }
1422
1423    #[test]
1424    fn test_remove_child_reclaims_rolled_up_usage() {
1425        let mut root = ResourceLedger::root(make_quota(1000, 100, 10));
1426        root.create_child("d0", LedgerType::Domain, make_quota(500, 50, 5)).unwrap();
1427
1428        // 子树通过 roll-up 使用 200:父账本记账 200
1429        root.allocate_in_child(&["d0"], ResourceType::Memory, 200).unwrap();
1430        assert_eq!(root.used().memory_bytes, 200);
1431
1432        // 移除子账本:配额与 roll-up 使用量都必须回收,父账本不得泄漏记账
1433        root.remove_child("d0").unwrap();
1434        assert_eq!(root.used().memory_bytes, 0);
1435        assert_eq!(root.allocated_to_children().memory_bytes, 0);
1436
1437        // 回收后配额可重新分配
1438        root.create_child("d1", LedgerType::Domain, make_quota(1000, 100, 10)).unwrap();
1439    }
1440}