@furongjun1999/dsh-memory 0.9.7 → 0.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +150 -662
- package/codebuddy/CODEBUDDY.md +333 -204
- package/docs/README.md +18 -0
- package/docs/discipline/harnesses.yaml +11 -3
- package/docs/discipline/templates/compact.txt.tmpl +20 -18
- package/docs/discipline/templates/full.md.tmpl +63 -61
- package/docs/discipline/templates/rules.mdc.tmpl +5 -3
- package/docs/discipline/templates/skill.md.tmpl +25 -23
- package/docs/discipline/templates/spec.txt.tmpl +1 -1
- package/docs/discipline/templates/zcode-user.md.tmpl +1 -1
- package/lib/hooks.js +1 -1
- package/lib/index.js +9 -3
- package/lib/init.js +19 -4
- package/lib/lib/hook_audit.js +26 -0
- package/md_cg/sustain.py +10 -1
- package/md_cg/test_heartbeat_ledger.py +563 -557
- package/md_cg/test_n184_keys_concurrent_provision.py +1 -1
- package/md_cg/test_read_scope_b27.py +2 -2
- package/md_cg/test_security_audit_v21.py +249 -249
- package/md_cg/test_sustain_bad_stamp.py +178 -0
- package/package.json +1 -1
- package/src/hooks.ts +932 -932
- package/src/index.ts +18 -12
- package/src/init.ts +16 -4
- package/src/lib/hook_audit.ts +302 -282
- package/zcode/AGENTS.md +333 -204
|
@@ -1,557 +1,563 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""心跳台账(append-only · 有界分片轮转)守卫 —— 让「连续 N 周期无断」可严格测得。
|
|
3
|
-
|
|
4
|
-
背景(答卷 `docs/plans/灵枢1.0_最小智能系统实存答卷_v1.1.md` §八 分诊第 4 项,
|
|
5
|
-
**甲类能力缺口**;取证 `docs/eval/W7v11_结构面局限取证_v0.1.md` §丁):
|
|
6
|
-
`_sustain.jsonl` 是 heal **动作**台账(有动作才写,平静期与停摆期不可区分),心跳戳
|
|
7
|
-
是**覆盖式单点**(无历史序列)——「连续 N 周期无断」在现数据结构下**不可严格测得**。
|
|
8
|
-
补法=给心跳加 **append-only 台账**(`<root>/_heartbeat.jsonl`),配合**分片轮转+
|
|
9
|
-
保留片数上限**(有界)与**只读统计**。
|
|
10
|
-
|
|
11
|
-
断言面(每条=一个可定点变异的判据):
|
|
12
|
-
L1 **零判定变更**(硬门):台账**开/关**下,`beat()` 返回、心跳戳字段、
|
|
13
|
-
`_sustain.jsonl` 既有记录、`judge()`/`heal()`/`diagnose()` 的返回**逐位一致**
|
|
14
|
-
(依 `root`/时间戳等天然差异字段外)。
|
|
15
|
-
L2 **append-only**:台账只追加——旧字节是新内容的**前缀**,行数==写入次数,
|
|
16
|
-
历史行不被改写。
|
|
17
|
-
L3 **断点可检出**:注入一个人为断档(周期缺失 > 阈值)后,`heartbeat_ledger_stats`
|
|
18
|
-
**报出断点**且最长连续区间**缩短**。
|
|
19
|
-
L4 **有界**(硬门):超轮转阈值后分片产生、保留片数受上限约束(淘汰有痕,
|
|
20
|
-
不静默丢);`HEARTBEAT_ROTATE_BYTES=0` 为显式退回无上界开关。
|
|
21
|
-
|
|
22
|
-
运行:python -X utf8 -m md_cg.test_heartbeat_ledger
|
|
23
|
-
python -X utf8 -m md_cg.test_heartbeat_ledger --mutate # 定点变异自证
|
|
24
|
-
python -X utf8 -m md_cg.test_heartbeat_ledger --mutate --list # 只列变异表
|
|
25
|
-
|
|
26
|
-
退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
|
|
27
|
-
2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表,不得静默跳过)。
|
|
28
|
-
|
|
29
|
-
**基线纪律**:不以 git HEAD 为基线源——「改动前形态」由在当前工作区源码上做
|
|
30
|
-
**定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
|
|
31
|
-
**沙箱纪律**:库根/辅助根/状态根/心跳目录全落守卫临时目录,绝不碰在役库与 `~/.mdcg`。
|
|
32
|
-
"""
|
|
33
|
-
from __future__ import annotations
|
|
34
|
-
|
|
35
|
-
import contextlib
|
|
36
|
-
import io
|
|
37
|
-
import json
|
|
38
|
-
import os
|
|
39
|
-
import shutil
|
|
40
|
-
import sys
|
|
41
|
-
import tempfile
|
|
42
|
-
import types
|
|
43
|
-
|
|
44
|
-
from . import sustain
|
|
45
|
-
from .fsutil import read_jsonl
|
|
46
|
-
|
|
47
|
-
_PASS = []
|
|
48
|
-
_FAIL = []
|
|
49
|
-
_SRC = {} # 变异模式下的源码文本(rel → text)
|
|
50
|
-
_REAL = sustain
|
|
51
|
-
_ORIG = {n: getattr(sustain, n) for n in (
|
|
52
|
-
"HEARTBEAT_ROTATE_BYTES", "HEARTBEAT_KEEP_SHARDS", "HEARTBEAT_PROBE_EVERY",
|
|
53
|
-
"HEARTBEAT_GAP_THRESHOLD")}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def ok(cond, msg, extra=""):
|
|
57
|
-
(_PASS if cond else _FAIL).append(msg)
|
|
58
|
-
print((" PASS " if cond else " FAIL ") + msg
|
|
59
|
-
+ ((" ← " + str(extra)) if (extra and not cond) else ""))
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def _repo_root() -> str:
|
|
63
|
-
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
def _rel_text(rel: str) -> str:
|
|
67
|
-
if rel in _SRC:
|
|
68
|
-
return _SRC[rel]
|
|
69
|
-
with open(os.path.join(_repo_root(), rel), encoding="utf-8") as f:
|
|
70
|
-
return f.read()
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
# ---------------------------------------------------------------- 沙箱
|
|
74
|
-
_TMP = tempfile.mkdtemp(prefix="mdcg_hbledger_")
|
|
75
|
-
_SAVED = {}
|
|
76
|
-
_GEN = [0]
|
|
77
|
-
_ENV_KEYS = ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT", "MDCG_SUSTAIN_DIR",
|
|
78
|
-
"MDCG_HEARTBEAT_LEDGER")
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
def _sandbox_env():
|
|
82
|
-
for k in _ENV_KEYS:
|
|
83
|
-
_SAVED[k] = os.environ.get(k)
|
|
84
|
-
os.environ["MDCG_ROOT"] = os.path.join(_TMP, "cg")
|
|
85
|
-
os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP, "aux")
|
|
86
|
-
os.environ["MDCG_STATE_ROOT"] = os.path.join(_TMP, "state")
|
|
87
|
-
os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
|
|
88
|
-
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
def _restore_env():
|
|
92
|
-
for k, v in _SAVED.items():
|
|
93
|
-
if v is None:
|
|
94
|
-
os.environ.pop(k, None)
|
|
95
|
-
else:
|
|
96
|
-
os.environ[k] = v
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
def _fresh_root(tag):
|
|
100
|
-
"""每轮用**全新根**(同一根跨轮复用会读到上一轮残留而假绿)。"""
|
|
101
|
-
_GEN[0] += 1
|
|
102
|
-
root = os.path.join(_TMP, "gen%d" % _GEN[0], tag)
|
|
103
|
-
os.makedirs(root, exist_ok=True)
|
|
104
|
-
return root
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
def _netdir(tag):
|
|
108
|
-
d = os.path.join(_TMP, "net", tag)
|
|
109
|
-
os.makedirs(d, exist_ok=True)
|
|
110
|
-
return d
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
# ---------------------------------------------------------------- 投影
|
|
114
|
-
#: 天然随运行变化的字段(路径/时间戳)——零判定变更比对应**排除**它们,其余逐位比。
|
|
115
|
-
_VOLATILE = ("ts", "iso", "uptime", "t", "age", "mtime", "updated_at",
|
|
116
|
-
"last_t", "root", "path", "started_at")
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
def _strip(v):
|
|
120
|
-
if isinstance(v, dict):
|
|
121
|
-
return {k: _strip(x) for k, x in v.items() if k not in _VOLATILE}
|
|
122
|
-
if isinstance(v, list):
|
|
123
|
-
return [_strip(x) for x in v]
|
|
124
|
-
return v
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def _canon(v, root):
|
|
128
|
-
"""把该跑的库根路径归一为 <ROOT>——两跑库根不同,路径差异不算判定差异。"""
|
|
129
|
-
s = json.dumps(_strip(v), ensure_ascii=False, sort_keys=True)
|
|
130
|
-
for form in (root, root.replace(os.sep, "/")):
|
|
131
|
-
s = s.replace(json.dumps(form)[1:-1], "<ROOT>")
|
|
132
|
-
return s
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
# ---------------------------------------------------------------- G0 基线
|
|
136
|
-
def g0():
|
|
137
|
-
print("== G0 隔离与基线自证 ==")
|
|
138
|
-
S = globals()["sustain"]
|
|
139
|
-
ok(S.heartbeat_ledger_enabled() is True,
|
|
140
|
-
"G0a 缺省开:未设 MDCG_HEARTBEAT_LEDGER 时台账启用")
|
|
141
|
-
ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": off}) is False
|
|
142
|
-
for off in ("0", "false", "False")),
|
|
143
|
-
"G0b 关断字面量 0/false/False 均关(沿用 AUTO_OFF_VALUES 口径)")
|
|
144
|
-
ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": on}) is True
|
|
145
|
-
for on in ("1", "true", "", "yes")),
|
|
146
|
-
"G0c 其余值(含空串)为开——只有三个关断字面量算关")
|
|
147
|
-
ok(S.HEARTBEAT_ROTATE_BYTES > 0 and S.HEARTBEAT_KEEP_SHARDS > 0
|
|
148
|
-
and S.HEARTBEAT_PROBE_EVERY >= 1,
|
|
149
|
-
"G0d 有界参数缺省 >0(轮转开、保留片数有上限、节流步长≥1)",
|
|
150
|
-
(S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY))
|
|
151
|
-
ok(S.heartbeat_path("/x") == os.path.join("/x", S.HEARTBEAT_LOG)
|
|
152
|
-
and S.HEARTBEAT_LOG == "_heartbeat.jsonl",
|
|
153
|
-
"G0e 台账落点=<root>/_heartbeat.jsonl(与 _sustain.jsonl 同域)",
|
|
154
|
-
S.heartbeat_path("/x"))
|
|
155
|
-
ok(os.environ["MDCG_ROOT"].startswith(_TMP),
|
|
156
|
-
"G0f 沙箱:库根在守卫临时目录内(绝不碰在役库)", os.environ["MDCG_ROOT"])
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
# ---------------------------------------------------------------- L1 零判定变更
|
|
160
|
-
def _l1_scenario(root, netdir):
|
|
161
|
-
"""跑一段固定序列,返回「既有读面」的投影(台账开/关两跑须逐位一致)。"""
|
|
162
|
-
from .mdcos import MdCGOS
|
|
163
|
-
S = globals()["sustain"]
|
|
164
|
-
cg = MdCGOS(root)
|
|
165
|
-
# 造一个孤儿索引条目 → heal 必有动作 → `_sustain.jsonl` 必落一行(读面非空)。
|
|
166
|
-
cg.index["nodes"]["ghost_hb"] = {"path": "knowledge/nope/ghost_hb.md"}
|
|
167
|
-
lp = S.SustainLoop(cg, name="h1", d=netdir, beat_interval=3600.0,
|
|
168
|
-
heal_interval=3600.0, scrub_interval=3600.0,
|
|
169
|
-
evolve_interval=3600.0, tidy_interval=3600.0,
|
|
170
|
-
auto_heal=True, auto_scrub=False, auto_evolve=False,
|
|
171
|
-
auto_tidy=False)
|
|
172
|
-
recs = [lp.beat(), lp.beat(True), lp.beat(False)]
|
|
173
|
-
with open(S.stamp_path("h1", netdir), encoding="utf-8") as f:
|
|
174
|
-
stamp = json.load(f)
|
|
175
|
-
judges = [S.judge(a, interval=600.0, task_running=tr)
|
|
176
|
-
for a in (None, 0.0, 1500.0, 2100.0, 2600.0, 99999.0)
|
|
177
|
-
for tr in (False, True)]
|
|
178
|
-
hr = S.heal(cg)
|
|
179
|
-
dg = S.diagnose(cg)
|
|
180
|
-
sust = list(read_jsonl(os.path.join(root, S.SUSTAIN_LOG)))
|
|
181
|
-
return {"recs": recs, "stamp": stamp, "judges": judges, "heal": hr,
|
|
182
|
-
"diag": dg, "sustain": sust,
|
|
183
|
-
"sustain_exists": os.path.exists(os.path.join(root, S.SUSTAIN_LOG)),
|
|
184
|
-
"ledger_exists": os.path.exists(S.heartbeat_path(root)),
|
|
185
|
-
"ledger_n": len(list(read_jsonl(S.heartbeat_path(root))))}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
def l1():
|
|
189
|
-
print("== L1 零判定变更(硬门)——台账开/关读面逐位一致 ==")
|
|
190
|
-
S = globals()["sustain"]
|
|
191
|
-
r_off = _fresh_root("l1_off")
|
|
192
|
-
os.environ["MDCG_HEARTBEAT_LEDGER"] = "0"
|
|
193
|
-
off = _l1_scenario(r_off, _netdir("l1_off"))
|
|
194
|
-
r_on = _fresh_root("l1_on")
|
|
195
|
-
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None) # 缺省=开
|
|
196
|
-
on = _l1_scenario(r_on, _netdir("l1_on"))
|
|
197
|
-
|
|
198
|
-
ok(off["ledger_exists"] is False and off["ledger_n"] == 0,
|
|
199
|
-
"L1 前置:台账关时不写盘(无 _heartbeat.jsonl)")
|
|
200
|
-
ok(on["ledger_exists"] is True and on["ledger_n"] == 3,
|
|
201
|
-
"L1a 台账开时恰 3 条周期行(三次 beat)",
|
|
202
|
-
(on["ledger_exists"], on["ledger_n"]))
|
|
203
|
-
|
|
204
|
-
ok(_canon(off["recs"], r_off) == _canon(on["recs"], r_on)
|
|
205
|
-
and [set(r) for r in off["recs"]] == [set(r) for r in on["recs"]],
|
|
206
|
-
"L1b beat() 返回逐位一致(键集 + 值)——台账不改返回")
|
|
207
|
-
ok(_canon(off["stamp"], r_off) == _canon(on["stamp"], r_on)
|
|
208
|
-
and set(off["stamp"]) == set(on["stamp"]),
|
|
209
|
-
"L1c 心跳戳字段逐位一致(含进度三字段)")
|
|
210
|
-
ok(off["judges"] == on["judges"] and off["judges"],
|
|
211
|
-
"L1d judge() 返回逐位一致(12 组年龄×任务态)", off["judges"][:2])
|
|
212
|
-
ok(_canon(off["heal"], r_off) == _canon(on["heal"], r_on),
|
|
213
|
-
"L1e heal() 返回逐位一致(含 before/after 统计)")
|
|
214
|
-
ok(bool(off["heal"]["actions"]) and bool(on["heal"]["actions"]),
|
|
215
|
-
"L1e' 前置:heal 确有动作(读面非空,比对有意义)",
|
|
216
|
-
[a.get("code") for a in off["heal"]["actions"]])
|
|
217
|
-
ok(_canon(off["diag"], r_off) == _canon(on["diag"], r_on),
|
|
218
|
-
"L1f diagnose() 返回逐位一致(含 issues/stats)")
|
|
219
|
-
ok(off["sustain_exists"] and on["sustain_exists"]
|
|
220
|
-
and _canon(off["sustain"], r_off) == _canon(on["sustain"], r_on)
|
|
221
|
-
and off["sustain"],
|
|
222
|
-
"L1g _sustain.jsonl 既有记录逐位一致(台账不污染既有台账)",
|
|
223
|
-
len(off["sustain"]))
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
# ---------------------------------------------------------------- L2 append-only
|
|
227
|
-
def l2():
|
|
228
|
-
print("== L2 append-only —— 只追加,历史行不被改写 ==")
|
|
229
|
-
S = globals()["sustain"]
|
|
230
|
-
root = _fresh_root("l2")
|
|
231
|
-
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
232
|
-
saved = S.HEARTBEAT_ROTATE_BYTES
|
|
233
|
-
S.HEARTBEAT_ROTATE_BYTES = 1 << 30 # 本轮不轮转,纯 append
|
|
234
|
-
try:
|
|
235
|
-
for i in range(5):
|
|
236
|
-
S.record_heartbeat(root, "hb2", t=100.0 + i)
|
|
237
|
-
raw1 = open(S.heartbeat_path(root), "rb").read()
|
|
238
|
-
for i in range(5):
|
|
239
|
-
S.record_heartbeat(root, "hb2", t=200.0 + i)
|
|
240
|
-
raw2 = open(S.heartbeat_path(root), "rb").read()
|
|
241
|
-
|
|
242
|
-
ok(raw1 and raw2.startswith(raw1),
|
|
243
|
-
"L2 旧字节是新内容的前缀(历史行未被改写/截断)")
|
|
244
|
-
lines = [l for l in raw2.split(b"\n") if l.strip()]
|
|
245
|
-
ok(len(lines) == 10, "L2a 行数==写入次数(10)", len(lines))
|
|
246
|
-
recs = [json.loads(l) for l in lines]
|
|
247
|
-
ok([r["t"] for r in recs]
|
|
248
|
-
== [100.0 + i for i in range(5)] + [200.0 + i for i in range(5)],
|
|
249
|
-
"L2b 记录顺序==写入顺序(追加不重排)")
|
|
250
|
-
ok(all(r.get("kind") == "beat" and "pid" in r and "name" in r
|
|
251
|
-
and r.get("ok") is True for r in recs),
|
|
252
|
-
"L2c 字段齐备(t/name/pid/ok/kind)")
|
|
253
|
-
finally:
|
|
254
|
-
S.HEARTBEAT_ROTATE_BYTES = saved
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
# ---------------------------------------------------------------- L3 断点可检出
|
|
258
|
-
def l3():
|
|
259
|
-
print("== L3 断点可检出 —— 人为断档 → 报断点且最长区间缩短 ==")
|
|
260
|
-
S = globals()["sustain"]
|
|
261
|
-
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
262
|
-
saved = S.HEARTBEAT_ROTATE_BYTES
|
|
263
|
-
S.HEARTBEAT_ROTATE_BYTES = 1 << 30
|
|
264
|
-
try:
|
|
265
|
-
r_move = _fresh_root("l3_move")
|
|
266
|
-
for t in (0.0, 10.0, 20.0, 30.0, 40.0): # 全连续
|
|
267
|
-
S.record_heartbeat(r_move, "hb3", t=t)
|
|
268
|
-
r_break = _fresh_root("l3_break")
|
|
269
|
-
for t in (0.0, 10.0, 20.0, 30.0, 1000.0, 1010.0, 1020.0): # 30→1000 断档
|
|
270
|
-
S.record_heartbeat(r_break, "hb3", t=t)
|
|
271
|
-
|
|
272
|
-
a = S.heartbeat_ledger_stats(r_move, name="hb3", threshold_s=15.0)
|
|
273
|
-
b = S.heartbeat_ledger_stats(r_break, name="hb3", threshold_s=15.0)
|
|
274
|
-
ok(a["breaks"] == 0 and a["longest_s"] == 40.0,
|
|
275
|
-
"L3 连续序列:零断点、最长 40s", (a["breaks"], a["longest_s"]))
|
|
276
|
-
ok(b["breaks"] == 1 and b["segments"] == 2,
|
|
277
|
-
"L3a 注入断档后**报出断点**(breaks=1、segments=2)",
|
|
278
|
-
(b["breaks"], b["segments"]))
|
|
279
|
-
ok(b["longest_s"] == 30.0 and b["longest_s"] < a["longest_s"],
|
|
280
|
-
"L3b 最长连续区间**缩短**(40s → 30s)",
|
|
281
|
-
(a["longest_s"], b["longest_s"]))
|
|
282
|
-
ok(b["breaks_top"] and b["breaks_top"][0]["gap_s"] == 970.0,
|
|
283
|
-
"L3c 断点间隔可读数(30→1000=970s)", b["breaks_top"])
|
|
284
|
-
ok(b["last_iso"] is not None and b["last_age_s"] is not None,
|
|
285
|
-
"L3d 最近一次周期时刻可读(last_iso / last_age_s)")
|
|
286
|
-
|
|
287
|
-
r_one = _fresh_root("l3_one")
|
|
288
|
-
S.record_heartbeat(r_one, "hb3", t=5.0)
|
|
289
|
-
c = S.heartbeat_ledger_stats(r_one, name="hb3", threshold_s=15.0)
|
|
290
|
-
ok(c["n"] == 1 and c["breaks"] == 0 and c["longest_s"] == 0.0
|
|
291
|
-
and c["segments"] == 1,
|
|
292
|
-
"L3e 单条记录:零断点、最长 0s、一段")
|
|
293
|
-
d = S.heartbeat_ledger_stats(_fresh_root("l3_none"), name="hb3")
|
|
294
|
-
ok(d["absent"] is True and d["n"] == 0 and d["longest_s"] is None,
|
|
295
|
-
"L3f 无记录:absent=True(诚实不编数)")
|
|
296
|
-
finally:
|
|
297
|
-
S.HEARTBEAT_ROTATE_BYTES = saved
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
# ---------------------------------------------------------------- L4 有界
|
|
301
|
-
def l4():
|
|
302
|
-
print("== L4 有界(硬门)——分片轮转 + 保留片数上限 ==")
|
|
303
|
-
S = globals()["sustain"]
|
|
304
|
-
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
305
|
-
rot, keep, probe = (S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS,
|
|
306
|
-
S.HEARTBEAT_PROBE_EVERY)
|
|
307
|
-
S.HEARTBEAT_ROTATE_BYTES = 256
|
|
308
|
-
S.HEARTBEAT_KEEP_SHARDS = 2
|
|
309
|
-
S.HEARTBEAT_PROBE_EVERY = 1
|
|
310
|
-
try:
|
|
311
|
-
root = _fresh_root("l4")
|
|
312
|
-
pad = {"pad": "z" * 80}
|
|
313
|
-
for i in range(120):
|
|
314
|
-
S.record_heartbeat(root, "hb4", t=float(i), extra=pad)
|
|
315
|
-
shards = S._hb_shards(root)
|
|
316
|
-
ok(len(shards) == 2, "L4 分片数受 KEEP=2 约束(实际 %d)" % len(shards),
|
|
317
|
-
shards)
|
|
318
|
-
ok(len(shards) <= S.HEARTBEAT_KEEP_SHARDS,
|
|
319
|
-
"L4a 保留片数不超上限(淘汰在跑)")
|
|
320
|
-
act = os.path.getsize(S.heartbeat_path(root))
|
|
321
|
-
arc = S.heartbeat_archive_dir(root)
|
|
322
|
-
sh_bytes = sum(os.path.getsize(os.path.join(arc, n)) for n in shards)
|
|
323
|
-
slack = 512
|
|
324
|
-
ok(act <= 256 + slack,
|
|
325
|
-
"L4b 活动台账有界:%.0f ≤ 阈值 256 + 单条余量" % act, act)
|
|
326
|
-
ok(all(os.path.getsize(os.path.join(arc, n)) <= 256 + slack
|
|
327
|
-
for n in shards),
|
|
328
|
-
"L4c 每个分片有界(≤ 阈值 + 单条余量)")
|
|
329
|
-
ok(act + sh_bytes <= (2 + 1) * 256 + slack,
|
|
330
|
-
"L4d 总字节有界:%d ≤ (keep+1)×阈值 + 余量" % (act + sh_bytes),
|
|
331
|
-
act + sh_bytes)
|
|
332
|
-
|
|
333
|
-
rows = [json.loads(l) for l in
|
|
334
|
-
open(S.heartbeat_path(root), encoding="utf-8") if l.strip()]
|
|
335
|
-
marks = [r for r in rows
|
|
336
|
-
if r.get("kind") == "rotate" and r.get("pruned")]
|
|
337
|
-
ok(bool(marks) and len(marks[0]["pruned"]) >= 1,
|
|
338
|
-
"L4e 淘汰**非静默**:pruned 名单写进轮转自述行(%s)"
|
|
339
|
-
% (marks[0]["pruned"] if marks else "无"))
|
|
340
|
-
idx = S._hb_load_index(root)
|
|
341
|
-
ok(all(n in idx for n in shards) and all(n in shards for n in idx),
|
|
342
|
-
"L4f 索引与磁盘分片对齐(淘汰即摘索引,不留悬空项)")
|
|
343
|
-
|
|
344
|
-
# 显式退回无上界开关:阈值 0 → 不切分(应急/对照)
|
|
345
|
-
r0 = _fresh_root("l4_off")
|
|
346
|
-
S.HEARTBEAT_ROTATE_BYTES = 0
|
|
347
|
-
for i in range(40):
|
|
348
|
-
S.record_heartbeat(r0, "hb4", t=float(i), extra=pad)
|
|
349
|
-
ok(not S._hb_shards(r0)
|
|
350
|
-
and os.path.getsize(S.heartbeat_path(r0)) > 0,
|
|
351
|
-
"L4g HEARTBEAT_ROTATE_BYTES=0 → 不切分(显式退回无上界形态)")
|
|
352
|
-
|
|
353
|
-
# 归档目录不在 LAYERS(检索面零污染)
|
|
354
|
-
from .mdcg import LAYERS
|
|
355
|
-
ok(S.HEARTBEAT_ARCHIVE not in LAYERS,
|
|
356
|
-
"L4h 归档目录不在 LAYERS → 分片不参与节点索引")
|
|
357
|
-
finally:
|
|
358
|
-
S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY \
|
|
359
|
-
= rot, keep, probe
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
def l5():
|
|
365
|
-
"""L5 心跳的**调度源唯一**(issue #207 T1)。
|
|
366
|
-
|
|
367
|
-
开启独立心跳线程(MDCG_SUSTAIN_BEAT_THREAD)后,beat 的调度源应当**转移**
|
|
368
|
-
到该线程,而不是在 _run 与线程上**各调度一次**——叠加会让心跳与台账行数
|
|
369
|
-
按倍率翻倍,并使 status()["beats"] 这一对外读数失真。
|
|
370
|
-
|
|
371
|
-
判据是**行为**的(真跑循环数台账行),不是源码文本:同一窗口下开关开/关的
|
|
372
|
-
台账 beat 行数必须同量级;若开关开时近乎翻倍,即叠加。
|
|
373
|
-
"""
|
|
374
|
-
print("== L5 心跳调度源唯一(开关开 => 转移,不叠加)==")
|
|
375
|
-
S = globals()["sustain"]
|
|
376
|
-
import time as _t
|
|
377
|
-
|
|
378
|
-
def _count(on, interval=0.25, window=2.5):
|
|
379
|
-
os.environ["MDCG_SUSTAIN_BEAT_THREAD"] = "1" if on else "0"
|
|
380
|
-
root, netdir = _fresh_root("l5"), _netdir("l5")
|
|
381
|
-
from .mdcos import MdCGOS
|
|
382
|
-
cg = MdCGOS(root)
|
|
383
|
-
lp = S.SustainLoop(cg, name="h5", d=netdir, beat_interval=interval,
|
|
384
|
-
heal_interval=1e9, scrub_interval=1e9,
|
|
385
|
-
evolve_interval=1e9, tidy_interval=1e9,
|
|
386
|
-
sleep_interval=1e9, auto_heal=False,
|
|
387
|
-
auto_scrub=False, auto_evolve=False,
|
|
388
|
-
auto_tidy=False)
|
|
389
|
-
lp.start()
|
|
390
|
-
_t.sleep(window)
|
|
391
|
-
lp.stop(1.0)
|
|
392
|
-
hp = S.heartbeat_path(root)
|
|
393
|
-
n = 0
|
|
394
|
-
if os.path.exists(hp):
|
|
395
|
-
for line in open(hp, encoding="utf-8", errors="replace"):
|
|
396
|
-
if chr(34) + "beat" + chr(34) in line:
|
|
397
|
-
n += 1
|
|
398
|
-
return n
|
|
399
|
-
|
|
400
|
-
try:
|
|
401
|
-
off = _count(False)
|
|
402
|
-
on = _count(True)
|
|
403
|
-
finally:
|
|
404
|
-
os.environ.pop("MDCG_SUSTAIN_BEAT_THREAD", None)
|
|
405
|
-
ok(off >= 4,
|
|
406
|
-
"L5a 前置:关态窗口内确有 beat 行(否则比较空转)实际 %d" % off, off)
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
(on,
|
|
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
|
-
1, "
|
|
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
|
-
for l in
|
|
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
|
-
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""心跳台账(append-only · 有界分片轮转)守卫 —— 让「连续 N 周期无断」可严格测得。
|
|
3
|
+
|
|
4
|
+
背景(答卷 `docs/plans/灵枢1.0_最小智能系统实存答卷_v1.1.md` §八 分诊第 4 项,
|
|
5
|
+
**甲类能力缺口**;取证 `docs/eval/W7v11_结构面局限取证_v0.1.md` §丁):
|
|
6
|
+
`_sustain.jsonl` 是 heal **动作**台账(有动作才写,平静期与停摆期不可区分),心跳戳
|
|
7
|
+
是**覆盖式单点**(无历史序列)——「连续 N 周期无断」在现数据结构下**不可严格测得**。
|
|
8
|
+
补法=给心跳加 **append-only 台账**(`<root>/_heartbeat.jsonl`),配合**分片轮转+
|
|
9
|
+
保留片数上限**(有界)与**只读统计**。
|
|
10
|
+
|
|
11
|
+
断言面(每条=一个可定点变异的判据):
|
|
12
|
+
L1 **零判定变更**(硬门):台账**开/关**下,`beat()` 返回、心跳戳字段、
|
|
13
|
+
`_sustain.jsonl` 既有记录、`judge()`/`heal()`/`diagnose()` 的返回**逐位一致**
|
|
14
|
+
(依 `root`/时间戳等天然差异字段外)。
|
|
15
|
+
L2 **append-only**:台账只追加——旧字节是新内容的**前缀**,行数==写入次数,
|
|
16
|
+
历史行不被改写。
|
|
17
|
+
L3 **断点可检出**:注入一个人为断档(周期缺失 > 阈值)后,`heartbeat_ledger_stats`
|
|
18
|
+
**报出断点**且最长连续区间**缩短**。
|
|
19
|
+
L4 **有界**(硬门):超轮转阈值后分片产生、保留片数受上限约束(淘汰有痕,
|
|
20
|
+
不静默丢);`HEARTBEAT_ROTATE_BYTES=0` 为显式退回无上界开关。
|
|
21
|
+
|
|
22
|
+
运行:python -X utf8 -m md_cg.test_heartbeat_ledger
|
|
23
|
+
python -X utf8 -m md_cg.test_heartbeat_ledger --mutate # 定点变异自证
|
|
24
|
+
python -X utf8 -m md_cg.test_heartbeat_ledger --mutate --list # 只列变异表
|
|
25
|
+
|
|
26
|
+
退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
|
|
27
|
+
2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表,不得静默跳过)。
|
|
28
|
+
|
|
29
|
+
**基线纪律**:不以 git HEAD 为基线源——「改动前形态」由在当前工作区源码上做
|
|
30
|
+
**定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
|
|
31
|
+
**沙箱纪律**:库根/辅助根/状态根/心跳目录全落守卫临时目录,绝不碰在役库与 `~/.mdcg`。
|
|
32
|
+
"""
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import contextlib
|
|
36
|
+
import io
|
|
37
|
+
import json
|
|
38
|
+
import os
|
|
39
|
+
import shutil
|
|
40
|
+
import sys
|
|
41
|
+
import tempfile
|
|
42
|
+
import types
|
|
43
|
+
|
|
44
|
+
from . import sustain
|
|
45
|
+
from .fsutil import read_jsonl
|
|
46
|
+
|
|
47
|
+
_PASS = []
|
|
48
|
+
_FAIL = []
|
|
49
|
+
_SRC = {} # 变异模式下的源码文本(rel → text)
|
|
50
|
+
_REAL = sustain
|
|
51
|
+
_ORIG = {n: getattr(sustain, n) for n in (
|
|
52
|
+
"HEARTBEAT_ROTATE_BYTES", "HEARTBEAT_KEEP_SHARDS", "HEARTBEAT_PROBE_EVERY",
|
|
53
|
+
"HEARTBEAT_GAP_THRESHOLD")}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def ok(cond, msg, extra=""):
|
|
57
|
+
(_PASS if cond else _FAIL).append(msg)
|
|
58
|
+
print((" PASS " if cond else " FAIL ") + msg
|
|
59
|
+
+ ((" ← " + str(extra)) if (extra and not cond) else ""))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _repo_root() -> str:
|
|
63
|
+
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _rel_text(rel: str) -> str:
|
|
67
|
+
if rel in _SRC:
|
|
68
|
+
return _SRC[rel]
|
|
69
|
+
with open(os.path.join(_repo_root(), rel), encoding="utf-8") as f:
|
|
70
|
+
return f.read()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# ---------------------------------------------------------------- 沙箱
|
|
74
|
+
_TMP = tempfile.mkdtemp(prefix="mdcg_hbledger_")
|
|
75
|
+
_SAVED = {}
|
|
76
|
+
_GEN = [0]
|
|
77
|
+
_ENV_KEYS = ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT", "MDCG_SUSTAIN_DIR",
|
|
78
|
+
"MDCG_HEARTBEAT_LEDGER")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _sandbox_env():
|
|
82
|
+
for k in _ENV_KEYS:
|
|
83
|
+
_SAVED[k] = os.environ.get(k)
|
|
84
|
+
os.environ["MDCG_ROOT"] = os.path.join(_TMP, "cg")
|
|
85
|
+
os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP, "aux")
|
|
86
|
+
os.environ["MDCG_STATE_ROOT"] = os.path.join(_TMP, "state")
|
|
87
|
+
os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
|
|
88
|
+
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _restore_env():
|
|
92
|
+
for k, v in _SAVED.items():
|
|
93
|
+
if v is None:
|
|
94
|
+
os.environ.pop(k, None)
|
|
95
|
+
else:
|
|
96
|
+
os.environ[k] = v
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _fresh_root(tag):
|
|
100
|
+
"""每轮用**全新根**(同一根跨轮复用会读到上一轮残留而假绿)。"""
|
|
101
|
+
_GEN[0] += 1
|
|
102
|
+
root = os.path.join(_TMP, "gen%d" % _GEN[0], tag)
|
|
103
|
+
os.makedirs(root, exist_ok=True)
|
|
104
|
+
return root
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _netdir(tag):
|
|
108
|
+
d = os.path.join(_TMP, "net", tag)
|
|
109
|
+
os.makedirs(d, exist_ok=True)
|
|
110
|
+
return d
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# ---------------------------------------------------------------- 投影
|
|
114
|
+
#: 天然随运行变化的字段(路径/时间戳)——零判定变更比对应**排除**它们,其余逐位比。
|
|
115
|
+
_VOLATILE = ("ts", "iso", "uptime", "t", "age", "mtime", "updated_at",
|
|
116
|
+
"last_t", "root", "path", "started_at")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _strip(v):
|
|
120
|
+
if isinstance(v, dict):
|
|
121
|
+
return {k: _strip(x) for k, x in v.items() if k not in _VOLATILE}
|
|
122
|
+
if isinstance(v, list):
|
|
123
|
+
return [_strip(x) for x in v]
|
|
124
|
+
return v
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _canon(v, root):
|
|
128
|
+
"""把该跑的库根路径归一为 <ROOT>——两跑库根不同,路径差异不算判定差异。"""
|
|
129
|
+
s = json.dumps(_strip(v), ensure_ascii=False, sort_keys=True)
|
|
130
|
+
for form in (root, root.replace(os.sep, "/")):
|
|
131
|
+
s = s.replace(json.dumps(form)[1:-1], "<ROOT>")
|
|
132
|
+
return s
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------------------------------------------------------------- G0 基线
|
|
136
|
+
def g0():
|
|
137
|
+
print("== G0 隔离与基线自证 ==")
|
|
138
|
+
S = globals()["sustain"]
|
|
139
|
+
ok(S.heartbeat_ledger_enabled() is True,
|
|
140
|
+
"G0a 缺省开:未设 MDCG_HEARTBEAT_LEDGER 时台账启用")
|
|
141
|
+
ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": off}) is False
|
|
142
|
+
for off in ("0", "false", "False")),
|
|
143
|
+
"G0b 关断字面量 0/false/False 均关(沿用 AUTO_OFF_VALUES 口径)")
|
|
144
|
+
ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": on}) is True
|
|
145
|
+
for on in ("1", "true", "", "yes")),
|
|
146
|
+
"G0c 其余值(含空串)为开——只有三个关断字面量算关")
|
|
147
|
+
ok(S.HEARTBEAT_ROTATE_BYTES > 0 and S.HEARTBEAT_KEEP_SHARDS > 0
|
|
148
|
+
and S.HEARTBEAT_PROBE_EVERY >= 1,
|
|
149
|
+
"G0d 有界参数缺省 >0(轮转开、保留片数有上限、节流步长≥1)",
|
|
150
|
+
(S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY))
|
|
151
|
+
ok(S.heartbeat_path("/x") == os.path.join("/x", S.HEARTBEAT_LOG)
|
|
152
|
+
and S.HEARTBEAT_LOG == "_heartbeat.jsonl",
|
|
153
|
+
"G0e 台账落点=<root>/_heartbeat.jsonl(与 _sustain.jsonl 同域)",
|
|
154
|
+
S.heartbeat_path("/x"))
|
|
155
|
+
ok(os.environ["MDCG_ROOT"].startswith(_TMP),
|
|
156
|
+
"G0f 沙箱:库根在守卫临时目录内(绝不碰在役库)", os.environ["MDCG_ROOT"])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# ---------------------------------------------------------------- L1 零判定变更
|
|
160
|
+
def _l1_scenario(root, netdir):
|
|
161
|
+
"""跑一段固定序列,返回「既有读面」的投影(台账开/关两跑须逐位一致)。"""
|
|
162
|
+
from .mdcos import MdCGOS
|
|
163
|
+
S = globals()["sustain"]
|
|
164
|
+
cg = MdCGOS(root)
|
|
165
|
+
# 造一个孤儿索引条目 → heal 必有动作 → `_sustain.jsonl` 必落一行(读面非空)。
|
|
166
|
+
cg.index["nodes"]["ghost_hb"] = {"path": "knowledge/nope/ghost_hb.md"}
|
|
167
|
+
lp = S.SustainLoop(cg, name="h1", d=netdir, beat_interval=3600.0,
|
|
168
|
+
heal_interval=3600.0, scrub_interval=3600.0,
|
|
169
|
+
evolve_interval=3600.0, tidy_interval=3600.0,
|
|
170
|
+
auto_heal=True, auto_scrub=False, auto_evolve=False,
|
|
171
|
+
auto_tidy=False)
|
|
172
|
+
recs = [lp.beat(), lp.beat(True), lp.beat(False)]
|
|
173
|
+
with open(S.stamp_path("h1", netdir), encoding="utf-8") as f:
|
|
174
|
+
stamp = json.load(f)
|
|
175
|
+
judges = [S.judge(a, interval=600.0, task_running=tr)
|
|
176
|
+
for a in (None, 0.0, 1500.0, 2100.0, 2600.0, 99999.0)
|
|
177
|
+
for tr in (False, True)]
|
|
178
|
+
hr = S.heal(cg)
|
|
179
|
+
dg = S.diagnose(cg)
|
|
180
|
+
sust = list(read_jsonl(os.path.join(root, S.SUSTAIN_LOG)))
|
|
181
|
+
return {"recs": recs, "stamp": stamp, "judges": judges, "heal": hr,
|
|
182
|
+
"diag": dg, "sustain": sust,
|
|
183
|
+
"sustain_exists": os.path.exists(os.path.join(root, S.SUSTAIN_LOG)),
|
|
184
|
+
"ledger_exists": os.path.exists(S.heartbeat_path(root)),
|
|
185
|
+
"ledger_n": len(list(read_jsonl(S.heartbeat_path(root))))}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def l1():
|
|
189
|
+
print("== L1 零判定变更(硬门)——台账开/关读面逐位一致 ==")
|
|
190
|
+
S = globals()["sustain"]
|
|
191
|
+
r_off = _fresh_root("l1_off")
|
|
192
|
+
os.environ["MDCG_HEARTBEAT_LEDGER"] = "0"
|
|
193
|
+
off = _l1_scenario(r_off, _netdir("l1_off"))
|
|
194
|
+
r_on = _fresh_root("l1_on")
|
|
195
|
+
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None) # 缺省=开
|
|
196
|
+
on = _l1_scenario(r_on, _netdir("l1_on"))
|
|
197
|
+
|
|
198
|
+
ok(off["ledger_exists"] is False and off["ledger_n"] == 0,
|
|
199
|
+
"L1 前置:台账关时不写盘(无 _heartbeat.jsonl)")
|
|
200
|
+
ok(on["ledger_exists"] is True and on["ledger_n"] == 3,
|
|
201
|
+
"L1a 台账开时恰 3 条周期行(三次 beat)",
|
|
202
|
+
(on["ledger_exists"], on["ledger_n"]))
|
|
203
|
+
|
|
204
|
+
ok(_canon(off["recs"], r_off) == _canon(on["recs"], r_on)
|
|
205
|
+
and [set(r) for r in off["recs"]] == [set(r) for r in on["recs"]],
|
|
206
|
+
"L1b beat() 返回逐位一致(键集 + 值)——台账不改返回")
|
|
207
|
+
ok(_canon(off["stamp"], r_off) == _canon(on["stamp"], r_on)
|
|
208
|
+
and set(off["stamp"]) == set(on["stamp"]),
|
|
209
|
+
"L1c 心跳戳字段逐位一致(含进度三字段)")
|
|
210
|
+
ok(off["judges"] == on["judges"] and off["judges"],
|
|
211
|
+
"L1d judge() 返回逐位一致(12 组年龄×任务态)", off["judges"][:2])
|
|
212
|
+
ok(_canon(off["heal"], r_off) == _canon(on["heal"], r_on),
|
|
213
|
+
"L1e heal() 返回逐位一致(含 before/after 统计)")
|
|
214
|
+
ok(bool(off["heal"]["actions"]) and bool(on["heal"]["actions"]),
|
|
215
|
+
"L1e' 前置:heal 确有动作(读面非空,比对有意义)",
|
|
216
|
+
[a.get("code") for a in off["heal"]["actions"]])
|
|
217
|
+
ok(_canon(off["diag"], r_off) == _canon(on["diag"], r_on),
|
|
218
|
+
"L1f diagnose() 返回逐位一致(含 issues/stats)")
|
|
219
|
+
ok(off["sustain_exists"] and on["sustain_exists"]
|
|
220
|
+
and _canon(off["sustain"], r_off) == _canon(on["sustain"], r_on)
|
|
221
|
+
and off["sustain"],
|
|
222
|
+
"L1g _sustain.jsonl 既有记录逐位一致(台账不污染既有台账)",
|
|
223
|
+
len(off["sustain"]))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# ---------------------------------------------------------------- L2 append-only
|
|
227
|
+
def l2():
|
|
228
|
+
print("== L2 append-only —— 只追加,历史行不被改写 ==")
|
|
229
|
+
S = globals()["sustain"]
|
|
230
|
+
root = _fresh_root("l2")
|
|
231
|
+
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
232
|
+
saved = S.HEARTBEAT_ROTATE_BYTES
|
|
233
|
+
S.HEARTBEAT_ROTATE_BYTES = 1 << 30 # 本轮不轮转,纯 append
|
|
234
|
+
try:
|
|
235
|
+
for i in range(5):
|
|
236
|
+
S.record_heartbeat(root, "hb2", t=100.0 + i)
|
|
237
|
+
raw1 = open(S.heartbeat_path(root), "rb").read()
|
|
238
|
+
for i in range(5):
|
|
239
|
+
S.record_heartbeat(root, "hb2", t=200.0 + i)
|
|
240
|
+
raw2 = open(S.heartbeat_path(root), "rb").read()
|
|
241
|
+
|
|
242
|
+
ok(raw1 and raw2.startswith(raw1),
|
|
243
|
+
"L2 旧字节是新内容的前缀(历史行未被改写/截断)")
|
|
244
|
+
lines = [l for l in raw2.split(b"\n") if l.strip()]
|
|
245
|
+
ok(len(lines) == 10, "L2a 行数==写入次数(10)", len(lines))
|
|
246
|
+
recs = [json.loads(l) for l in lines]
|
|
247
|
+
ok([r["t"] for r in recs]
|
|
248
|
+
== [100.0 + i for i in range(5)] + [200.0 + i for i in range(5)],
|
|
249
|
+
"L2b 记录顺序==写入顺序(追加不重排)")
|
|
250
|
+
ok(all(r.get("kind") == "beat" and "pid" in r and "name" in r
|
|
251
|
+
and r.get("ok") is True for r in recs),
|
|
252
|
+
"L2c 字段齐备(t/name/pid/ok/kind)")
|
|
253
|
+
finally:
|
|
254
|
+
S.HEARTBEAT_ROTATE_BYTES = saved
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# ---------------------------------------------------------------- L3 断点可检出
|
|
258
|
+
def l3():
|
|
259
|
+
print("== L3 断点可检出 —— 人为断档 → 报断点且最长区间缩短 ==")
|
|
260
|
+
S = globals()["sustain"]
|
|
261
|
+
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
262
|
+
saved = S.HEARTBEAT_ROTATE_BYTES
|
|
263
|
+
S.HEARTBEAT_ROTATE_BYTES = 1 << 30
|
|
264
|
+
try:
|
|
265
|
+
r_move = _fresh_root("l3_move")
|
|
266
|
+
for t in (0.0, 10.0, 20.0, 30.0, 40.0): # 全连续
|
|
267
|
+
S.record_heartbeat(r_move, "hb3", t=t)
|
|
268
|
+
r_break = _fresh_root("l3_break")
|
|
269
|
+
for t in (0.0, 10.0, 20.0, 30.0, 1000.0, 1010.0, 1020.0): # 30→1000 断档
|
|
270
|
+
S.record_heartbeat(r_break, "hb3", t=t)
|
|
271
|
+
|
|
272
|
+
a = S.heartbeat_ledger_stats(r_move, name="hb3", threshold_s=15.0)
|
|
273
|
+
b = S.heartbeat_ledger_stats(r_break, name="hb3", threshold_s=15.0)
|
|
274
|
+
ok(a["breaks"] == 0 and a["longest_s"] == 40.0,
|
|
275
|
+
"L3 连续序列:零断点、最长 40s", (a["breaks"], a["longest_s"]))
|
|
276
|
+
ok(b["breaks"] == 1 and b["segments"] == 2,
|
|
277
|
+
"L3a 注入断档后**报出断点**(breaks=1、segments=2)",
|
|
278
|
+
(b["breaks"], b["segments"]))
|
|
279
|
+
ok(b["longest_s"] == 30.0 and b["longest_s"] < a["longest_s"],
|
|
280
|
+
"L3b 最长连续区间**缩短**(40s → 30s)",
|
|
281
|
+
(a["longest_s"], b["longest_s"]))
|
|
282
|
+
ok(b["breaks_top"] and b["breaks_top"][0]["gap_s"] == 970.0,
|
|
283
|
+
"L3c 断点间隔可读数(30→1000=970s)", b["breaks_top"])
|
|
284
|
+
ok(b["last_iso"] is not None and b["last_age_s"] is not None,
|
|
285
|
+
"L3d 最近一次周期时刻可读(last_iso / last_age_s)")
|
|
286
|
+
|
|
287
|
+
r_one = _fresh_root("l3_one")
|
|
288
|
+
S.record_heartbeat(r_one, "hb3", t=5.0)
|
|
289
|
+
c = S.heartbeat_ledger_stats(r_one, name="hb3", threshold_s=15.0)
|
|
290
|
+
ok(c["n"] == 1 and c["breaks"] == 0 and c["longest_s"] == 0.0
|
|
291
|
+
and c["segments"] == 1,
|
|
292
|
+
"L3e 单条记录:零断点、最长 0s、一段")
|
|
293
|
+
d = S.heartbeat_ledger_stats(_fresh_root("l3_none"), name="hb3")
|
|
294
|
+
ok(d["absent"] is True and d["n"] == 0 and d["longest_s"] is None,
|
|
295
|
+
"L3f 无记录:absent=True(诚实不编数)")
|
|
296
|
+
finally:
|
|
297
|
+
S.HEARTBEAT_ROTATE_BYTES = saved
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# ---------------------------------------------------------------- L4 有界
|
|
301
|
+
def l4():
|
|
302
|
+
print("== L4 有界(硬门)——分片轮转 + 保留片数上限 ==")
|
|
303
|
+
S = globals()["sustain"]
|
|
304
|
+
os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
|
|
305
|
+
rot, keep, probe = (S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS,
|
|
306
|
+
S.HEARTBEAT_PROBE_EVERY)
|
|
307
|
+
S.HEARTBEAT_ROTATE_BYTES = 256
|
|
308
|
+
S.HEARTBEAT_KEEP_SHARDS = 2
|
|
309
|
+
S.HEARTBEAT_PROBE_EVERY = 1
|
|
310
|
+
try:
|
|
311
|
+
root = _fresh_root("l4")
|
|
312
|
+
pad = {"pad": "z" * 80}
|
|
313
|
+
for i in range(120):
|
|
314
|
+
S.record_heartbeat(root, "hb4", t=float(i), extra=pad)
|
|
315
|
+
shards = S._hb_shards(root)
|
|
316
|
+
ok(len(shards) == 2, "L4 分片数受 KEEP=2 约束(实际 %d)" % len(shards),
|
|
317
|
+
shards)
|
|
318
|
+
ok(len(shards) <= S.HEARTBEAT_KEEP_SHARDS,
|
|
319
|
+
"L4a 保留片数不超上限(淘汰在跑)")
|
|
320
|
+
act = os.path.getsize(S.heartbeat_path(root))
|
|
321
|
+
arc = S.heartbeat_archive_dir(root)
|
|
322
|
+
sh_bytes = sum(os.path.getsize(os.path.join(arc, n)) for n in shards)
|
|
323
|
+
slack = 512
|
|
324
|
+
ok(act <= 256 + slack,
|
|
325
|
+
"L4b 活动台账有界:%.0f ≤ 阈值 256 + 单条余量" % act, act)
|
|
326
|
+
ok(all(os.path.getsize(os.path.join(arc, n)) <= 256 + slack
|
|
327
|
+
for n in shards),
|
|
328
|
+
"L4c 每个分片有界(≤ 阈值 + 单条余量)")
|
|
329
|
+
ok(act + sh_bytes <= (2 + 1) * 256 + slack,
|
|
330
|
+
"L4d 总字节有界:%d ≤ (keep+1)×阈值 + 余量" % (act + sh_bytes),
|
|
331
|
+
act + sh_bytes)
|
|
332
|
+
|
|
333
|
+
rows = [json.loads(l) for l in
|
|
334
|
+
open(S.heartbeat_path(root), encoding="utf-8") if l.strip()]
|
|
335
|
+
marks = [r for r in rows
|
|
336
|
+
if r.get("kind") == "rotate" and r.get("pruned")]
|
|
337
|
+
ok(bool(marks) and len(marks[0]["pruned"]) >= 1,
|
|
338
|
+
"L4e 淘汰**非静默**:pruned 名单写进轮转自述行(%s)"
|
|
339
|
+
% (marks[0]["pruned"] if marks else "无"))
|
|
340
|
+
idx = S._hb_load_index(root)
|
|
341
|
+
ok(all(n in idx for n in shards) and all(n in shards for n in idx),
|
|
342
|
+
"L4f 索引与磁盘分片对齐(淘汰即摘索引,不留悬空项)")
|
|
343
|
+
|
|
344
|
+
# 显式退回无上界开关:阈值 0 → 不切分(应急/对照)
|
|
345
|
+
r0 = _fresh_root("l4_off")
|
|
346
|
+
S.HEARTBEAT_ROTATE_BYTES = 0
|
|
347
|
+
for i in range(40):
|
|
348
|
+
S.record_heartbeat(r0, "hb4", t=float(i), extra=pad)
|
|
349
|
+
ok(not S._hb_shards(r0)
|
|
350
|
+
and os.path.getsize(S.heartbeat_path(r0)) > 0,
|
|
351
|
+
"L4g HEARTBEAT_ROTATE_BYTES=0 → 不切分(显式退回无上界形态)")
|
|
352
|
+
|
|
353
|
+
# 归档目录不在 LAYERS(检索面零污染)
|
|
354
|
+
from .mdcg import LAYERS
|
|
355
|
+
ok(S.HEARTBEAT_ARCHIVE not in LAYERS,
|
|
356
|
+
"L4h 归档目录不在 LAYERS → 分片不参与节点索引")
|
|
357
|
+
finally:
|
|
358
|
+
S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY \
|
|
359
|
+
= rot, keep, probe
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def l5():
|
|
365
|
+
"""L5 心跳的**调度源唯一**(issue #207 T1)。
|
|
366
|
+
|
|
367
|
+
开启独立心跳线程(MDCG_SUSTAIN_BEAT_THREAD)后,beat 的调度源应当**转移**
|
|
368
|
+
到该线程,而不是在 _run 与线程上**各调度一次**——叠加会让心跳与台账行数
|
|
369
|
+
按倍率翻倍,并使 status()["beats"] 这一对外读数失真。
|
|
370
|
+
|
|
371
|
+
判据是**行为**的(真跑循环数台账行),不是源码文本:同一窗口下开关开/关的
|
|
372
|
+
台账 beat 行数必须同量级;若开关开时近乎翻倍,即叠加。
|
|
373
|
+
"""
|
|
374
|
+
print("== L5 心跳调度源唯一(开关开 => 转移,不叠加)==")
|
|
375
|
+
S = globals()["sustain"]
|
|
376
|
+
import time as _t
|
|
377
|
+
|
|
378
|
+
def _count(on, interval=0.25, window=2.5):
|
|
379
|
+
os.environ["MDCG_SUSTAIN_BEAT_THREAD"] = "1" if on else "0"
|
|
380
|
+
root, netdir = _fresh_root("l5"), _netdir("l5")
|
|
381
|
+
from .mdcos import MdCGOS
|
|
382
|
+
cg = MdCGOS(root)
|
|
383
|
+
lp = S.SustainLoop(cg, name="h5", d=netdir, beat_interval=interval,
|
|
384
|
+
heal_interval=1e9, scrub_interval=1e9,
|
|
385
|
+
evolve_interval=1e9, tidy_interval=1e9,
|
|
386
|
+
sleep_interval=1e9, auto_heal=False,
|
|
387
|
+
auto_scrub=False, auto_evolve=False,
|
|
388
|
+
auto_tidy=False)
|
|
389
|
+
lp.start()
|
|
390
|
+
_t.sleep(window)
|
|
391
|
+
lp.stop(1.0)
|
|
392
|
+
hp = S.heartbeat_path(root)
|
|
393
|
+
n = 0
|
|
394
|
+
if os.path.exists(hp):
|
|
395
|
+
for line in open(hp, encoding="utf-8", errors="replace"):
|
|
396
|
+
if chr(34) + "beat" + chr(34) in line:
|
|
397
|
+
n += 1
|
|
398
|
+
return n
|
|
399
|
+
|
|
400
|
+
try:
|
|
401
|
+
off = _count(False)
|
|
402
|
+
on = _count(True)
|
|
403
|
+
finally:
|
|
404
|
+
os.environ.pop("MDCG_SUSTAIN_BEAT_THREAD", None)
|
|
405
|
+
ok(off >= 4,
|
|
406
|
+
"L5a 前置:关态窗口内确有 beat 行(否则比较空转)实际 %d" % off, off)
|
|
407
|
+
# issue #573:原判据用「开/关倍率 ≤1.6x」,但**关态跑在主循环上**(忙时少几拍,实测 6~7),
|
|
408
|
+
# 而开态由独立线程驱动 ≈ 窗口/间隔 = 10 拍 ⇒ 倍率在 1.43~1.67 间抖动,机器快慢决定红绿。
|
|
409
|
+
# 改为按「理论上限」与「叠加≈2×」两条判据:真叠加会产生 ~20 拍,与关态快慢无关。
|
|
410
|
+
exp = int(2.5 / 0.25) # 理论拍数(窗口 2.5s / 间隔 0.25s = 10)
|
|
411
|
+
ok(on <= exp + 1,
|
|
412
|
+
"L5b 开态不超理论上限:开=%d ≤ %d+1(窗口/间隔)" % (on, exp), (on, exp))
|
|
413
|
+
ok(on <= off * 2.2,
|
|
414
|
+
"L5b2 未出现两路叠加:开=%d 关=%d(真叠加应≈2 倍以上;关态跑主循环,忙时少拍属正常)"
|
|
415
|
+
% (on, off), (on, off))
|
|
416
|
+
ok(on >= off * 0.6,
|
|
417
|
+
"L5c 开态心跳**仍在推进**(未被误关掉):开=%d 关=%d" % (on, off),
|
|
418
|
+
(on, off))
|
|
419
|
+
|
|
420
|
+
_GROUPS = (g0, l1, l2, l3, l4, l5)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
# ---------------------------------------------------------------- 变异表
|
|
424
|
+
# 锚点 = (名字, kind, rel, old, new, 预期红项数下限, 预期命中的红项子串)。
|
|
425
|
+
# kind="mod":改**可执行实现**(exec 成模块并换进 sys.modules,供 `from .` 面读到)
|
|
426
|
+
_MUTATIONS = (
|
|
427
|
+
("M1 台账写入退化为覆盖式(非 append)", "mod", "md_cg/sustain.py",
|
|
428
|
+
" append_jsonl(heartbeat_path(root), row)\n",
|
|
429
|
+
' open(heartbeat_path(root), "w", encoding="utf-8").write('
|
|
430
|
+
'json.dumps(row, ensure_ascii=False) + "\\n")\n',
|
|
431
|
+
1, "L2"),
|
|
432
|
+
("M2 断点不可检出(阈值设为不可达)", "mod", "md_cg/sustain.py",
|
|
433
|
+
" if t - prev > threshold_s:",
|
|
434
|
+
" if t - prev > 1e300:",
|
|
435
|
+
1, "L3"),
|
|
436
|
+
("M3 关闭轮转(有界性消失)", "mod", "md_cg/sustain.py",
|
|
437
|
+
" limit = HEARTBEAT_ROTATE_BYTES\n if limit <= 0:\n return",
|
|
438
|
+
" limit = HEARTBEAT_ROTATE_BYTES\n if limit <= 0 or True:\n return",
|
|
439
|
+
1, "L4"),
|
|
440
|
+
("M4 关闭淘汰(分片无上界增长)", "mod", "md_cg/sustain.py",
|
|
441
|
+
" keep = HEARTBEAT_KEEP_SHARDS\n if keep <= 0:\n return []",
|
|
442
|
+
" keep = HEARTBEAT_KEEP_SHARDS\n if keep <= 0 or True:\n return []",
|
|
443
|
+
1, "L4"),
|
|
444
|
+
("M5 台账污染既有 _sustain.jsonl(判定变更)", "mod", "md_cg/sustain.py",
|
|
445
|
+
" append_jsonl(heartbeat_path(root), row)\n",
|
|
446
|
+
" append_jsonl(heartbeat_path(root), row)\n"
|
|
447
|
+
" append_jsonl(os.path.join(root, SUSTAIN_LOG),"
|
|
448
|
+
' {"t": row["t"], "op": "hb_probe"})\n',
|
|
449
|
+
1, "L1"),
|
|
450
|
+
("M6 beat 调度源叠加(开关开时 _run 仍自行调度)", "mod",
|
|
451
|
+
"md_cg/sustain.py",
|
|
452
|
+
" if own_beat and now >= next_beat:",
|
|
453
|
+
" if now >= next_beat:",
|
|
454
|
+
1, "L5"),
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _run_groups() -> int:
|
|
459
|
+
_PASS.clear()
|
|
460
|
+
_FAIL.clear()
|
|
461
|
+
for g in _GROUPS:
|
|
462
|
+
try:
|
|
463
|
+
g()
|
|
464
|
+
except Exception as exc: # noqa: BLE001
|
|
465
|
+
ok(False, "断言组 %s 抛异常:%s" % (g.__name__, exc))
|
|
466
|
+
import traceback
|
|
467
|
+
print(traceback.format_exc()[-800:])
|
|
468
|
+
for mod in (globals().get("sustain"), _REAL):
|
|
469
|
+
try:
|
|
470
|
+
mod.stop_all()
|
|
471
|
+
except Exception: # noqa: BLE001
|
|
472
|
+
pass
|
|
473
|
+
return len(_FAIL)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _exec_module(name, rel, text):
|
|
477
|
+
"""把变异源码 exec 进**模块自身的 __dict__**——使函数的 __globals__ 就是
|
|
478
|
+
该模块 dict,从而 l2/l3/l4 的常量补丁(如 HEARTBEAT_ROTATE_BYTES)对变异
|
|
479
|
+
模块同样生效(否则补丁落到副本、函数仍读旧值,会假红 L4)。"""
|
|
480
|
+
m = types.ModuleType(name)
|
|
481
|
+
m.__file__ = os.path.join(_repo_root(), rel)
|
|
482
|
+
m.__package__ = "md_cg"
|
|
483
|
+
exec(compile(text, rel, "exec"), m.__dict__) # noqa: S102 —— 基线自证
|
|
484
|
+
return m
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _mutate_mode(list_only: bool = False) -> int:
|
|
488
|
+
print("!! 定点变异自证:逐条注入退化,套件必须转红且打中预期判据\n")
|
|
489
|
+
if list_only:
|
|
490
|
+
for name, kind, rel, _o, _n, exp, label in _MUTATIONS:
|
|
491
|
+
print(" %-44s [%s] expect_red>=%d hit~%s (%s)"
|
|
492
|
+
% (name, kind, exp, label, rel))
|
|
493
|
+
return 0
|
|
494
|
+
anchor_miss, bad = [], []
|
|
495
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
496
|
+
clean = _run_groups()
|
|
497
|
+
print(" 未变异基线:失败=%d(必须为 0)" % clean)
|
|
498
|
+
if clean:
|
|
499
|
+
bad.append("未变异基线即失败")
|
|
500
|
+
|
|
501
|
+
for name, kind, rel, old, new, expect, label in _MUTATIONS:
|
|
502
|
+
src = _rel_text(rel)
|
|
503
|
+
if old not in src:
|
|
504
|
+
print(" ANCHOR-MISS %s —— 锚点在 %s 找不到(实现改了却没同步本表)"
|
|
505
|
+
% (name, rel))
|
|
506
|
+
anchor_miss.append(name)
|
|
507
|
+
continue
|
|
508
|
+
_SRC[rel] = src.replace(old, new, 1)
|
|
509
|
+
live = None
|
|
510
|
+
try:
|
|
511
|
+
if kind == "mod":
|
|
512
|
+
live = sys.modules["md_cg.sustain"]
|
|
513
|
+
mut = _exec_module("md_cg._hb_mut", rel, _SRC[rel])
|
|
514
|
+
sys.modules["md_cg.sustain"] = mut
|
|
515
|
+
globals()["sustain"] = mut
|
|
516
|
+
with contextlib.redirect_stdout(buf := io.StringIO()):
|
|
517
|
+
reds = _run_groups()
|
|
518
|
+
detail = buf.getvalue()
|
|
519
|
+
finally:
|
|
520
|
+
if live is not None:
|
|
521
|
+
sys.modules["md_cg.sustain"] = live
|
|
522
|
+
globals()["sustain"] = _REAL
|
|
523
|
+
_SRC.pop(rel, None)
|
|
524
|
+
red_lines = [l.strip() for l in detail.splitlines()
|
|
525
|
+
if l.strip().startswith("FAIL ")]
|
|
526
|
+
hit = any(label in l for l in red_lines)
|
|
527
|
+
mark = "OK " if (reds >= expect and hit) else "MISMATCH"
|
|
528
|
+
print(" %s %-44s 红项=%d 预期>=%d 命中%s=%s"
|
|
529
|
+
% (mark, name, reds, expect, label, "是" if hit else "**否**"))
|
|
530
|
+
for l in red_lines[:4]:
|
|
531
|
+
print(" " + l[5:])
|
|
532
|
+
if reds < expect or not hit:
|
|
533
|
+
bad.append("%s(红=%d 预期>=%d,命中%s=%s)"
|
|
534
|
+
% (name, reds, expect, label, hit))
|
|
535
|
+
|
|
536
|
+
if anchor_miss:
|
|
537
|
+
print("\nANCHOR-MISS:%s" % "、".join(anchor_miss))
|
|
538
|
+
print("退出码 2(fail-closed):变异表锚点漂移即判失败,不得静默跳过")
|
|
539
|
+
return 2
|
|
540
|
+
print("\n定点变异自证:%s"
|
|
541
|
+
% ("PASS(每处判据都被打红)" if not bad else "FAIL —— " + "、".join(bad)))
|
|
542
|
+
return 0 if not bad else 1
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def main() -> int:
|
|
546
|
+
_sandbox_env()
|
|
547
|
+
try:
|
|
548
|
+
if "--mutate" in sys.argv:
|
|
549
|
+
return _mutate_mode("--list" in sys.argv)
|
|
550
|
+
n = _run_groups()
|
|
551
|
+
print("\n心跳台账守卫:%d 通过,%d 失败" % (len(_PASS), n))
|
|
552
|
+
return 0 if not n else 1
|
|
553
|
+
finally:
|
|
554
|
+
try:
|
|
555
|
+
_REAL.stop_all()
|
|
556
|
+
except Exception: # noqa: BLE001
|
|
557
|
+
pass
|
|
558
|
+
_restore_env()
|
|
559
|
+
shutil.rmtree(_TMP, ignore_errors=True)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
if __name__ == "__main__":
|
|
563
|
+
sys.exit(main())
|