astrbot_plugin_private_comp.../tests/test_p0_runtime_fixes.py

143 行
6.5 KiB
Python

fix: clear the three P0 defects that were bleeding in production All three shared a shape: the symptom was invisible from the data, so every acceptance run stayed green while the VM was failing. daily_state still called _ensure_daily_news_reading, removed when the news feature was retired. The VM threw AttributeError 14 times in three hours and marked the "today's schedule" maintenance step failed, but the crash sits after the plan is saved -- so the stored plan always looked correct. Removed the call and added a repo-wide scan rather than a single-point assertion, since this kind of residue is by definition somewhere you did not look. enable_memory_companion_bridge, the master switch for the whole archive chain, was never added to _conf_schema.json. _cfg_bool falls back to True, so the feature worked and only its operability was missing -- nothing could have failed. It now sits in the visible external_memory_config group, with an assertion that _flat_get still resolves it by flat key. A fallback plan carried today's date, and all three reuse branches key on the date alone, so one startup timing hiccup froze a template plan into the day and archived it as real. source="fallback" was produced and never consumed; now a fallback can be upgraded once the provider is back, capped at three attempts and bucketed per day. Also fixed two test files whose classes sat after the __main__ guard (silently dropped when run directly) and the retired-config prefix list, which only listed the uppercase WEB_EXPLORATION_ form and missed the lowercase schema keys. VM after restart: 0 AttributeError, 0 ERRO/Traceback, plan intact at v2/llm, switch materialised as True. Companion suite 218 passed, joint E2E 135/135. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 05:01:56 +08:00
# -*- coding: utf-8 -*-
"""P0 生产缺陷回归(2026-07-27)。
三件事,共同点是「生产在报错/退化,而验收全绿」:
1. `daily_state.py` 还在调用早已被删掉的 `_ensure_daily_news_reading`,
每轮日程维护写盘后必抛 AttributeError,主动循环把「今日日程」标失败并冷却。
计划本身已经保存,所以故障一直藏在「计划看起来是好的」后面。
2. 归档总闸 `enable_memory_companion_bridge` 不在 `_conf_schema.json` 里,
设置页看不到、改了也不落盘——上次整条归档链路静默停摆三天就是同一处开关问题。
3. 兜底日程带上当天日期后,三处复用分支都会直接把它返回,当天不再生成,
于是一次启动时序抖动把模板兜底固化成正式的一天并归档进长期记忆。
"""
from __future__ import annotations
import importlib
import json
import logging
import pathlib
import sys
import types
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
_package_name = "_p0_companion"
_package = types.ModuleType(_package_name)
_package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])]
sys.modules.setdefault(_package_name, _package)
ROOT = pathlib.Path(__file__).resolve().parents[1]
daily_state = importlib.import_module(f"{_package_name}.daily_state")
helpers = importlib.import_module(f"{_package_name}.helpers")
TODAY = "2026-07-27"
class Host(daily_state.DailyStateMixin):
"""只带本组用例需要的状态,其余走 Mixin 真实实现。"""
def __init__(self, plan=None, retry=None, provider_ready=True):
self.data = {}
if plan is not None:
self.data["daily_plan"] = plan
if retry is not None:
self.data["daily_plan_fallback_retry"] = retry
self._provider_ready = provider_ready
self.saves = 0
def _chat_provider_ready(self) -> bool:
return self._provider_ready
def _save_data_sync(self) -> None:
self.saves += 1
class DeadNewsCallTests(unittest.TestCase):
def test_no_production_code_calls_the_removed_news_reader(self):
offenders = []
for path in ROOT.rglob("*.py"):
parts = set(path.parts)
if parts & {"tests", ".tmp", "__pycache__"}:
continue
for num, line in enumerate(path.read_text(encoding="utf-8", errors="ignore").splitlines(), 1):
if "_ensure_daily_news_reading" in line and not line.strip().startswith("#"):
offenders.append(f"{path.name}:{num}")
self.assertEqual(offenders, [], f"仍在调用已删除的新闻阅读实现: {offenders}")
def test_the_method_really_does_not_exist(self):
"""反面证据:它确实没有实现,所以上面的调用点必然是 AttributeError。"""
self.assertFalse(hasattr(daily_state.DailyStateMixin, "_ensure_daily_news_reading"))
class BridgeSwitchSchemaTests(unittest.TestCase):
def setUp(self):
self.schema = json.loads((ROOT / "_conf_schema.json").read_text(encoding="utf-8"))
def test_bridge_switch_is_visible_in_the_external_memory_group(self):
items = self.schema["external_memory_config"]["items"]
self.assertIn("enable_memory_companion_bridge", items)
entry = items["enable_memory_companion_bridge"]
self.assertEqual(entry["type"], "bool")
self.assertIs(entry["default"], True)
self.assertFalse(entry.get("invisible"), "总闸被标成 invisible 就等于设置页还是看不到")
def test_the_switch_is_read_through_the_same_path_main_uses(self):
"""schema 里挂在分组下,main.py 却按扁平键读——_flat_get 必须能穿过分组。"""
config = {"external_memory_config": {"enable_memory_companion_bridge": False}}
self.assertIs(helpers._flat_get(config, "enable_memory_companion_bridge", True), False)
class FallbackUpgradeTests(unittest.TestCase):
def test_fallback_plan_can_be_upgraded_when_provider_is_back(self):
host = Host(plan={"date": TODAY, "source": "fallback"})
self.assertTrue(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_real_plan_is_never_regenerated(self):
host = Host(plan={"date": TODAY, "source": "llm"})
self.assertFalse(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_provider_still_down_means_no_upgrade_attempt(self):
host = Host(plan={"date": TODAY, "source": "fallback"}, provider_ready=False)
self.assertFalse(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_yesterdays_fallback_is_not_upgraded_today(self):
host = Host(plan={"date": "2026-07-26", "source": "fallback"})
self.assertFalse(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_retry_budget_is_capped(self):
limit = daily_state.DAILY_PLAN_FALLBACK_RETRY_LIMIT
host = Host(plan={"date": TODAY, "source": "fallback"})
for expected in range(1, limit + 1):
self.assertTrue(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
self.assertEqual(host._note_daily_plan_fallback_retry(TODAY), expected)
self.assertFalse(
host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY),
"重试次数用尽后仍在尝试,Provider 就绪但生成始终失败时会每个 tick 重跑模型",
)
def test_retry_counter_is_scoped_to_its_own_day(self):
"""昨天用掉的额度不能占掉今天的。"""
host = Host(plan={"date": TODAY, "source": "fallback"},
retry={"date": "2026-07-26", "count": 99})
self.assertEqual(host._daily_plan_fallback_retries(TODAY), 0)
self.assertTrue(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_broken_retry_state_is_tolerated(self):
host = Host(plan={"date": TODAY, "source": "fallback"}, retry="不是字典")
self.assertEqual(host._daily_plan_fallback_retries(TODAY), 0)
def test_note_retry_persists(self):
host = Host(plan={"date": TODAY, "source": "fallback"})
host._note_daily_plan_fallback_retry(TODAY)
self.assertEqual(host.data["daily_plan_fallback_retry"], {"date": TODAY, "count": 1})
self.assertEqual(host.saves, 1, "重试计数必须落盘,否则重启后额度重置")
if __name__ == "__main__":
unittest.main()