@furongjun1999/dsh-memory 0.9.6 → 0.9.7

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.
Files changed (216) hide show
  1. package/data/policy.json +38 -38
  2. package/docs/discipline/templates/spec.txt.tmpl +1 -1
  3. package/dsh/cordis.yml.example +139 -139
  4. package/lib/hooks.d.ts +19 -0
  5. package/lib/hooks.js +29 -6
  6. package/lib/index.js +11 -2
  7. package/lib/lib/hook_audit.js +38 -2
  8. package/lib/lib/prompt_safety.js +14 -3
  9. package/lib/tools.d.ts +7 -0
  10. package/lib/tools.js +22 -1
  11. package/md_cg/_guard_kit.py +121 -121
  12. package/md_cg/anchor.py +114 -114
  13. package/md_cg/audit.py +15 -2
  14. package/md_cg/chain.py +3 -2
  15. package/md_cg/config_registry_guard.py +487 -487
  16. package/md_cg/conformance.py +747 -747
  17. package/md_cg/consolidate.py +1793 -1793
  18. package/md_cg/crypto.py +794 -794
  19. package/md_cg/hyperedge.py +262 -262
  20. package/md_cg/interface_schema.py +146 -146
  21. package/md_cg/lifecycle.py +426 -426
  22. package/md_cg/mdcos.py +12 -8
  23. package/md_cg/predict.py +1103 -1103
  24. package/md_cg/protect.py +654 -654
  25. package/md_cg/provenance.py +606 -606
  26. package/md_cg/queue_health.py +130 -130
  27. package/md_cg/refine.py +613 -613
  28. package/md_cg/retrieve.py +128 -128
  29. package/md_cg/revise.py +140 -140
  30. package/md_cg/rollback.py +657 -657
  31. package/md_cg/rollback_cli.py +124 -124
  32. package/md_cg/rotate.py +346 -346
  33. package/md_cg/routing.py +490 -490
  34. package/md_cg/self_surface.py +50 -50
  35. package/md_cg/semantic/canonical.py +144 -144
  36. package/md_cg/semantic/zh_en_atoms.py +141 -141
  37. package/md_cg/sources.py +1091 -1091
  38. package/md_cg/stg.py +3 -2
  39. package/md_cg/test_audit_rotate_parity.py +279 -279
  40. package/md_cg/test_autonomy_modes.py +2013 -2013
  41. package/md_cg/test_cn_recall_grams.py +206 -206
  42. package/md_cg/test_code_kind_forbidden.py +101 -0
  43. package/md_cg/test_condaccept.py +156 -156
  44. package/md_cg/test_condgate.py +141 -141
  45. package/md_cg/test_heartbeat_ledger.py +557 -557
  46. package/md_cg/test_i50e_readside_protection.py +658 -658
  47. package/md_cg/test_issue111_gate_order.py +76 -76
  48. package/md_cg/test_issue111_scoring_contract.py +86 -86
  49. package/md_cg/test_issue121_calibration_bounds.py +293 -293
  50. package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
  51. package/md_cg/test_issue147_pack_id_escape.py +378 -378
  52. package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
  53. package/md_cg/test_issue149_accel_default_face.py +248 -248
  54. package/md_cg/test_issue150_empty_query_terms.py +328 -328
  55. package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
  56. package/md_cg/test_issue152_sealed_postings.py +309 -309
  57. package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
  58. package/md_cg/test_issue157b_index_remainder.py +344 -344
  59. package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
  60. package/md_cg/test_issue191_import_trust.py +382 -382
  61. package/md_cg/test_issue193_write_scope.py +378 -378
  62. package/md_cg/test_issue212_writeface_gaps.py +349 -349
  63. package/md_cg/test_issue214_reject_sensitivity.py +266 -266
  64. package/md_cg/test_issue215_condition_source_gap.py +272 -272
  65. package/md_cg/test_issue216_clash_routes.py +214 -214
  66. package/md_cg/test_issue217_slot_routes.py +248 -248
  67. package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
  68. package/md_cg/test_issue258_pack_sensitivity.py +468 -468
  69. package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
  70. package/md_cg/test_issue274_read_node_id_none.py +341 -341
  71. package/md_cg/test_issue275_layer_param.py +250 -250
  72. package/md_cg/test_issue277_node_id_traversal.py +384 -384
  73. package/md_cg/test_issue278_neg_separated_tension.py +271 -271
  74. package/md_cg/test_issue278_neg_window.py +294 -294
  75. package/md_cg/test_issue278_negative_layering.py +83 -83
  76. package/md_cg/test_issue284_skip_not_pass.py +291 -291
  77. package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
  78. package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
  79. package/md_cg/test_issue303_design_boundaries.py +262 -262
  80. package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
  81. package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
  82. package/md_cg/test_issue321_mcp_deep_json.py +304 -304
  83. package/md_cg/test_issue322_node_write_lock.py +727 -727
  84. package/md_cg/test_issue324_write_size_fields.py +214 -214
  85. package/md_cg/test_issue325_audit_poison.py +229 -229
  86. package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
  87. package/md_cg/test_issue326_key_perms.py +355 -355
  88. package/md_cg/test_issue326_twin_parser_parity.py +323 -323
  89. package/md_cg/test_issue326_vm_call_frame.py +569 -569
  90. package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
  91. package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
  92. package/md_cg/test_issue348_insight_verify_op.py +199 -199
  93. package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
  94. package/md_cg/test_issue350_casefold_collision.py +235 -235
  95. package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
  96. package/md_cg/test_issue352_imgaudit.py +418 -418
  97. package/md_cg/test_issue352_pathsjson.py +537 -537
  98. package/md_cg/test_issue352_refindex.py +412 -412
  99. package/md_cg/test_issue352_rollback.py +604 -604
  100. package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
  101. package/md_cg/test_issue354_rust_index_containment.py +571 -571
  102. package/md_cg/test_issue354_rust_wal_containment.py +606 -606
  103. package/md_cg/test_issue358_truncation_observable.py +247 -247
  104. package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
  105. package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
  106. package/md_cg/test_issue362_neg_condition.py +468 -468
  107. package/md_cg/test_issue363_lexical_idf.py +275 -275
  108. package/md_cg/test_issue370_readcache_assembly.py +488 -488
  109. package/md_cg/test_issue376_heartbeat_failed.py +293 -293
  110. package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
  111. package/md_cg/test_issue378_protected_floor.py +310 -310
  112. package/md_cg/test_issue383_state_event_write_gate.py +462 -462
  113. package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
  114. package/md_cg/test_issue398_toolface_op_parity.py +511 -511
  115. package/md_cg/test_issue399_hive_json_shape.py +317 -317
  116. package/md_cg/test_issue401_wisdom_codegen.py +295 -295
  117. package/md_cg/test_issue404_heal_receipt.py +389 -389
  118. package/md_cg/test_issue409_compact_index_completeness.py +509 -509
  119. package/md_cg/test_issue410_verify_demote_write.py +366 -366
  120. package/md_cg/test_issue411_scrub_idempotence.py +575 -575
  121. package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
  122. package/md_cg/test_issue413_preimage_failclosed.py +239 -239
  123. package/md_cg/test_issue413_preimage_twin.py +339 -339
  124. package/md_cg/test_issue415_deps_gate_probe.py +357 -357
  125. package/md_cg/test_issue416_entry_key_subset.py +525 -525
  126. package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
  127. package/md_cg/test_issue425_ingest_library_path.py +331 -331
  128. package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
  129. package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
  130. package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
  131. package/md_cg/test_issue427_serve_status_shape.py +191 -191
  132. package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
  133. package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
  134. package/md_cg/test_issue434_435_float_gate.py +90 -90
  135. package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
  136. package/md_cg/test_issue43_default_policy.py +874 -874
  137. package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
  138. package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
  139. package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
  140. package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
  141. package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
  142. package/md_cg/test_issue451_audit_actor.py +313 -313
  143. package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
  144. package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
  145. package/md_cg/test_issue466_basis_registry.py +469 -469
  146. package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
  147. package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
  148. package/md_cg/test_issue470_wal_event_durable.py +427 -427
  149. package/md_cg/test_issue471_identity_readable.py +136 -136
  150. package/md_cg/test_issue472_audit_chain.py +90 -90
  151. package/md_cg/test_issue472_prune_ledger.py +105 -105
  152. package/md_cg/test_issue472_rollback_degraded.py +81 -81
  153. package/md_cg/test_issue491_compose_sandbox.py +460 -460
  154. package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
  155. package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
  156. package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
  157. package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
  158. package/md_cg/test_issue525_read_null_semantics.py +52 -52
  159. package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
  160. package/md_cg/test_issue547_audit_durable.py +96 -96
  161. package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
  162. package/md_cg/test_issue559_refine_prefix.py +69 -69
  163. package/md_cg/test_issue562_retired_faces.py +150 -0
  164. package/md_cg/test_issue71_queue_backlog.py +376 -376
  165. package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
  166. package/md_cg/test_issue82_credential_rules.py +271 -271
  167. package/md_cg/test_issue91_verifier_sandbox.py +314 -314
  168. package/md_cg/test_issue93_remember_redaction.py +282 -282
  169. package/md_cg/test_logref.py +1141 -1141
  170. package/md_cg/test_md_access_parity.py +330 -330
  171. package/md_cg/test_md_cg_no_hive_dep.py +139 -139
  172. package/md_cg/test_mutation_residue.py +119 -119
  173. package/md_cg/test_mutation_rollback.py +835 -835
  174. package/md_cg/test_n123_derive_expiry_chain.py +210 -210
  175. package/md_cg/test_n209_verify_write_face_gates.py +466 -466
  176. package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
  177. package/md_cg/test_neg_tail_honesty.py +733 -733
  178. package/md_cg/test_p21_tokens.py +294 -294
  179. package/md_cg/test_p27_docindex.py +792 -792
  180. package/md_cg/test_p28_refcheck.py +1053 -1053
  181. package/md_cg/test_p2_six_elements.py +476 -476
  182. package/md_cg/test_p33_ccg_wiring.py +300 -300
  183. package/md_cg/test_p3_legacy_closure.py +438 -438
  184. package/md_cg/test_p40_refine_worklist.py +244 -244
  185. package/md_cg/test_p4_freshness.py +781 -781
  186. package/md_cg/test_p9c_dedup_hints.py +288 -288
  187. package/md_cg/test_policy_required_ccg.py +444 -444
  188. package/md_cg/test_retr_s5.py +312 -312
  189. package/md_cg/test_s1_ast_judge.py +109 -109
  190. package/md_cg/test_state_event_op.py +521 -521
  191. package/md_cg/test_stgidx_index_parity.py +1024 -1024
  192. package/md_cg/test_sustain_bounded.py +652 -652
  193. package/md_cg/test_trust_edge_reachability.py +405 -405
  194. package/md_cg/test_w7_redlines.py +659 -659
  195. package/md_cg/test_write_return_shape.py +919 -919
  196. package/md_cg/test_writepipe.py +228 -228
  197. package/md_cg/trust.py +1114 -1114
  198. package/md_cg/twophase.py +303 -303
  199. package/md_cg/whitebox.py +536 -536
  200. package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
  201. package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
  202. package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
  203. package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
  204. package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
  205. package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
  206. package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
  207. package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
  208. package/md_cg/writepipe.py +1337 -1337
  209. package/package.json +3 -2
  210. package/scripts/workspace_index.py +328 -0
  211. package/src/hooks.ts +30 -6
  212. package/src/index.ts +14 -5
  213. package/src/lib/hook_audit.ts +282 -256
  214. package/src/lib/mdcg_client.ts +469 -469
  215. package/src/lib/prompt_safety.ts +17 -3
  216. package/src/tools.ts +23 -1
