Skip to main content

atmos/os_lib/ecma/
gc_policy.rs

1//! ガベージコレクション方針および孤立ノード判定の純粋ロジック。
2//!
3//! レジスタやグローバルアロケータ、複雑なランタイム状態に触れず、
4//! ヒープ使用量・生存数に基づく次回回収間隔の決定や、
5//! DOM ノードの到達可能性判定を純粋計算で行う。
6
7use alloc::collections::BTreeSet;
8use alloc::vec::Vec;
9
10/// 回収の最小間隔(登録数)。
11pub const MIN_INTERVAL: usize = 50_000;
12
13/// 現在のヒープ使用量と生存数から、次回回収までのインターバル(生成数)を動的に決定する(純粋計算)。
14///
15/// 【2026-11-06】従来は `MIN_INTERVAL + live`(前回の生存数 100% 増)で設定していたため、
16/// 生存数が 50 万個あると次回まで 60 万個作られるまで回収されず、768MB ヒープが枯渇して
17/// `ALLOC FAIL` で panic していた(TODO A7)。ヒープ使用率に応じた上限と緊急縮小を導入。
18pub fn calc_next_interval_pure(live: usize, used: usize, total: usize) -> usize {
19    if total == 0 {
20        return (MIN_INTERVAL + live / 4).clamp(MIN_INTERVAL, 100_000);
21    }
22    let ratio_percent = (used.saturating_mul(100)) / total;
23    if ratio_percent >= 80 {
24        // 危険域 (80%超): 1万個ごとに緊急回収
25        10_000
26    } else if ratio_percent >= 70 {
27        // 高負荷域 (70%〜80%): 2.5万個ごと
28        25_000
29    } else if ratio_percent >= 55 {
30        // 中負荷域 (55%〜70%): 5万個ごと
31        50_000
32    } else {
33        // 低負荷域 (< 55%): 最大でも10万個でキャップ
34        (MIN_INTERVAL + live / 4).clamp(MIN_INTERVAL, 100_000)
35    }
36}
37
38/// 回収する頃合いかの判定(純粋計算)。
39#[allow(clippy::manual_checked_ops)] // `total > 0` の確認と割合の計算を並べて書いたほうが読みやすい
40pub fn should_collect_pure(made: usize, next_at: usize, used: usize, total: usize) -> bool {
41    if made >= next_at {
42        return true;
43    }
44    // メモリ圧迫(Memory Pressure)検知:
45    // ヒープが危険水域に達しており、前回収集からある程度生成されていれば早期回収
46    if total > 0 {
47        let ratio_percent = (used.saturating_mul(100)) / total;
48        if ratio_percent >= 80 && made >= 2_000 {
49            return true;
50        }
51        if ratio_percent >= 75 && made >= 5_000 {
52            return true;
53        }
54    }
55    false
56}
57
58/// 文書ルート(0番ノード)または JS から参照されたノードから到達可能な全ノードの集合を計算する。
59///
60/// `get_parent(i)`: ノード `i` の親ノード番号
61/// `get_children(i)`: ノード `i` の子ノード番号一覧
62/// `is_referenced(i)`: ノード `i` が JS 側から参照されているか
63pub fn find_reachable_dom_nodes<FParent, FChildren, FRef>(
64    total_nodes: usize,
65    mut get_parent: FParent,
66    mut get_children: FChildren,
67    mut is_referenced: FRef,
68) -> BTreeSet<usize>
69where
70    FParent: FnMut(usize) -> Option<usize>,
71    FChildren: FnMut(usize) -> Vec<usize>,
72    FRef: FnMut(usize) -> bool,
73{
74    let mut reachable = BTreeSet::new();
75    if total_nodes == 0 {
76        return reachable;
77    }
78
79    let mut stack = Vec::new();
80
81    // 1. 文書ルート(0番ノード)から辿れる全ノードをマーク
82    stack.push(0);
83    while let Some(i) = stack.pop() {
84        if !reachable.insert(i) {
85            continue;
86        }
87        for c in get_children(i) {
88            if c < total_nodes && !reachable.contains(&c) {
89                stack.push(c);
90            }
91        }
92    }
93
94    // 2. JS 側から参照されているノードについて、その連結成分(先祖と子孫)をマーク
95    for i in 1..total_nodes {
96        if reachable.contains(&i) {
97            continue;
98        }
99        if is_referenced(i) {
100            // 親を辿ってこの部分木の最上位ノードを見つける
101            let mut top = i;
102            let mut guard = 0;
103            while let Some(p) = get_parent(top) {
104                if p >= total_nodes || guard > 2048 {
105                    break;
106                }
107                top = p;
108                guard += 1;
109            }
110            // top から子孫をすべてマーク
111            stack.clear();
112            stack.push(top);
113            while let Some(curr) = stack.pop() {
114                if !reachable.insert(curr) {
115                    continue;
116                }
117                for c in get_children(curr) {
118                    if c < total_nodes && !reachable.contains(&c) {
119                        stack.push(c);
120                    }
121                }
122            }
123        }
124    }
125
126    reachable
127}
128
129/// 属性 `_content_frag` の値(`<template>` の `.content` のフラグメントの添字)を読む(2026-11-19)。
130pub fn parse_content_frag(attr: Option<&str>) -> Option<usize> {
131    attr.and_then(|s| s.parse::<usize>().ok())
132}
133
134/// 到達可能性の判定に使うノードの「子」の辺(2026-11-19)。
135///
136/// 実の子に加えて、シャドウ木の根(持ち主の要素の辺)と `<template>` の中身のフラグメントも辺に数える。
137/// 後者 2 つは親子ではなく別の表・属性の添字でつながるため、数えないと生きている `<template>` の
138/// 中身(`dom-if`・`dom-repeat` など)が孤立ノードと見なされて原型・expando を消されていた。
139pub fn children_with_links(children: &[usize], shadow_root: Option<usize>, content_frag: Option<usize>) -> Vec<usize> {
140    let mut kids = Vec::with_capacity(children.len() + 2);
141    kids.extend_from_slice(children);
142    if let Some(r) = shadow_root {
143        kids.push(r);
144    }
145    if let Some(f) = content_frag {
146        kids.push(f);
147    }
148    kids
149}