@@ -1,781 +1,781 @@
1
- # -*- coding: utf-8 -*-
2
- """P4 守卫 · 权重刷新与衰减进主分数(§7.1–§7.4)。
3
-
4
- 覆盖判据(每条对应契约的一项):
5
-
6
- G1 **核来自唯一权威**:`md_cg/whitebox_kb/aeis_core/time_core.py`——本模块
7
- 源码**不含指数核调用**,且 `decay_factor` 与 `cred_factor` 在 6 个 dt 上
8
- **逐位相等**(含 inf → floor)。
9
- G2 **γ 与 Δt 口径**(§〇.3-12):γ 缺省 `ln2/30 天`、与 `mdcos.temporal_gamma`
10
- **同一读取点**(env `MDCG_TEMPORAL_GAMMA` 同时覆盖两条路);Δt 取
11
- `created_at`;**单位必须是「天」**——30 天 → 0.5,若按秒喂同一时长则触 floor
12
- (单位断言的**判别力**)。
13
- G3 **refresh 参数照抄 AEIS**:与 `aeis_core/core.py` 的 `consolidate_cycle`
14
- 既有取值逐条相等(源码对拍 + 行为三档 1.01 / 0.99 / 1.0)。
15
- G4 **衰减必加 floor**(§7.3):老节点/缺 created_at 不低于 `SCORE_FLOOR`;
16
- **受保护节点** `importance × 乘子 ≥ IMPORTANCE_PROTECT` 恒成立;判别力
17
- (未保护节点不享有该下界)。
18
- G5 **落位 = 与分池权重同一乘子位**(§7.2):源码断言乘子行紧邻
19
- `pooling.weight_of(...)` 行;行为断言 `_score` 的同内容两节点分数比
20
- == 乘子比。
21
- G6 **索引条目取数**(P4-2①):条目含 `access_count`/`last_access`;
22
- `freshness.entry_weight` 只凭条目即可算(无 IO 面)。
23
- G7 **开关可回退**:`MDCG_FRESHNESS=0` → 乘子恒 1.0,`_score` 与基线逐位一致。
24
- G8 **三件套**(§7.4):预演零写盘;apply 逐节点 before/after 落
25
- `_maintain.jsonl`(`action="freshness"`,与 `importance` 同族);
26
- rollback 写回 before 且**不删节点**。
27
- G9 **降级不得实现为删除记录**(§7.3):降级只写 `freshness_state="degraded"`,
28
- 节点与正文原样在库;跨层降级走既有 `_move_layer`(内含 `guard_move`)
29
- ——受保护节点被移出保护层抛 `ProtectionError` 且无副作用。
30
- G10 `weights.recalc` 的「`after ≥ 0.70` 自动补写 `protected`」行为**仍在位**。
31
- G11 **Rust 侧同口径**:`rust/src/freshness.rs` 的四个常量与 Python 同值;
32
- 乘子只在 `sort_path(..., apply_freshness=true)` 生效且 `fuse` 只对
33
- lexical 传 true(与 Python `_score` 的对位面一致)。
34
-
35
- 运行:
36
- python -X utf8 -m md_cg.test_p4_freshness
37
- python -X utf8 -m md_cg.test_p4_freshness --mutate
38
- python -X utf8 -m md_cg.test_p4_freshness --mutate --list
39
-
40
- 退出码:0 = 全绿;1 = 有失败 / 变异未按预期转红;2 = ANCHOR-MISS。
41
-
42
- 硬边界:库根一律 tempfile;不动在役数据根;不 git add/commit/push。
43
- """
44
- from __future__ import annotations
45
-
46
- import hashlib
47
- import json
48
- import math
49
- import os
50
- import re
51
- import sys
52
- import tempfile
53
-
54
- # ── 隔离前置(必须在 import md_cg 子模块之前)──
55
- _TMP0 = tempfile.mkdtemp(prefix="p4_fresh_")
56
- os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP0, "auxroot")
57
- os.environ["MDCG_MASTER_KEY"] = "12" * 32
58
- os.environ["MDCG_TOKEN_FILE"] = os.path.join(_TMP0, "tokens.json")
59
- os.environ["MDCG_ROOT"] = os.path.join(_TMP0, "cgroot")
60
- for _k in ("MDCG_TOKEN", "MDCG_TENANT", "MDCG_CLEARANCE", "MDCG_SESSION",
61
- "MDCG_RETRIEVAL_PIPELINE", "MDCG_POOLING", "MDCG_FRESHNESS",
62
- "MDCG_FRESHNESS_NOW", "MDCG_TEMPORAL_GAMMA"):
63
- os.environ.pop(_k, None)
64
-
65
- _HERE = os.path.dirname(os.path.abspath(__file__))
66
- _REPO = os.path.dirname(_HERE)
67
- sys.path.insert(0, _REPO)
68
-
69
- try:
70
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
71
- except AttributeError:
72
- pass
73
-
74
- from md_cg import freshness as F # noqa: E402
75
- from md_cg import mdcg as M # noqa: E402
76
- from md_cg import nodefile # noqa: E402
77
- from md_cg import weights as W # noqa: E402
78
- from md_cg.mdcos import MdCGOS # noqa: E402
79
- from md_cg.whitebox_kb.aeis_core import time_core as TC # noqa: E402
80
-
81
- REF = 1_800_000_000.0
82
- DAY = 86400.0
83
-
84
- PASS = 0
85
- FAIL = 0
86
- FAILS = []
87
-
88
-
89
- def check(name, cond, detail=""):
90
- global PASS, FAIL
91
- if cond:
92
- PASS += 1
93
- print(f" OK {name}")
94
- else:
95
- FAIL += 1
96
- FAILS.append(name)
97
- print(f" FAIL {name} {detail}")
98
- return bool(cond)
99
-
100
-
101
- BODY = ("# 功能名:{n}\n# 生效条件:无条件\n# 子功能:无\n# 执行:占位\n"
102
- "# 验证方式:compiler 复现\n# 不适用条件:其它会话\n\n{t}\n")
103
-
104
-
105
- def _mk(cg, nid, layer="knowledge", **kw):
106
- cg.add(nid, BODY.format(n=nid, t=f"{nid} 正文 苹果 章节"), layer=layer, **kw)
107
-
108
-
109
- def _lib(extra=None):
110
- root = tempfile.mkdtemp(prefix="p4_lib_")
111
- cg = MdCGOS(root)
112
- for nid, kw in (extra or (("k_new", {"importance": 0.5,
113
- "created_at": REF}),
114
- ("k_old", {"importance": 0.5,
115
- "created_at": REF - 300 * DAY}))):
116
- _mk(cg, nid, **kw)
117
- cg.flush()
118
- return root, cg
119
-
120
-
121
- def _src(rel):
122
- with open(os.path.join(_REPO, rel), encoding="utf-8") as f:
123
- return f.read()
124
-
125
-
126
- def _tree_hash(root):
127
- h = hashlib.sha256()
128
- for dirpath, dirs, files in os.walk(root):
129
- dirs[:] = sorted(d for d in dirs if not d.startswith("_"))
130
- for fn in sorted(files):
131
- if fn.startswith("_"):
132
- continue
133
- p = os.path.join(dirpath, fn)
134
- h.update(os.path.relpath(p, root).replace("\\", "/").encode())
135
- with open(p, "rb") as f:
136
- h.update(f.read())
137
- return h.hexdigest()[:16]
138
-
139
-
140
- def _score_pair(cg, q="苹果 章节", protected=False):
141
- docs = []
142
- for nid, created, ac in (("k_new", REF, 0), ("k_old", REF - 300 * DAY, 0)):
143
- docs.append(({"path": f"knowledge/{nid}.md"},
144
- {"id": nid, "tags": [], "created_at": created,
145
- "access_count": ac, "last_access": 0,
146
- "importance": 0.5, "protected": protected},
147
- BODY.format(n=nid, t=f"{nid} 正文 苹果 章节")))
148
- return cg._score(docs, q, M.bigrams(M.normalize_en(q)))
149
-
150
-
151
- def g1_core_authority():
152
- print("== G1 核来自唯一权威 time_core(本模块无自写指数核)==")
153
- sc = F.selfcheck()
154
- check("freshness 源码不含指数核调用", sc["no_local_exp_core"] is True, str(sc))
155
- check("核经 time_core.cred_factor", sc["uses_cred_factor"] is True)
156
- g = F.resolve_gamma()
157
- ok = True
158
- detail = []
159
- for dt in (0.0, 1.0, 7.0, 30.0, 300.0, float("inf")):
160
- a = F.decay_factor(g, dt)
161
- b = TC.cred_factor(g, dt, F.SCORE_FLOOR, F.SCORE_CEIL)
162
- if a != b:
163
- ok = False
164
- detail.append((dt, a))
165
- check("decay_factor ≡ time_core.cred_factor(6 个 dt 逐位相等)", ok, str(detail))
166
-
167
-
168
- def g2_gamma_and_unit():
169
- print("== G2 γ 与 Δt 口径 / 单位必须是「天」==")
170
- from md_cg.mdcos import temporal_gamma
171
- from md_cg.links import DECAY_DAYS
172
- check("γ 缺省 = ln2/30 天",
173
- abs(F.resolve_gamma() - math.log(2.0) / 30.0) < 1e-15,
174
- str(F.resolve_gamma()))
175
- check("γ 与 mdcos.temporal_gamma **同一读取点**(缺省同值)",
176
- F.resolve_gamma() == temporal_gamma())
177
- check("半衰期真源 links.DECAY_DAYS == 30", DECAY_DAYS == 30.0)
178
- os.environ["MDCG_TEMPORAL_GAMMA"] = "0.5"
179
- try:
180
- check("env MDCG_TEMPORAL_GAMMA 同时覆盖两条路",
181
- F.resolve_gamma() == 0.5 and temporal_gamma() == 0.5)
182
- finally:
183
- os.environ.pop("MDCG_TEMPORAL_GAMMA", None)
184
- os.environ["MDCG_TEMPORAL_GAMMA"] = "abc"
185
- try:
186
- check("非法 γ 回落缺省(不抛)",
187
- abs(F.resolve_gamma() - math.log(2.0) / 30.0) < 1e-15)
188
- finally:
189
- os.environ.pop("MDCG_TEMPORAL_GAMMA", None)
190
- g = F.resolve_gamma()
191
- check("单位断言(天):30 天 → 0.5", abs(F.decay_factor(g, 30.0) - 0.5) < 1e-12,
192
- str(F.decay_factor(g, 30.0)))
193
- check("判别力:同一时长按**秒**喂 → 触 floor(喂秒会快 86400 倍)",
194
- F.decay_factor(g, 30.0 * DAY) == F.SCORE_FLOOR,
195
- str(F.decay_factor(g, 30.0 * DAY)))
196
- check("Δt 取 created_at(entry_weight 用 created_at 算天数)",
197
- F.entry_weight({"created_at": REF - 30 * DAY, "importance": 0.5},
198
- now=REF)[0] == F.decay_factor(g, 30.0))
199
- # 粒度=整日(向下取整):同为「1.x 天」的节点与「1 天」同值;「0.x 天」不衰减
200
- check("粒度断言:Δt 取整日(1.5 天 ≡ 1 天)",
201
- F.entry_weight({"created_at": REF - 1.5 * DAY, "importance": 0.5},
202
- now=REF)[0] == F.decay_factor(g, 1.0))
203
- check("粒度断言:当日写入(0.9 天)不衰减",
204
- F.entry_weight({"created_at": REF - 0.9 * DAY, "importance": 0.5},
205
- now=REF)[0] == F.decay_factor(g, 0.0))
206
- check("可复算:同一 (created_at, 日) 上两轮乘子逐位一致",
207
- F.entry_weight({"created_at": REF - 3 * DAY - 100, "importance": 0.5},
208
- now=REF)[0]
209
- == F.entry_weight({"created_at": REF - 3 * DAY - 100,
210
- "importance": 0.5}, now=REF + 10.0)[0])
211
-
212
-
213
- def g3_refresh_params():
214
- print("== G3 refresh 参数照抄 AEIS consolidate_cycle ==")
215
- src = _src(os.path.join("md_cg", "whitebox_kb", "aeis_core", "core.py"))
216
- check("AEIS 源码含 rehearsal_threshold = 0.7",
217
- re.search(r"rehearsal_threshold\s*:\s*float\s*=\s*0\.7", src)
218
- is not None)
219
- check("AEIS 源码含 degrade_threshold = 0.2",
220
- re.search(r"degrade_threshold\s*:\s*float\s*=\s*0\.2", src)
221
- is not None)
222
- check("AEIS 源码含 gain = 0.01",
223
- re.search(r"gain\s*:\s*float\s*=\s*0\.01", src) is not None)
224
- check("AEIS 源码的降权是 −gain(同一档语义)",
225
- re.search(r"update_node_importance\(n\.id,\s*-gain\)", src)
226
- is not None)
227
- check("AEIS 源码含 `% 10 == 0` 档",
228
- re.search(r"%\s*10\s*==\s*0", src) is not None)
229
- p = F.REFRESH_PARAMS
230
- check("参数取值与 AEIS 既有取值逐条相等",
231
- (p["rehearsal_threshold"], p["degrade_threshold"], p["gain"],
232
- p["cycle"]) == (0.7, 0.2, 0.01, 10), str(p))
233
- check("参数出处写在 paramsSource(REFRESH_PARAMS.source)",
234
- "consolidate_cycle" in p["source"] and "core.py" in p["source"],
235
- p["source"])
236
- check("行为档①演练:+gain", abs(F.refresh_factor(40, 1.0, 0.8) - 1.01) < 1e-12)
237
- check("行为档②降权:−gain", abs(F.refresh_factor(1, 1.0, 0.1) - 0.99) < 1e-12)
238
- check("行为档③其余:1.0", F.refresh_factor(3, 1.0, 0.5) == 1.0)
239
- check("从未访问不得白拿刷新(last_access=0 ⇒ 1.0)",
240
- F.refresh_factor(0, 0, 0.9) == 1.0)
241
-
242
-
243
- def g4_floor():
244
- print("== G4 衰减必加 floor / 保护线不被穿过 ==")
245
- g = F.resolve_gamma()
246
- check("老节点 ≥ SCORE_FLOOR",
247
- F.decay_factor(g, 10000.0) >= F.SCORE_FLOOR)
248
- check("缺 created_at 的节点仍带非零分(不乘成 0)",
249
- F.entry_weight({"created_at": 0, "importance": 0.5})[0] > 0.0,
250
- str(F.entry_weight({"created_at": 0, "importance": 0.5})[0]))
251
- check("缺 created_at 的衰减项触 floor(decay 本身 = SCORE_FLOOR)",
252
- F.decay_factor(g, float("inf")) == F.SCORE_FLOOR)
253
- for imp in (0.70, 0.8, 0.95, 1.0):
254
- w = F.entry_weight({"created_at": REF - 3650 * DAY,
255
- "importance": imp, "protected": True}, now=REF)[0]
256
- if not (imp * w >= W.IMPORTANCE_PROTECT):
257
- check(f"受保护节点 importance={imp} 乘子不穿保护线", False,
258
- f"imp*w={imp * w}")
259
- return
260
- check("受保护节点:importance × 乘子 ≥ IMPORTANCE_PROTECT(跨越 1/10/100 个半衰期)",
261
- True)
262
- # #378(2026-10-14)夹具更正:原夹具只写 importance=0.8 而**不带来源标注**
263
- # ——按本仓保护规则(protect.is_protected,AUTO_PROTECT_IMPORTANCE=0.70)
264
- # 那是「**缺省来源**高分」=受保护节点,与「未保护节点」的断言前提冲突
265
- # (且写侧对 importance≥0.70 本就会自动置保护位 ⇒ 该 dict 不对应任何真实
266
- # 节点)。补上显式非 hint 来源后前提重新成立,断言一字未动(数值前提
267
- # importance=0.8 亦保留)。
268
- w_free = F.entry_weight({"created_at": REF - 3650 * DAY,
269
- "importance": 0.8,
270
- "importance_source": "heuristic"}, now=REF)[0]
271
- check("判别力:未保护节点不享有该下界(乘子触 floor)",
272
- abs(w_free - F.SCORE_FLOOR) < 1e-12, str(w_free))
273
- check("保护下限口径取自 weights.IMPORTANCE_PROTECT(单一真源)",
274
- F.IMPORTANCE_PROTECT == W.IMPORTANCE_PROTECT == 0.70)
275
-
276
-
277
- def g5_same_multiplier_slot():
278
- print("== G5 落位:与分池权重同一乘子位 ==")
279
- root, cg = _lib()
280
- try:
281
- os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
282
- src = _src(os.path.join("md_cg", "mdcg.py"))
283
- lines = src.splitlines()
284
- i = next(n for n, l in enumerate(lines)
285
- if l.startswith(" def _score(self, docs, q, qb"))
286
- seg = lines[i:i + 120]
287
- jd = next(n for n, l in enumerate(seg)
288
- if "raw * pooling.weight_of(" in l)
289
- kd = next(n for n, l in enumerate(seg)
290
- if "raw * freshness.entry_weight(" in l)
291
- check("乘子行与分池权重行同处一个语句块(中间只有注释、无空行)",
292
- 0 < kd - jd <= 12
293
- and all(l.strip() for l in seg[jd + 1:kd]),
294
- f"pooling 行={jd} 乘子行={kd}")
295
- # N274:乘子行改为「调用跨两行」形态(循环外提升后追加
296
- # now/gamma/enabled 关键字透传)——判据性质不变(仍要求乘子**直接
297
- # 乘在 raw 上**、同一乘子位、以 [0] 取乘子),仅匹配形态同步为
298
- # 跨行;并顺带收紧为「行首即 raw = raw * …」。
299
- check("乘子直接乘在 raw 上(同一乘子位,不新开乘子链)",
300
- seg[kd].strip().startswith("raw = raw * freshness.entry_weight(")
301
- and "[0]" in (seg[kd] + seg[kd + 1]), # 单行/跨行两形态皆可
302
- f"kd 行={seg[kd]!r} 次行={seg[kd + 1]!r}")
303
- # 行为:同内容两节点,仅 created_at 不同 → 分数比 == 乘子比
304
- scored = _score_pair(cg)
305
- m_new = F.entry_weight(cg.index["nodes"]["k_new"], now=REF)[0]
306
- m_old = F.entry_weight({"created_at": REF - 300 * DAY,
307
- "importance": 0.5}, now=REF)[0]
308
- got = scored[0][1] / scored[1][1]
309
- check("_score 的同内容两节点分数比 == 乘子比(乘子确实进了主分数)",
310
- abs(got - (1.0 * m_new) / (1.0 * m_old)) < 1e-9,
311
- f"got={got} want={m_new / m_old}")
312
- check("旧节点被衰减(ratio > 1 且旧节点分更低)",
313
- scored[0][1] > scored[1][1], str(scored))
314
- finally:
315
- os.environ.pop("MDCG_FRESHNESS_NOW", None)
316
- cg.close()
317
-
318
-
319
- def g6_index_entry_data():
320
- print("== G6 取数:access_count / last_access 进索引条目(检索期不读盘)==")
321
- root, cg = _lib()
322
- try:
323
- e = cg.index["nodes"]["k_new"]
324
- check("条目含 access_count", "access_count" in e, str(sorted(e)[:5]))
325
- check("条目含 last_access", "last_access" in e)
326
- check("条目含 created_at(Δt 的输入)", e.get("created_at") == REF,
327
- str(e.get("created_at")))
328
- w, why = F.entry_weight(e)
329
- check("只凭条目即可算乘子(entry_weight 无 IO)",
330
- isinstance(w, float) and why.get("unit") == F.DT_UNIT, str(why))
331
- check("单位依据如实标为 day", why.get("unit") == "day")
332
- finally:
333
- cg.close()
334
-
335
-
336
- def g7_switch():
337
- print("== G7 开关可回退(MDCG_FRESHNESS=0 与基线逐位一致)==")
338
- root, cg = _lib()
339
- try:
340
- os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
341
- on = [round(s, 12) for _d, s in _score_pair(cg)]
342
- os.environ["MDCG_FRESHNESS"] = "0"
343
- off = [round(s, 12) for _d, s in _score_pair(cg)]
344
- os.environ.pop("MDCG_FRESHNESS", None)
345
- check("关时乘子恒 1.0",
346
- F.entry_weight(cg.index["nodes"]["k_new"])[0] == 1.0
347
- if os.environ.get("MDCG_FRESHNESS") == "0" else True)
348
- check("开/关两态下分数不同(开关真的有作用)", on != off,
349
- f"{on} vs {off}")
350
- check("关态 = 无乘子基线(两节点分数相同)", abs(off[0] - off[1]) < 1e-12,
351
- str(off))
352
- finally:
353
- os.environ.pop("MDCG_FRESHNESS", None)
354
- os.environ.pop("MDCG_FRESHNESS_NOW", None)
355
- cg.close()
356
-
357
-
358
- def g8_triplet():
359
- print("== G8 三件套:预演 / 逐节点留痕 / 反向 apply ==")
360
- root, cg = _lib()
361
- try:
362
- os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
363
- src_a = _tree_hash(root)
364
- pre = F.recalc(cg, apply=False)
365
- check("预演:dry_run=True 且零写盘(源面逐字节不变)",
366
- pre["dry_run"] is True and _tree_hash(root) == src_a, str(pre["written"]))
367
- check("预演给出逐节点 before/after 样本", bool(pre["samples"]),
368
- str(pre["samples"][:1]))
369
- check("预演不改 frontmatter",
370
- (cg.get("k_old")["frontmatter"].get("freshness_weight") is None))
371
- res = F.recalc(cg, apply=True, min_delta=0.0)
372
- check("apply:written ≥ 1", res["written"] >= 1, str(res["written"]))
373
- fm = cg.get("k_old")["frontmatter"]
374
- check("apply 写入 freshness_weight(与乘子一致)",
375
- abs(float(fm.get("freshness_weight")) -
376
- F.entry_weight({"created_at": REF - 300 * DAY,
377
- "importance": 0.5}, now=REF)[0]) < 1e-9,
378
- str(fm.get("freshness_weight")))
379
- log = os.path.join(cg.root, W.MAINTAIN_LOG)
380
- recs = [json.loads(x) for x in
381
- open(log, encoding="utf-8").read().splitlines() if x.strip()]
382
- mine = [r for r in recs if r.get("action") == "freshness"]
383
- check("逐节点留痕:_maintain.jsonl 有 action=freshness 记录",
384
- bool(mine), str([r.get("action") for r in recs]))
385
- check("留痕含 before/after(逐节点)",
386
- all(("before" in r and "after" in r) for r in mine),
387
- json.dumps(mine[:1], ensure_ascii=False))
388
- check("与 weights 的 action=importance 同族(同一 log 文件)",
389
- W.MAINTAIN_LOG == F.MAINTAIN_LOG == "_maintain.jsonl")
390
- rb = F.rollback(cg)
391
- check("rollback:reverted ≥ 1 且写回 before", rb["reverted"] >= 1, str(rb))
392
- fm2 = cg.get("k_old")["frontmatter"]
393
- check("rollback 后 freshness_weight 回到 before",
394
- abs(float(fm2.get("freshness_weight") or 0.0) - 1.0) < 1e-9,
395
- str(fm2.get("freshness_weight")))
396
- _p = (cg.index["nodes"].get("k_old") or {}).get("path") or ""
397
- check("rollback 后节点仍在索引(不删记录)",
398
- "k_old" in cg.index["nodes"] and bool(_p)
399
- and os.path.exists(os.path.join(cg.root, _p)), _p)
400
- check("rollback 自身再记一条留痕",
401
- any(r.get("action") == "freshness_rollback"
402
- for r in [json.loads(x) for x in
403
- open(log, encoding="utf-8").read().splitlines()
404
- if x.strip()]))
405
- finally:
406
- os.environ.pop("MDCG_FRESHNESS_NOW", None)
407
- cg.close()
408
-
409
-
410
- def g9_degrade_not_delete():
411
- print("== G9 降级 = 标记(不是删除);跨层降级走 guard_move ==")
412
- root = tempfile.mkdtemp(prefix="p4_deg_")
413
- cg = MdCGOS(root)
414
- try:
415
- _mk(cg, "k_prot", importance=0.8) # ≥0.70 ⇒ 自动打保护
416
- _mk(cg, "k_plain", importance=0.5, created_at=REF - 300 * DAY)
417
- cg.flush()
418
- os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
419
- e0 = dict(cg.index["nodes"]["k_prot"])
420
- check("夹具前提:节点受保护", bool(e0.get("protected")),
421
- str(e0.get("protected")))
422
- check("bind_move_layer 现绑既有 `_move_layer`(不新写搬迁路径)",
423
- F.bind_move_layer(cg) is True)
424
- res = F.recalc(cg, apply=True, min_delta=0.0)
425
- fm_p = cg.get("k_plain")["frontmatter"]
426
- _pp = (cg.index["nodes"].get("k_plain") or {}).get("path") or ""
427
- check("衰减到阈值下的节点被标 degraded(**只标记**)",
428
- fm_p.get("freshness_state") == "degraded", str(fm_p.get(
429
- "freshness_state")))
430
- check("被标 degraded 的节点与正文原样在库(降级 ≠ 删除记录)",
431
- os.path.exists(os.path.join(cg.root, _pp))
432
- and "k_plain" in cg.index["nodes"], _pp)
433
- check("受保护节点**不被**降级(保护下界生效)",
434
- (cg.get("k_prot")["frontmatter"].get("freshness_state")
435
- in (None, "")), str(cg.get("k_prot")["frontmatter"].get(
436
- "freshness_state")))
437
- check("报表给出降级计数", "degraded" in res, str(sorted(res)))
438
- # 跨层降级:受保护节点被移出保护层 → guard_move 抛错且无副作用
439
- import md_cg.protect as P
440
- before = cg.get("k_prot")["frontmatter"].get("layer")
441
- try:
442
- cg._move_layer("k_prot", "contextual", reason="guard 试")
443
- moved = True
444
- except P.ProtectionError:
445
- moved = False
446
- check("受保护节点降级被 guard_move 拒绝(ProtectionError)", moved is False)
447
- check("拒绝后节点层位与记录未变(无副作用)",
448
- cg.get("k_prot")["frontmatter"].get("layer") == before
449
- and "k_prot" in cg.index["nodes"])
450
- check("fixture 未因降级被删除(降级 ≠ 删除记录)",
451
- "k_prot" in cg.index["nodes"] and "k_plain" in cg.index["nodes"])
452
- check("非保护节点可被搬迁(同一闸的两侧对照)",
453
- isinstance(cg._move_layer("k_plain", "contextual",
454
- reason="guard 对照"), dict))
455
- finally:
456
- os.environ.pop("MDCG_FRESHNESS_NOW", None)
457
- cg.close()
458
-
459
-
460
- def g10_weights_autoprotect_kept():
461
- print("== G10 weights.recalc 的 ≥0.70 自动补写 protected 仍在位 ==")
462
- src = _src(os.path.join("md_cg", "weights.py"))
463
- check("weights.py 仍含 IMPORTANCE_PROTECT 常量与自动补写分支",
464
- "IMPORTANCE_PROTECT = 0.70" in src
465
- and 'fm["protected"] = True' in src)
466
- root = tempfile.mkdtemp(prefix="p4_w_")
467
- cg = MdCGOS(root)
468
- try:
469
- _mk(cg, "hub", importance=0.2, verification_basis="formal_proof")
470
- for i in range(12):
471
- cg.add(f"leaf{i}", BODY.format(n=f"leaf{i}", t=f"leaf{i} 正文"),
472
- layer="knowledge", importance=0.1,
473
- edges=[{"target": "hub", "relation_type": "causal"}])
474
- cg.flush()
475
- rep = W.recalc(cg, apply=True, min_delta=0.0)
476
- fm = cg.get("hub")["frontmatter"]
477
- check("重算后 after ≥ 0.70 ⇒ 自动补写 protected",
478
- float(fm.get("importance") or 0) >= W.IMPORTANCE_PROTECT
479
- and fm.get("protected") is True,
480
- f"imp={fm.get('importance')} protected={fm.get('protected')}")
481
- check("recalc 报表结构未变(预演/留痕/回滚三件套仍在)",
482
- {"dry_run", "samples", "log"} <= set(rep), str(sorted(rep)))
483
- finally:
484
- cg.close()
485
-
486
-
487
- def g11_rust_parity():
488
- print("== G11 Rust 侧同口径(常量 + 生效面)==")
489
- rs = _src(os.path.join("rust", "src", "freshness.rs"))
490
- for name, val in (("SCORE_FLOOR", "0.001"), ("SECONDS_PER_DAY", "86400.0"),
491
- ("IMPORTANCE_PROTECT", "0.70"), ("DECAY_DAYS", "30.0")):
492
- check(f"rust 常量 {name} 与 Python 同值",
493
- f"pub const {name}: f64 = {val};" in rs, name)
494
- for name, val in (("REHEARSAL_THRESHOLD", "0.7"),
495
- ("DEGRADE_THRESHOLD", "0.2"), ("GAIN", "0.01")):
496
- check(f"rust 参数 {name} 照抄 AEIS({val})",
497
- f"const {name}: f64 = {val};" in rs, name)
498
- ret = _src(os.path.join("rust", "src", "retrieval.rs"))
499
- check("sort_path 带 apply_freshness 开关",
500
- "pub fn sort_path(hits: &mut [Hit], docs: &[Option<Doc>],"
501
- " apply_freshness: bool)" in ret)
502
- check("fuse 只对 lexical 路开乘子(与 Python `_score` 对位)",
503
- 'sort_path(&mut h, docs, *name == "lexical")' in ret)
504
- eng = _src(os.path.join("rust", "src", "engine.rs"))
505
- check("graph 种子排序带乘子(种子取自 lexical 路)",
506
- "retrieval::sort_path(&mut v, docs, true);" in eng)
507
- check("Rust 侧有核/参数的单测(半衰期、floor、保护线、演练闸)",
508
- rs.count("#[test]") >= 4, str(rs.count("#[test]")))
509
-
510
-
511
- # --------------------------------------------------------------------------
512
- # 定点变异(只改本进程内存对象/临时文件,绝不改仓库文件)
513
- # --------------------------------------------------------------------------
514
-
515
- def g12_rust_parity_e2e():
516
- """P4-2② 双侧同改的**端到端逐位对拍**(判别力夹具,非 rank_parity 现有语料)。
517
-
518
- 为什么必须另造夹具:`scripts/rank_parity.py` 的语料是**新建节点**(Δt=0 天
519
- ⇒ 乘子恒 1.0)、无 edges/无时间参数/无六要素后两行 ⇒ 对 P4 乘子**零判别力**
520
- (实测:改前 10/10、改后 10/10、改后 Python + 改前 Rust 二进制亦 10/10)。
521
- 只有把「同分不同龄」的节点放进去,乘子才改变路内名次,两侧才可能劈叉。
522
-
523
- 夹具:6 个**正文逐字相同**(词法分并列)的节点,created_at 跨度 0/30/300 天,
524
- importance 随年龄递增(未乘者按 (-score,-importance,id) 会「越老越靠前」);
525
- `MDCG_FRESHNESS_NOW` 钉死 → 两侧同一参照时刻。断言:
526
- ① 改后两侧 top-k **逐位一致**(Python `search_rrf` vs Rust `--serve`);
527
- ② 夹具**有判别力**:把 Python 侧乘子关掉,名次与 ① 不同(否则本对拍空转)。
528
- 二进制缺失 = fail-closed 红(「跑不起来」永不算通过)。
529
- """
530
- exe = os.path.join(_REPO, "rust", "target", "release",
531
- "mdcg-eval.exe" if os.name == "nt" else "mdcg-eval")
532
- if not os.path.isfile(exe):
533
- check("Rust 二进制在位(逐位对拍的另一侧)", False,
534
- f"{exe} 不存在——先 cd rust && cargo build --release")
535
- return
536
- sys.path.insert(0, os.path.join(_REPO, "scripts"))
537
- import rank_parity as RP # noqa: E402
538
- py_mode, conflict = RP.pin_python_score_mode()
539
- if py_mode != "jaccard" or conflict:
540
- check("Python 侧口径可钉住(eval_common.use_jaccard)", False,
541
- f"{py_mode} / {conflict}")
542
- return
543
- root = tempfile.mkdtemp(prefix="p4_parity_")
544
- cg = MdCGOS(root)
545
- ages = (0.0, 0.0, 30.0, 30.0, 300.0, 300.0)
546
- for i, age in enumerate(ages):
547
- # importance 全部 < 0.70(避开自动保护 → 不受保护下界豁免衰减)
548
- # 且全部 ≥ 0.20(避开 AEIS 降权档),年龄越大 importance 越高 ⇒
549
- # 「未乘者越老越靠前」,乘子一到即翻转
550
- _mk(cg, f"p{i}", created_at=REF - age * DAY,
551
- importance=0.20 + 0.04 * i, tags=[])
552
- cg.flush()
553
- q = "苹果 章节"
554
- os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
555
- try:
556
- py = [(x[0]["id"], round(float(x[1]), 6))
557
- for x in cg.search_rrf(q, k=6, record=False)[0]]
558
- os.environ["MDCG_FRESHNESS"] = "0"
559
- off = [(x[0]["id"], round(float(x[1]), 6))
560
- for x in cg.search_rrf(q, k=6, record=False)[0]]
561
- os.environ.pop("MDCG_FRESHNESS", None)
562
- try:
563
- proc, rs_mode = RP.rust_open(exe, root)
564
- except Exception as exc: # noqa: BLE001
565
- check("Rust serve 可拉起且自报口径", False, str(exc)[:200])
566
- cg.close()
567
- return
568
- try:
569
- rs = RP.rust_topk(proc, [q], k=6)[q]
570
- finally:
571
- pass
572
- rs2 = [(i, None if s is None else round(float(s), 6)) for i, s in rs]
573
- print(f" py(new)={py}")
574
- print(f" rust ={rs2}")
575
- print(f" py(off)={off}")
576
- check("① 两侧 top-k 逐位一致(同乘子、同口径)",
577
- [i for i, _s in py] == [i for i, _s in rs2],
578
- f"{[i for i, _s in py]} vs {[i for i, _s in rs2]}")
579
- check("② 夹具判别力:关掉乘子后名次不同(本对拍非空转)",
580
- [i for i, _s in py] != [i for i, _s in off],
581
- f"{[i for i, _s in py]} vs {[i for i, _s in off]}")
582
- check("② 乘子使「新节点靠前、旧节点靠后」",
583
- [i for i, _s in py][0] in ("p0", "p1")
584
- and [i for i, _s in py][-1] in ("p4", "p5"),
585
- f"{[i for i, _s in py]}")
586
- finally:
587
- os.environ.pop("MDCG_FRESHNESS_NOW", None)
588
- cg.close()
589
- import shutil
590
- shutil.rmtree(root, ignore_errors=True)
591
-
592
-
593
- def g13_hot_loop_reads():
594
- """N274:freshness 读取点全部提升到 `_score` 循环外(调用计数判据)。
595
-
596
- 判据=**与文档数无关**:同一 `_score` 调用于 2 节点与 20 节点两批文档
597
- 时,`enabled`/`freshness_now`/`resolve_gamma`/`temporal_gamma` 的调用
598
- 计数相同。修前(8000 池实测,2026-10-05)为每节点 7 次(enabled 4×N
599
- + now/γ/temporal 各 N);墙钟只作辅助,不作判据。
600
- """
601
- print("== G13 freshness 读取提升到 _score 循环外(N274)==")
602
- import md_cg.mdcos as MC
603
- root, cg = _lib()
604
- c = {"enabled": 0, "now": 0, "gamma": 0, "temporal": 0}
605
- orig = {n: getattr(F, n) for n in ("enabled", "freshness_now",
606
- "resolve_gamma")}
607
- orig_tg = MC.temporal_gamma
608
-
609
- def _wrap(fn, key):
610
- def _w(*a, **k):
611
- c[key] += 1
612
- return fn(*a, **k)
613
- return _w
614
-
615
- F.enabled = _wrap(orig["enabled"], "enabled")
616
- F.freshness_now = _wrap(orig["freshness_now"], "now")
617
- F.resolve_gamma = _wrap(orig["resolve_gamma"], "gamma")
618
- MC.temporal_gamma = _wrap(orig_tg, "temporal")
619
- try:
620
- def _mk_docs(n):
621
- return [({"path": "knowledge/k%d.md" % i},
622
- {"id": "k%d" % i, "tags": [],
623
- "created_at": REF - i * DAY, "access_count": 0,
624
- "last_access": 0, "importance": 0.5},
625
- BODY.format(n="k%d" % i, t="k%d 正文 苹果 章节" % i))
626
- for i in range(n)]
627
-
628
- def _count(docs):
629
- for k in c:
630
- c[k] = 0
631
- cg._score(docs, "苹果 章节",
632
- M.bigrams(M.normalize_en("苹果 章节")))
633
- return dict(c)
634
-
635
- c2 = _count(_mk_docs(2))
636
- c20 = _count(_mk_docs(20))
637
- # 判据面=**env 读取三面**(enabled / freshness_now / temporal_gamma
638
- # ——后者是 γ 的实际读取点:resolve_gamma 的 early-return 分支不碰
639
- # temporal_gamma,故「temporal_gamma 常数」即「γ 的 env 读取归零」)。
640
- # 诚实边界:resolve_gamma 的**函数调用**仍每节点一次(early-return
641
- # 直通已解析的 float,~0.15µs/节点、不读 env)——保留它是因为
642
- # resolve_gamma 还承担「非法 gamma 回落缺省」的单点边界语义,跳过
643
- # 调用会改变该边界。
644
- check("env 读取面与文档数无关(enabled/now/temporal;修前各 N×)",
645
- {k: c2[k] for k in ("enabled", "now", "temporal")}
646
- == {k: c20[k] for k in ("enabled", "now", "temporal")},
647
- f"c2={c2} c20={c20}")
648
- check("enabled() 常数级(修前 = 4×N)", c20["enabled"] <= 2, str(c20))
649
- check("freshness_now() 常数级(修前 = 1×N)", c20["now"] <= 1, str(c20))
650
- check("temporal_gamma() 常数级(修前 = 1×N;γ 的实际读取点)",
651
- c20["temporal"] <= 1, str(c20))
652
- # 自证腿(常驻):全缺省签名的旧路径仍自算,四个 spy 数得到——证明
653
- # 上面的「零/常数」不是 spy 失效造成的假绿(判别力在位)。
654
- for k in c:
655
- c[k] = 0
656
- F.entry_weight({"created_at": REF, "importance": 0.5})
657
- check("自证腿:全缺省签名仍自算(四路 spy 各 ≥1,判别力在位)",
658
- c["enabled"] >= 1 and c["now"] >= 1 and c["gamma"] >= 1
659
- and c["temporal"] >= 1, str(c))
660
- # 语义等价:显式透传与自算逐位同值;关闭恒 1.0(三面同口径)
661
- e0 = {"created_at": REF - 30 * DAY, "importance": 0.5}
662
- check("显式 enabled+now+γ 透传与自算同值(逐位一致)",
663
- F.entry_weight(e0, now=REF)[0]
664
- == F.entry_weight(e0, now=REF, gamma=F.resolve_gamma(None),
665
- enabled=True)[0])
666
- check("enabled=False 恒 1.0(entry/decay/refresh 三面同口径)",
667
- F.entry_weight(e0, now=REF, enabled=False)[0] == 1.0
668
- and F.decay_factor(0.023, 100.0, enabled=False) == 1.0
669
- and F.refresh_factor(0, 0, 0.9, enabled=False) == 1.0)
670
- finally:
671
- F.enabled = orig["enabled"]
672
- F.freshness_now = orig["freshness_now"]
673
- F.resolve_gamma = orig["resolve_gamma"]
674
- MC.temporal_gamma = orig_tg
675
- cg.close()
676
- import shutil
677
- shutil.rmtree(root, ignore_errors=True)
678
-
679
-
680
- def _mut_floor_zero():
681
- return _patch(F, "SCORE_FLOOR", 0.0)
682
-
683
-
684
- def _mut_gain_10x():
685
- orig = dict(F.REFRESH_PARAMS)
686
-
687
- def restore():
688
- F.REFRESH_PARAMS.clear()
689
- F.REFRESH_PARAMS.update(orig)
690
- F.REFRESH_PARAMS["gain"] = 0.1
691
- return restore
692
-
693
-
694
- def _mut_unit_seconds():
695
- return _patch(F, "SECONDS_PER_DAY", 1.0)
696
-
697
-
698
- def _mut_protect_floor_off():
699
- orig = F.protected_floor
700
- F.protected_floor = lambda entry: F.SCORE_FLOOR
701
-
702
- def restore():
703
- F.protected_floor = orig
704
- return restore
705
-
706
-
707
- def _mut_switch_off():
708
- return _patch(F, "enabled", lambda environ=None: False)
709
-
710
-
711
- def _patch(mod, name, value):
712
- orig = getattr(mod, name)
713
-
714
- def restore():
715
- setattr(mod, name, orig)
716
- setattr(mod, name, value)
717
- return restore
718
-
719
-
720
- _MUTATIONS = [
721
- ("floor_zero", "衰减 floor 归零", _mut_floor_zero),
722
- ("gain_10x", "刷新步长改成 0.1(脱离 AEIS 取值)", _mut_gain_10x),
723
- ("unit_seconds", "Δt 单位改成「秒」", _mut_unit_seconds),
724
- ("protect_floor_off", "去掉受保护节点的保护下界", _mut_protect_floor_off),
725
- ("switch_off", "乘子开关恒关", _mut_switch_off),
726
- ]
727
-
728
-
729
- def _collect():
730
- global PASS, FAIL, FAILS
731
- PASS, FAIL, FAILS = 0, 0, []
732
- g1_core_authority()
733
- g2_gamma_and_unit()
734
- g3_refresh_params()
735
- g4_floor()
736
- g5_same_multiplier_slot()
737
- g6_index_entry_data()
738
- g7_switch()
739
- g8_triplet()
740
- g9_degrade_not_delete()
741
- g10_weights_autoprotect_kept()
742
- g11_rust_parity()
743
- g12_rust_parity_e2e()
744
- g13_hot_loop_reads()
745
- return list(FAILS)
746
-
747
-
748
- def main(argv):
749
- if "--mutate" in argv:
750
- if "--list" in argv:
751
- for name, desc, _fn in _MUTATIONS:
752
- print(f" {name:20s} {desc}")
753
- return 0
754
- base = _collect()
755
- if base:
756
- print(f"\n!! 基线不绿({len(base)} 条):{base}")
757
- return 1
758
- bad = []
759
- for name, desc, fn in _MUTATIONS:
760
- try:
761
- restore = fn()
762
- except AttributeError as exc:
763
- print(f" ANCHOR-MISS {name}: {exc}")
764
- return 2
765
- got = _collect()
766
- restore()
767
- if got:
768
- print(f" MUTATE-OK {name}({desc})→ 转红 {len(got)} 条:{got[:3]}")
769
- else:
770
- bad.append(name)
771
- print(f" MUTATE-FAIL {name}({desc})→ 仍全绿")
772
- print(f"\ntest_p4_freshness --mutate: "
773
- f"{len(_MUTATIONS) - len(bad)}/{len(_MUTATIONS)} 变异按预期转红")
774
- return 0 if not bad else 1
775
- fails = _collect()
776
- print(f"\ntest_p4_freshness: {PASS} 通过 / {FAIL} 失败")
777
- return 0 if not fails else 1
778
-
779
-
780
- if __name__ == "__main__":
781
- sys.exit(main(sys.argv[1:]))
1
+ # -*- coding: utf-8 -*-
2
+ """P4 守卫 · 权重刷新与衰减进主分数(§7.1–§7.4)。
3
+
4
+ 覆盖判据(每条对应契约的一项):
5
+
6
+ G1 **核来自唯一权威**:`md_cg/whitebox_kb/aeis_core/time_core.py`——本模块
7
+ 源码**不含指数核调用**,且 `decay_factor` 与 `cred_factor` 在 6 个 dt 上
8
+ **逐位相等**(含 inf → floor)。
9
+ G2 **γ 与 Δt 口径**(§〇.3-12):γ 缺省 `ln2/30 天`、与 `mdcos.temporal_gamma`
10
+ **同一读取点**(env `MDCG_TEMPORAL_GAMMA` 同时覆盖两条路);Δt 取
11
+ `created_at`;**单位必须是「天」**——30 天 → 0.5,若按秒喂同一时长则触 floor
12
+ (单位断言的**判别力**)。
13
+ G3 **refresh 参数照抄 AEIS**:与 `aeis_core/core.py` 的 `consolidate_cycle`
14
+ 既有取值逐条相等(源码对拍 + 行为三档 1.01 / 0.99 / 1.0)。
15
+ G4 **衰减必加 floor**(§7.3):老节点/缺 created_at 不低于 `SCORE_FLOOR`;
16
+ **受保护节点** `importance × 乘子 ≥ IMPORTANCE_PROTECT` 恒成立;判别力
17
+ (未保护节点不享有该下界)。
18
+ G5 **落位 = 与分池权重同一乘子位**(§7.2):源码断言乘子行紧邻
19
+ `pooling.weight_of(...)` 行;行为断言 `_score` 的同内容两节点分数比
20
+ == 乘子比。
21
+ G6 **索引条目取数**(P4-2①):条目含 `access_count`/`last_access`;
22
+ `freshness.entry_weight` 只凭条目即可算(无 IO 面)。
23
+ G7 **开关可回退**:`MDCG_FRESHNESS=0` → 乘子恒 1.0,`_score` 与基线逐位一致。
24
+ G8 **三件套**(§7.4):预演零写盘;apply 逐节点 before/after 落
25
+ `_maintain.jsonl`(`action="freshness"`,与 `importance` 同族);
26
+ rollback 写回 before 且**不删节点**。
27
+ G9 **降级不得实现为删除记录**(§7.3):降级只写 `freshness_state="degraded"`,
28
+ 节点与正文原样在库;跨层降级走既有 `_move_layer`(内含 `guard_move`)
29
+ ——受保护节点被移出保护层抛 `ProtectionError` 且无副作用。
30
+ G10 `weights.recalc` 的「`after ≥ 0.70` 自动补写 `protected`」行为**仍在位**。
31
+ G11 **Rust 侧同口径**:`rust/src/freshness.rs` 的四个常量与 Python 同值;
32
+ 乘子只在 `sort_path(..., apply_freshness=true)` 生效且 `fuse` 只对
33
+ lexical 传 true(与 Python `_score` 的对位面一致)。
34
+
35
+ 运行:
36
+ python -X utf8 -m md_cg.test_p4_freshness
37
+ python -X utf8 -m md_cg.test_p4_freshness --mutate
38
+ python -X utf8 -m md_cg.test_p4_freshness --mutate --list
39
+
40
+ 退出码:0 = 全绿;1 = 有失败 / 变异未按预期转红;2 = ANCHOR-MISS。
41
+
42
+ 硬边界:库根一律 tempfile;不动在役数据根;不 git add/commit/push。
43
+ """
44
+ from __future__ import annotations
45
+
46
+ import hashlib
47
+ import json
48
+ import math
49
+ import os
50
+ import re
51
+ import sys
52
+ import tempfile
53
+
54
+ # ── 隔离前置(必须在 import md_cg 子模块之前)──
55
+ _TMP0 = tempfile.mkdtemp(prefix="p4_fresh_")
56
+ os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP0, "auxroot")
57
+ os.environ["MDCG_MASTER_KEY"] = "12" * 32
58
+ os.environ["MDCG_TOKEN_FILE"] = os.path.join(_TMP0, "tokens.json")
59
+ os.environ["MDCG_ROOT"] = os.path.join(_TMP0, "cgroot")
60
+ for _k in ("MDCG_TOKEN", "MDCG_TENANT", "MDCG_CLEARANCE", "MDCG_SESSION",
61
+ "MDCG_RETRIEVAL_PIPELINE", "MDCG_POOLING", "MDCG_FRESHNESS",
62
+ "MDCG_FRESHNESS_NOW", "MDCG_TEMPORAL_GAMMA"):
63
+ os.environ.pop(_k, None)
64
+
65
+ _HERE = os.path.dirname(os.path.abspath(__file__))
66
+ _REPO = os.path.dirname(_HERE)
67
+ sys.path.insert(0, _REPO)
68
+
69
+ try:
70
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
71
+ except AttributeError:
72
+ pass
73
+
74
+ from md_cg import freshness as F # noqa: E402
75
+ from md_cg import mdcg as M # noqa: E402
76
+ from md_cg import nodefile # noqa: E402
77
+ from md_cg import weights as W # noqa: E402
78
+ from md_cg.mdcos import MdCGOS # noqa: E402
79
+ from md_cg.whitebox_kb.aeis_core import time_core as TC # noqa: E402
80
+
81
+ REF = 1_800_000_000.0
82
+ DAY = 86400.0
83
+
84
+ PASS = 0
85
+ FAIL = 0
86
+ FAILS = []
87
+
88
+
89
+ def check(name, cond, detail=""):
90
+ global PASS, FAIL
91
+ if cond:
92
+ PASS += 1
93
+ print(f" OK {name}")
94
+ else:
95
+ FAIL += 1
96
+ FAILS.append(name)
97
+ print(f" FAIL {name} {detail}")
98
+ return bool(cond)
99
+
100
+
101
+ BODY = ("# 功能名:{n}\n# 生效条件:无条件\n# 子功能:无\n# 执行:占位\n"
102
+ "# 验证方式:compiler 复现\n# 不适用条件:其它会话\n\n{t}\n")
103
+
104
+
105
+ def _mk(cg, nid, layer="knowledge", **kw):
106
+ cg.add(nid, BODY.format(n=nid, t=f"{nid} 正文 苹果 章节"), layer=layer, **kw)
107
+
108
+
109
+ def _lib(extra=None):
110
+ root = tempfile.mkdtemp(prefix="p4_lib_")
111
+ cg = MdCGOS(root)
112
+ for nid, kw in (extra or (("k_new", {"importance": 0.5,
113
+ "created_at": REF}),
114
+ ("k_old", {"importance": 0.5,
115
+ "created_at": REF - 300 * DAY}))):
116
+ _mk(cg, nid, **kw)
117
+ cg.flush()
118
+ return root, cg
119
+
120
+
121
+ def _src(rel):
122
+ with open(os.path.join(_REPO, rel), encoding="utf-8") as f:
123
+ return f.read()
124
+
125
+
126
+ def _tree_hash(root):
127
+ h = hashlib.sha256()
128
+ for dirpath, dirs, files in os.walk(root):
129
+ dirs[:] = sorted(d for d in dirs if not d.startswith("_"))
130
+ for fn in sorted(files):
131
+ if fn.startswith("_"):
132
+ continue
133
+ p = os.path.join(dirpath, fn)
134
+ h.update(os.path.relpath(p, root).replace("\\", "/").encode())
135
+ with open(p, "rb") as f:
136
+ h.update(f.read())
137
+ return h.hexdigest()[:16]
138
+
139
+
140
+ def _score_pair(cg, q="苹果 章节", protected=False):
141
+ docs = []
142
+ for nid, created, ac in (("k_new", REF, 0), ("k_old", REF - 300 * DAY, 0)):
143
+ docs.append(({"path": f"knowledge/{nid}.md"},
144
+ {"id": nid, "tags": [], "created_at": created,
145
+ "access_count": ac, "last_access": 0,
146
+ "importance": 0.5, "protected": protected},
147
+ BODY.format(n=nid, t=f"{nid} 正文 苹果 章节")))
148
+ return cg._score(docs, q, M.bigrams(M.normalize_en(q)))
149
+
150
+
151
+ def g1_core_authority():
152
+ print("== G1 核来自唯一权威 time_core(本模块无自写指数核)==")
153
+ sc = F.selfcheck()
154
+ check("freshness 源码不含指数核调用", sc["no_local_exp_core"] is True, str(sc))
155
+ check("核经 time_core.cred_factor", sc["uses_cred_factor"] is True)
156
+ g = F.resolve_gamma()
157
+ ok = True
158
+ detail = []
159
+ for dt in (0.0, 1.0, 7.0, 30.0, 300.0, float("inf")):
160
+ a = F.decay_factor(g, dt)
161
+ b = TC.cred_factor(g, dt, F.SCORE_FLOOR, F.SCORE_CEIL)
162
+ if a != b:
163
+ ok = False
164
+ detail.append((dt, a))
165
+ check("decay_factor ≡ time_core.cred_factor(6 个 dt 逐位相等)", ok, str(detail))
166
+
167
+
168
+ def g2_gamma_and_unit():
169
+ print("== G2 γ 与 Δt 口径 / 单位必须是「天」==")
170
+ from md_cg.mdcos import temporal_gamma
171
+ from md_cg.links import DECAY_DAYS
172
+ check("γ 缺省 = ln2/30 天",
173
+ abs(F.resolve_gamma() - math.log(2.0) / 30.0) < 1e-15,
174
+ str(F.resolve_gamma()))
175
+ check("γ 与 mdcos.temporal_gamma **同一读取点**(缺省同值)",
176
+ F.resolve_gamma() == temporal_gamma())
177
+ check("半衰期真源 links.DECAY_DAYS == 30", DECAY_DAYS == 30.0)
178
+ os.environ["MDCG_TEMPORAL_GAMMA"] = "0.5"
179
+ try:
180
+ check("env MDCG_TEMPORAL_GAMMA 同时覆盖两条路",
181
+ F.resolve_gamma() == 0.5 and temporal_gamma() == 0.5)
182
+ finally:
183
+ os.environ.pop("MDCG_TEMPORAL_GAMMA", None)
184
+ os.environ["MDCG_TEMPORAL_GAMMA"] = "abc"
185
+ try:
186
+ check("非法 γ 回落缺省(不抛)",
187
+ abs(F.resolve_gamma() - math.log(2.0) / 30.0) < 1e-15)
188
+ finally:
189
+ os.environ.pop("MDCG_TEMPORAL_GAMMA", None)
190
+ g = F.resolve_gamma()
191
+ check("单位断言(天):30 天 → 0.5", abs(F.decay_factor(g, 30.0) - 0.5) < 1e-12,
192
+ str(F.decay_factor(g, 30.0)))
193
+ check("判别力:同一时长按**秒**喂 → 触 floor(喂秒会快 86400 倍)",
194
+ F.decay_factor(g, 30.0 * DAY) == F.SCORE_FLOOR,
195
+ str(F.decay_factor(g, 30.0 * DAY)))
196
+ check("Δt 取 created_at(entry_weight 用 created_at 算天数)",
197
+ F.entry_weight({"created_at": REF - 30 * DAY, "importance": 0.5},
198
+ now=REF)[0] == F.decay_factor(g, 30.0))
199
+ # 粒度=整日(向下取整):同为「1.x 天」的节点与「1 天」同值;「0.x 天」不衰减
200
+ check("粒度断言:Δt 取整日(1.5 天 ≡ 1 天)",
201
+ F.entry_weight({"created_at": REF - 1.5 * DAY, "importance": 0.5},
202
+ now=REF)[0] == F.decay_factor(g, 1.0))
203
+ check("粒度断言:当日写入(0.9 天)不衰减",
204
+ F.entry_weight({"created_at": REF - 0.9 * DAY, "importance": 0.5},
205
+ now=REF)[0] == F.decay_factor(g, 0.0))
206
+ check("可复算:同一 (created_at, 日) 上两轮乘子逐位一致",
207
+ F.entry_weight({"created_at": REF - 3 * DAY - 100, "importance": 0.5},
208
+ now=REF)[0]
209
+ == F.entry_weight({"created_at": REF - 3 * DAY - 100,
210
+ "importance": 0.5}, now=REF + 10.0)[0])
211
+
212
+
213
+ def g3_refresh_params():
214
+ print("== G3 refresh 参数照抄 AEIS consolidate_cycle ==")
215
+ src = _src(os.path.join("md_cg", "whitebox_kb", "aeis_core", "core.py"))
216
+ check("AEIS 源码含 rehearsal_threshold = 0.7",
217
+ re.search(r"rehearsal_threshold\s*:\s*float\s*=\s*0\.7", src)
218
+ is not None)
219
+ check("AEIS 源码含 degrade_threshold = 0.2",
220
+ re.search(r"degrade_threshold\s*:\s*float\s*=\s*0\.2", src)
221
+ is not None)
222
+ check("AEIS 源码含 gain = 0.01",
223
+ re.search(r"gain\s*:\s*float\s*=\s*0\.01", src) is not None)
224
+ check("AEIS 源码的降权是 −gain(同一档语义)",
225
+ re.search(r"update_node_importance\(n\.id,\s*-gain\)", src)
226
+ is not None)
227
+ check("AEIS 源码含 `% 10 == 0` 档",
228
+ re.search(r"%\s*10\s*==\s*0", src) is not None)
229
+ p = F.REFRESH_PARAMS
230
+ check("参数取值与 AEIS 既有取值逐条相等",
231
+ (p["rehearsal_threshold"], p["degrade_threshold"], p["gain"],
232
+ p["cycle"]) == (0.7, 0.2, 0.01, 10), str(p))
233
+ check("参数出处写在 paramsSource(REFRESH_PARAMS.source)",
234
+ "consolidate_cycle" in p["source"] and "core.py" in p["source"],
235
+ p["source"])
236
+ check("行为档①演练:+gain", abs(F.refresh_factor(40, 1.0, 0.8) - 1.01) < 1e-12)
237
+ check("行为档②降权:−gain", abs(F.refresh_factor(1, 1.0, 0.1) - 0.99) < 1e-12)
238
+ check("行为档③其余:1.0", F.refresh_factor(3, 1.0, 0.5) == 1.0)
239
+ check("从未访问不得白拿刷新(last_access=0 ⇒ 1.0)",
240
+ F.refresh_factor(0, 0, 0.9) == 1.0)
241
+
242
+
243
+ def g4_floor():
244
+ print("== G4 衰减必加 floor / 保护线不被穿过 ==")
245
+ g = F.resolve_gamma()
246
+ check("老节点 ≥ SCORE_FLOOR",
247
+ F.decay_factor(g, 10000.0) >= F.SCORE_FLOOR)
248
+ check("缺 created_at 的节点仍带非零分(不乘成 0)",
249
+ F.entry_weight({"created_at": 0, "importance": 0.5})[0] > 0.0,
250
+ str(F.entry_weight({"created_at": 0, "importance": 0.5})[0]))
251
+ check("缺 created_at 的衰减项触 floor(decay 本身 = SCORE_FLOOR)",
252
+ F.decay_factor(g, float("inf")) == F.SCORE_FLOOR)
253
+ for imp in (0.70, 0.8, 0.95, 1.0):
254
+ w = F.entry_weight({"created_at": REF - 3650 * DAY,
255
+ "importance": imp, "protected": True}, now=REF)[0]
256
+ if not (imp * w >= W.IMPORTANCE_PROTECT):
257
+ check(f"受保护节点 importance={imp} 乘子不穿保护线", False,
258
+ f"imp*w={imp * w}")
259
+ return
260
+ check("受保护节点:importance × 乘子 ≥ IMPORTANCE_PROTECT(跨越 1/10/100 个半衰期)",
261
+ True)
262
+ # #378(2026-10-14)夹具更正:原夹具只写 importance=0.8 而**不带来源标注**
263
+ # ——按本仓保护规则(protect.is_protected,AUTO_PROTECT_IMPORTANCE=0.70)
264
+ # 那是「**缺省来源**高分」=受保护节点,与「未保护节点」的断言前提冲突
265
+ # (且写侧对 importance≥0.70 本就会自动置保护位 ⇒ 该 dict 不对应任何真实
266
+ # 节点)。补上显式非 hint 来源后前提重新成立,断言一字未动(数值前提
267
+ # importance=0.8 亦保留)。
268
+ w_free = F.entry_weight({"created_at": REF - 3650 * DAY,
269
+ "importance": 0.8,
270
+ "importance_source": "heuristic"}, now=REF)[0]
271
+ check("判别力:未保护节点不享有该下界(乘子触 floor)",
272
+ abs(w_free - F.SCORE_FLOOR) < 1e-12, str(w_free))
273
+ check("保护下限口径取自 weights.IMPORTANCE_PROTECT(单一真源)",
274
+ F.IMPORTANCE_PROTECT == W.IMPORTANCE_PROTECT == 0.70)
275
+
276
+
277
+ def g5_same_multiplier_slot():
278
+ print("== G5 落位:与分池权重同一乘子位 ==")
279
+ root, cg = _lib()
280
+ try:
281
+ os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
282
+ src = _src(os.path.join("md_cg", "mdcg.py"))
283
+ lines = src.splitlines()
284
+ i = next(n for n, l in enumerate(lines)
285
+ if l.startswith(" def _score(self, docs, q, qb"))
286
+ seg = lines[i:i + 120]
287
+ jd = next(n for n, l in enumerate(seg)
288
+ if "raw * pooling.weight_of(" in l)
289
+ kd = next(n for n, l in enumerate(seg)
290
+ if "raw * freshness.entry_weight(" in l)
291
+ check("乘子行与分池权重行同处一个语句块(中间只有注释、无空行)",
292
+ 0 < kd - jd <= 12
293
+ and all(l.strip() for l in seg[jd + 1:kd]),
294
+ f"pooling 行={jd} 乘子行={kd}")
295
+ # N274:乘子行改为「调用跨两行」形态(循环外提升后追加
296
+ # now/gamma/enabled 关键字透传)——判据性质不变(仍要求乘子**直接
297
+ # 乘在 raw 上**、同一乘子位、以 [0] 取乘子),仅匹配形态同步为
298
+ # 跨行;并顺带收紧为「行首即 raw = raw * …」。
299
+ check("乘子直接乘在 raw 上(同一乘子位,不新开乘子链)",
300
+ seg[kd].strip().startswith("raw = raw * freshness.entry_weight(")
301
+ and "[0]" in (seg[kd] + seg[kd + 1]), # 单行/跨行两形态皆可
302
+ f"kd 行={seg[kd]!r} 次行={seg[kd + 1]!r}")
303
+ # 行为:同内容两节点,仅 created_at 不同 → 分数比 == 乘子比
304
+ scored = _score_pair(cg)
305
+ m_new = F.entry_weight(cg.index["nodes"]["k_new"], now=REF)[0]
306
+ m_old = F.entry_weight({"created_at": REF - 300 * DAY,
307
+ "importance": 0.5}, now=REF)[0]
308
+ got = scored[0][1] / scored[1][1]
309
+ check("_score 的同内容两节点分数比 == 乘子比(乘子确实进了主分数)",
310
+ abs(got - (1.0 * m_new) / (1.0 * m_old)) < 1e-9,
311
+ f"got={got} want={m_new / m_old}")
312
+ check("旧节点被衰减(ratio > 1 且旧节点分更低)",
313
+ scored[0][1] > scored[1][1], str(scored))
314
+ finally:
315
+ os.environ.pop("MDCG_FRESHNESS_NOW", None)
316
+ cg.close()
317
+
318
+
319
+ def g6_index_entry_data():
320
+ print("== G6 取数:access_count / last_access 进索引条目(检索期不读盘)==")
321
+ root, cg = _lib()
322
+ try:
323
+ e = cg.index["nodes"]["k_new"]
324
+ check("条目含 access_count", "access_count" in e, str(sorted(e)[:5]))
325
+ check("条目含 last_access", "last_access" in e)
326
+ check("条目含 created_at(Δt 的输入)", e.get("created_at") == REF,
327
+ str(e.get("created_at")))
328
+ w, why = F.entry_weight(e)
329
+ check("只凭条目即可算乘子(entry_weight 无 IO)",
330
+ isinstance(w, float) and why.get("unit") == F.DT_UNIT, str(why))
331
+ check("单位依据如实标为 day", why.get("unit") == "day")
332
+ finally:
333
+ cg.close()
334
+
335
+
336
+ def g7_switch():
337
+ print("== G7 开关可回退(MDCG_FRESHNESS=0 与基线逐位一致)==")
338
+ root, cg = _lib()
339
+ try:
340
+ os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
341
+ on = [round(s, 12) for _d, s in _score_pair(cg)]
342
+ os.environ["MDCG_FRESHNESS"] = "0"
343
+ off = [round(s, 12) for _d, s in _score_pair(cg)]
344
+ os.environ.pop("MDCG_FRESHNESS", None)
345
+ check("关时乘子恒 1.0",
346
+ F.entry_weight(cg.index["nodes"]["k_new"])[0] == 1.0
347
+ if os.environ.get("MDCG_FRESHNESS") == "0" else True)
348
+ check("开/关两态下分数不同(开关真的有作用)", on != off,
349
+ f"{on} vs {off}")
350
+ check("关态 = 无乘子基线(两节点分数相同)", abs(off[0] - off[1]) < 1e-12,
351
+ str(off))
352
+ finally:
353
+ os.environ.pop("MDCG_FRESHNESS", None)
354
+ os.environ.pop("MDCG_FRESHNESS_NOW", None)
355
+ cg.close()
356
+
357
+
358
+ def g8_triplet():
359
+ print("== G8 三件套:预演 / 逐节点留痕 / 反向 apply ==")
360
+ root, cg = _lib()
361
+ try:
362
+ os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
363
+ src_a = _tree_hash(root)
364
+ pre = F.recalc(cg, apply=False)
365
+ check("预演:dry_run=True 且零写盘(源面逐字节不变)",
366
+ pre["dry_run"] is True and _tree_hash(root) == src_a, str(pre["written"]))
367
+ check("预演给出逐节点 before/after 样本", bool(pre["samples"]),
368
+ str(pre["samples"][:1]))
369
+ check("预演不改 frontmatter",
370
+ (cg.get("k_old")["frontmatter"].get("freshness_weight") is None))
371
+ res = F.recalc(cg, apply=True, min_delta=0.0)
372
+ check("apply:written ≥ 1", res["written"] >= 1, str(res["written"]))
373
+ fm = cg.get("k_old")["frontmatter"]
374
+ check("apply 写入 freshness_weight(与乘子一致)",
375
+ abs(float(fm.get("freshness_weight")) -
376
+ F.entry_weight({"created_at": REF - 300 * DAY,
377
+ "importance": 0.5}, now=REF)[0]) < 1e-9,
378
+ str(fm.get("freshness_weight")))
379
+ log = os.path.join(cg.root, W.MAINTAIN_LOG)
380
+ recs = [json.loads(x) for x in
381
+ open(log, encoding="utf-8").read().splitlines() if x.strip()]
382
+ mine = [r for r in recs if r.get("action") == "freshness"]
383
+ check("逐节点留痕:_maintain.jsonl 有 action=freshness 记录",
384
+ bool(mine), str([r.get("action") for r in recs]))
385
+ check("留痕含 before/after(逐节点)",
386
+ all(("before" in r and "after" in r) for r in mine),
387
+ json.dumps(mine[:1], ensure_ascii=False))
388
+ check("与 weights 的 action=importance 同族(同一 log 文件)",
389
+ W.MAINTAIN_LOG == F.MAINTAIN_LOG == "_maintain.jsonl")
390
+ rb = F.rollback(cg)
391
+ check("rollback:reverted ≥ 1 且写回 before", rb["reverted"] >= 1, str(rb))
392
+ fm2 = cg.get("k_old")["frontmatter"]
393
+ check("rollback 后 freshness_weight 回到 before",
394
+ abs(float(fm2.get("freshness_weight") or 0.0) - 1.0) < 1e-9,
395
+ str(fm2.get("freshness_weight")))
396
+ _p = (cg.index["nodes"].get("k_old") or {}).get("path") or ""
397
+ check("rollback 后节点仍在索引(不删记录)",
398
+ "k_old" in cg.index["nodes"] and bool(_p)
399
+ and os.path.exists(os.path.join(cg.root, _p)), _p)
400
+ check("rollback 自身再记一条留痕",
401
+ any(r.get("action") == "freshness_rollback"
402
+ for r in [json.loads(x) for x in
403
+ open(log, encoding="utf-8").read().splitlines()
404
+ if x.strip()]))
405
+ finally:
406
+ os.environ.pop("MDCG_FRESHNESS_NOW", None)
407
+ cg.close()
408
+
409
+
410
+ def g9_degrade_not_delete():
411
+ print("== G9 降级 = 标记(不是删除);跨层降级走 guard_move ==")
412
+ root = tempfile.mkdtemp(prefix="p4_deg_")
413
+ cg = MdCGOS(root)
414
+ try:
415
+ _mk(cg, "k_prot", importance=0.8) # ≥0.70 ⇒ 自动打保护
416
+ _mk(cg, "k_plain", importance=0.5, created_at=REF - 300 * DAY)
417
+ cg.flush()
418
+ os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
419
+ e0 = dict(cg.index["nodes"]["k_prot"])
420
+ check("夹具前提:节点受保护", bool(e0.get("protected")),
421
+ str(e0.get("protected")))
422
+ check("bind_move_layer 现绑既有 `_move_layer`(不新写搬迁路径)",
423
+ F.bind_move_layer(cg) is True)
424
+ res = F.recalc(cg, apply=True, min_delta=0.0)
425
+ fm_p = cg.get("k_plain")["frontmatter"]
426
+ _pp = (cg.index["nodes"].get("k_plain") or {}).get("path") or ""
427
+ check("衰减到阈值下的节点被标 degraded(**只标记**)",
428
+ fm_p.get("freshness_state") == "degraded", str(fm_p.get(
429
+ "freshness_state")))
430
+ check("被标 degraded 的节点与正文原样在库(降级 ≠ 删除记录)",
431
+ os.path.exists(os.path.join(cg.root, _pp))
432
+ and "k_plain" in cg.index["nodes"], _pp)
433
+ check("受保护节点**不被**降级(保护下界生效)",
434
+ (cg.get("k_prot")["frontmatter"].get("freshness_state")
435
+ in (None, "")), str(cg.get("k_prot")["frontmatter"].get(
436
+ "freshness_state")))
437
+ check("报表给出降级计数", "degraded" in res, str(sorted(res)))
438
+ # 跨层降级:受保护节点被移出保护层 → guard_move 抛错且无副作用
439
+ import md_cg.protect as P
440
+ before = cg.get("k_prot")["frontmatter"].get("layer")
441
+ try:
442
+ cg._move_layer("k_prot", "contextual", reason="guard 试")
443
+ moved = True
444
+ except P.ProtectionError:
445
+ moved = False
446
+ check("受保护节点降级被 guard_move 拒绝(ProtectionError)", moved is False)
447
+ check("拒绝后节点层位与记录未变(无副作用)",
448
+ cg.get("k_prot")["frontmatter"].get("layer") == before
449
+ and "k_prot" in cg.index["nodes"])
450
+ check("fixture 未因降级被删除(降级 ≠ 删除记录)",
451
+ "k_prot" in cg.index["nodes"] and "k_plain" in cg.index["nodes"])
452
+ check("非保护节点可被搬迁(同一闸的两侧对照)",
453
+ isinstance(cg._move_layer("k_plain", "contextual",
454
+ reason="guard 对照"), dict))
455
+ finally:
456
+ os.environ.pop("MDCG_FRESHNESS_NOW", None)
457
+ cg.close()
458
+
459
+
460
+ def g10_weights_autoprotect_kept():
461
+ print("== G10 weights.recalc 的 ≥0.70 自动补写 protected 仍在位 ==")
462
+ src = _src(os.path.join("md_cg", "weights.py"))
463
+ check("weights.py 仍含 IMPORTANCE_PROTECT 常量与自动补写分支",
464
+ "IMPORTANCE_PROTECT = 0.70" in src
465
+ and 'fm["protected"] = True' in src)
466
+ root = tempfile.mkdtemp(prefix="p4_w_")
467
+ cg = MdCGOS(root)
468
+ try:
469
+ _mk(cg, "hub", importance=0.2, verification_basis="formal_proof")
470
+ for i in range(12):
471
+ cg.add(f"leaf{i}", BODY.format(n=f"leaf{i}", t=f"leaf{i} 正文"),
472
+ layer="knowledge", importance=0.1,
473
+ edges=[{"target": "hub", "relation_type": "causal"}])
474
+ cg.flush()
475
+ rep = W.recalc(cg, apply=True, min_delta=0.0)
476
+ fm = cg.get("hub")["frontmatter"]
477
+ check("重算后 after ≥ 0.70 ⇒ 自动补写 protected",
478
+ float(fm.get("importance") or 0) >= W.IMPORTANCE_PROTECT
479
+ and fm.get("protected") is True,
480
+ f"imp={fm.get('importance')} protected={fm.get('protected')}")
481
+ check("recalc 报表结构未变(预演/留痕/回滚三件套仍在)",
482
+ {"dry_run", "samples", "log"} <= set(rep), str(sorted(rep)))
483
+ finally:
484
+ cg.close()
485
+
486
+
487
+ def g11_rust_parity():
488
+ print("== G11 Rust 侧同口径(常量 + 生效面)==")
489
+ rs = _src(os.path.join("rust", "src", "freshness.rs"))
490
+ for name, val in (("SCORE_FLOOR", "0.001"), ("SECONDS_PER_DAY", "86400.0"),
491
+ ("IMPORTANCE_PROTECT", "0.70"), ("DECAY_DAYS", "30.0")):
492
+ check(f"rust 常量 {name} 与 Python 同值",
493
+ f"pub const {name}: f64 = {val};" in rs, name)
494
+ for name, val in (("REHEARSAL_THRESHOLD", "0.7"),
495
+ ("DEGRADE_THRESHOLD", "0.2"), ("GAIN", "0.01")):
496
+ check(f"rust 参数 {name} 照抄 AEIS({val})",
497
+ f"const {name}: f64 = {val};" in rs, name)
498
+ ret = _src(os.path.join("rust", "src", "retrieval.rs"))
499
+ check("sort_path 带 apply_freshness 开关",
500
+ "pub fn sort_path(hits: &mut [Hit], docs: &[Option<Doc>],"
501
+ " apply_freshness: bool)" in ret)
502
+ check("fuse 只对 lexical 路开乘子(与 Python `_score` 对位)",
503
+ 'sort_path(&mut h, docs, *name == "lexical")' in ret)
504
+ eng = _src(os.path.join("rust", "src", "engine.rs"))
505
+ check("graph 种子排序带乘子(种子取自 lexical 路)",
506
+ "retrieval::sort_path(&mut v, docs, true);" in eng)
507
+ check("Rust 侧有核/参数的单测(半衰期、floor、保护线、演练闸)",
508
+ rs.count("#[test]") >= 4, str(rs.count("#[test]")))
509
+
510
+
511
+ # --------------------------------------------------------------------------
512
+ # 定点变异(只改本进程内存对象/临时文件,绝不改仓库文件)
513
+ # --------------------------------------------------------------------------
514
+
515
+ def g12_rust_parity_e2e():
516
+ """P4-2② 双侧同改的**端到端逐位对拍**(判别力夹具,非 rank_parity 现有语料)。
517
+
518
+ 为什么必须另造夹具:`scripts/rank_parity.py` 的语料是**新建节点**(Δt=0 天
519
+ ⇒ 乘子恒 1.0)、无 edges/无时间参数/无六要素后两行 ⇒ 对 P4 乘子**零判别力**
520
+ (实测:改前 10/10、改后 10/10、改后 Python + 改前 Rust 二进制亦 10/10)。
521
+ 只有把「同分不同龄」的节点放进去,乘子才改变路内名次,两侧才可能劈叉。
522
+
523
+ 夹具:6 个**正文逐字相同**(词法分并列)的节点,created_at 跨度 0/30/300 天,
524
+ importance 随年龄递增(未乘者按 (-score,-importance,id) 会「越老越靠前」);
525
+ `MDCG_FRESHNESS_NOW` 钉死 → 两侧同一参照时刻。断言:
526
+ ① 改后两侧 top-k **逐位一致**(Python `search_rrf` vs Rust `--serve`);
527
+ ② 夹具**有判别力**:把 Python 侧乘子关掉,名次与 ① 不同(否则本对拍空转)。
528
+ 二进制缺失 = fail-closed 红(「跑不起来」永不算通过)。
529
+ """
530
+ exe = os.path.join(_REPO, "rust", "target", "release",
531
+ "mdcg-eval.exe" if os.name == "nt" else "mdcg-eval")
532
+ if not os.path.isfile(exe):
533
+ check("Rust 二进制在位(逐位对拍的另一侧)", False,
534
+ f"{exe} 不存在——先 cd rust && cargo build --release")
535
+ return
536
+ sys.path.insert(0, os.path.join(_REPO, "scripts"))
537
+ import rank_parity as RP # noqa: E402
538
+ py_mode, conflict = RP.pin_python_score_mode()
539
+ if py_mode != "jaccard" or conflict:
540
+ check("Python 侧口径可钉住(eval_common.use_jaccard)", False,
541
+ f"{py_mode} / {conflict}")
542
+ return
543
+ root = tempfile.mkdtemp(prefix="p4_parity_")
544
+ cg = MdCGOS(root)
545
+ ages = (0.0, 0.0, 30.0, 30.0, 300.0, 300.0)
546
+ for i, age in enumerate(ages):
547
+ # importance 全部 < 0.70(避开自动保护 → 不受保护下界豁免衰减)
548
+ # 且全部 ≥ 0.20(避开 AEIS 降权档),年龄越大 importance 越高 ⇒
549
+ # 「未乘者越老越靠前」,乘子一到即翻转
550
+ _mk(cg, f"p{i}", created_at=REF - age * DAY,
551
+ importance=0.20 + 0.04 * i, tags=[])
552
+ cg.flush()
553
+ q = "苹果 章节"
554
+ os.environ["MDCG_FRESHNESS_NOW"] = repr(REF)
555
+ try:
556
+ py = [(x[0]["id"], round(float(x[1]), 6))
557
+ for x in cg.search_rrf(q, k=6, record=False)[0]]
558
+ os.environ["MDCG_FRESHNESS"] = "0"
559
+ off = [(x[0]["id"], round(float(x[1]), 6))
560
+ for x in cg.search_rrf(q, k=6, record=False)[0]]
561
+ os.environ.pop("MDCG_FRESHNESS", None)
562
+ try:
563
+ proc, rs_mode = RP.rust_open(exe, root)
564
+ except Exception as exc: # noqa: BLE001
565
+ check("Rust serve 可拉起且自报口径", False, str(exc)[:200])
566
+ cg.close()
567
+ return
568
+ try:
569
+ rs = RP.rust_topk(proc, [q], k=6)[q]
570
+ finally:
571
+ pass
572
+ rs2 = [(i, None if s is None else round(float(s), 6)) for i, s in rs]
573
+ print(f" py(new)={py}")
574
+ print(f" rust ={rs2}")
575
+ print(f" py(off)={off}")
576
+ check("① 两侧 top-k 逐位一致(同乘子、同口径)",
577
+ [i for i, _s in py] == [i for i, _s in rs2],
578
+ f"{[i for i, _s in py]} vs {[i for i, _s in rs2]}")
579
+ check("② 夹具判别力:关掉乘子后名次不同(本对拍非空转)",
580
+ [i for i, _s in py] != [i for i, _s in off],
581
+ f"{[i for i, _s in py]} vs {[i for i, _s in off]}")
582
+ check("② 乘子使「新节点靠前、旧节点靠后」",
583
+ [i for i, _s in py][0] in ("p0", "p1")
584
+ and [i for i, _s in py][-1] in ("p4", "p5"),
585
+ f"{[i for i, _s in py]}")
586
+ finally:
587
+ os.environ.pop("MDCG_FRESHNESS_NOW", None)
588
+ cg.close()
589
+ import shutil
590
+ shutil.rmtree(root, ignore_errors=True)
591
+
592
+
593
+ def g13_hot_loop_reads():
594
+ """N274:freshness 读取点全部提升到 `_score` 循环外(调用计数判据)。
595
+
596
+ 判据=**与文档数无关**:同一 `_score` 调用于 2 节点与 20 节点两批文档
597
+ 时,`enabled`/`freshness_now`/`resolve_gamma`/`temporal_gamma` 的调用
598
+ 计数相同。修前(8000 池实测,2026-10-05)为每节点 7 次(enabled 4×N
599
+ + now/γ/temporal 各 N);墙钟只作辅助,不作判据。
600
+ """
601
+ print("== G13 freshness 读取提升到 _score 循环外(N274)==")
602
+ import md_cg.mdcos as MC
603
+ root, cg = _lib()
604
+ c = {"enabled": 0, "now": 0, "gamma": 0, "temporal": 0}
605
+ orig = {n: getattr(F, n) for n in ("enabled", "freshness_now",
606
+ "resolve_gamma")}
607
+ orig_tg = MC.temporal_gamma
608
+
609
+ def _wrap(fn, key):
610
+ def _w(*a, **k):
611
+ c[key] += 1
612
+ return fn(*a, **k)
613
+ return _w
614
+
615
+ F.enabled = _wrap(orig["enabled"], "enabled")
616
+ F.freshness_now = _wrap(orig["freshness_now"], "now")
617
+ F.resolve_gamma = _wrap(orig["resolve_gamma"], "gamma")
618
+ MC.temporal_gamma = _wrap(orig_tg, "temporal")
619
+ try:
620
+ def _mk_docs(n):
621
+ return [({"path": "knowledge/k%d.md" % i},
622
+ {"id": "k%d" % i, "tags": [],
623
+ "created_at": REF - i * DAY, "access_count": 0,
624
+ "last_access": 0, "importance": 0.5},
625
+ BODY.format(n="k%d" % i, t="k%d 正文 苹果 章节" % i))
626
+ for i in range(n)]
627
+
628
+ def _count(docs):
629
+ for k in c:
630
+ c[k] = 0
631
+ cg._score(docs, "苹果 章节",
632
+ M.bigrams(M.normalize_en("苹果 章节")))
633
+ return dict(c)
634
+
635
+ c2 = _count(_mk_docs(2))
636
+ c20 = _count(_mk_docs(20))
637
+ # 判据面=**env 读取三面**(enabled / freshness_now / temporal_gamma
638
+ # ——后者是 γ 的实际读取点:resolve_gamma 的 early-return 分支不碰
639
+ # temporal_gamma,故「temporal_gamma 常数」即「γ 的 env 读取归零」)。
640
+ # 诚实边界:resolve_gamma 的**函数调用**仍每节点一次(early-return
641
+ # 直通已解析的 float,~0.15µs/节点、不读 env)——保留它是因为
642
+ # resolve_gamma 还承担「非法 gamma 回落缺省」的单点边界语义,跳过
643
+ # 调用会改变该边界。
644
+ check("env 读取面与文档数无关(enabled/now/temporal;修前各 N×)",
645
+ {k: c2[k] for k in ("enabled", "now", "temporal")}
646
+ == {k: c20[k] for k in ("enabled", "now", "temporal")},
647
+ f"c2={c2} c20={c20}")
648
+ check("enabled() 常数级(修前 = 4×N)", c20["enabled"] <= 2, str(c20))
649
+ check("freshness_now() 常数级(修前 = 1×N)", c20["now"] <= 1, str(c20))
650
+ check("temporal_gamma() 常数级(修前 = 1×N;γ 的实际读取点)",
651
+ c20["temporal"] <= 1, str(c20))
652
+ # 自证腿(常驻):全缺省签名的旧路径仍自算,四个 spy 数得到——证明
653
+ # 上面的「零/常数」不是 spy 失效造成的假绿(判别力在位)。
654
+ for k in c:
655
+ c[k] = 0
656
+ F.entry_weight({"created_at": REF, "importance": 0.5})
657
+ check("自证腿:全缺省签名仍自算(四路 spy 各 ≥1,判别力在位)",
658
+ c["enabled"] >= 1 and c["now"] >= 1 and c["gamma"] >= 1
659
+ and c["temporal"] >= 1, str(c))
660
+ # 语义等价:显式透传与自算逐位同值;关闭恒 1.0(三面同口径)
661
+ e0 = {"created_at": REF - 30 * DAY, "importance": 0.5}
662
+ check("显式 enabled+now+γ 透传与自算同值(逐位一致)",
663
+ F.entry_weight(e0, now=REF)[0]
664
+ == F.entry_weight(e0, now=REF, gamma=F.resolve_gamma(None),
665
+ enabled=True)[0])
666
+ check("enabled=False 恒 1.0(entry/decay/refresh 三面同口径)",
667
+ F.entry_weight(e0, now=REF, enabled=False)[0] == 1.0
668
+ and F.decay_factor(0.023, 100.0, enabled=False) == 1.0
669
+ and F.refresh_factor(0, 0, 0.9, enabled=False) == 1.0)
670
+ finally:
671
+ F.enabled = orig["enabled"]
672
+ F.freshness_now = orig["freshness_now"]
673
+ F.resolve_gamma = orig["resolve_gamma"]
674
+ MC.temporal_gamma = orig_tg
675
+ cg.close()
676
+ import shutil
677
+ shutil.rmtree(root, ignore_errors=True)
678
+
679
+
680
+ def _mut_floor_zero():
681
+ return _patch(F, "SCORE_FLOOR", 0.0)
682
+
683
+
684
+ def _mut_gain_10x():
685
+ orig = dict(F.REFRESH_PARAMS)
686
+
687
+ def restore():
688
+ F.REFRESH_PARAMS.clear()
689
+ F.REFRESH_PARAMS.update(orig)
690
+ F.REFRESH_PARAMS["gain"] = 0.1
691
+ return restore
692
+
693
+
694
+ def _mut_unit_seconds():
695
+ return _patch(F, "SECONDS_PER_DAY", 1.0)
696
+
697
+
698
+ def _mut_protect_floor_off():
699
+ orig = F.protected_floor
700
+ F.protected_floor = lambda entry: F.SCORE_FLOOR
701
+
702
+ def restore():
703
+ F.protected_floor = orig
704
+ return restore
705
+
706
+
707
+ def _mut_switch_off():
708
+ return _patch(F, "enabled", lambda environ=None: False)
709
+
710
+
711
+ def _patch(mod, name, value):
712
+ orig = getattr(mod, name)
713
+
714
+ def restore():
715
+ setattr(mod, name, orig)
716
+ setattr(mod, name, value)
717
+ return restore
718
+
719
+
720
+ _MUTATIONS = [
721
+ ("floor_zero", "衰减 floor 归零", _mut_floor_zero),
722
+ ("gain_10x", "刷新步长改成 0.1(脱离 AEIS 取值)", _mut_gain_10x),
723
+ ("unit_seconds", "Δt 单位改成「秒」", _mut_unit_seconds),
724
+ ("protect_floor_off", "去掉受保护节点的保护下界", _mut_protect_floor_off),
725
+ ("switch_off", "乘子开关恒关", _mut_switch_off),
726
+ ]
727
+
728
+
729
+ def _collect():
730
+ global PASS, FAIL, FAILS
731
+ PASS, FAIL, FAILS = 0, 0, []
732
+ g1_core_authority()
733
+ g2_gamma_and_unit()
734
+ g3_refresh_params()
735
+ g4_floor()
736
+ g5_same_multiplier_slot()
737
+ g6_index_entry_data()
738
+ g7_switch()
739
+ g8_triplet()
740
+ g9_degrade_not_delete()
741
+ g10_weights_autoprotect_kept()
742
+ g11_rust_parity()
743
+ g12_rust_parity_e2e()
744
+ g13_hot_loop_reads()
745
+ return list(FAILS)
746
+
747
+
748
+ def main(argv):
749
+ if "--mutate" in argv:
750
+ if "--list" in argv:
751
+ for name, desc, _fn in _MUTATIONS:
752
+ print(f" {name:20s} {desc}")
753
+ return 0
754
+ base = _collect()
755
+ if base:
756
+ print(f"\n!! 基线不绿({len(base)} 条):{base}")
757
+ return 1
758
+ bad = []
759
+ for name, desc, fn in _MUTATIONS:
760
+ try:
761
+ restore = fn()
762
+ except AttributeError as exc:
763
+ print(f" ANCHOR-MISS {name}: {exc}")
764
+ return 2
765
+ got = _collect()
766
+ restore()
767
+ if got:
768
+ print(f" MUTATE-OK {name}({desc})→ 转红 {len(got)} 条:{got[:3]}")
769
+ else:
770
+ bad.append(name)
771
+ print(f" MUTATE-FAIL {name}({desc})→ 仍全绿")
772
+ print(f"\ntest_p4_freshness --mutate: "
773
+ f"{len(_MUTATIONS) - len(bad)}/{len(_MUTATIONS)} 变异按预期转红")
774
+ return 0 if not bad else 1
775
+ fails = _collect()
776
+ print(f"\ntest_p4_freshness: {PASS} 通过 / {FAIL} 失败")
777
+ return 0 if not fails else 1
778
+
779
+
780
+ if __name__ == "__main__":
781
+ sys.exit(main(sys.argv[1:]))