astrbot_plugin_private_comp.../tests/test_provider_readiness.py
YokiiroBW 2518f7b6bf fix: make the daily plan chain survive startup timing and same-day rewrites
Two defects that only showed up on the real machine, both of which left the
schedule frozen on a fallback plan with nothing in the logs to say so.

The plugin asked for a chat provider 0.8s before AstrBot finished loading
them, wrote a template fallback, and stamped it with today's date -- so the
next 24 hours never retried. Resolution now falls back through get_config()
(4.26.6's Context exposes nothing else) and validates the configured id with
get_provider_by_id, because a configured default is not a loaded instance.
When nothing is ready yet the round is skipped instead of downgraded, up to
DAILY_PLAN_PROVIDER_MAX_WAITS rounds.

Once the model recovered, the real plan still could not reach the archive:
the idempotency key is always daily_plan:<date> but the plan dict never
carried a version, so every rewrite re-sent v1 and the memory side rejected
it as version_conflict. The companion swallowed that -- outbox state is only
touched when enqueue accepts, and a same key/version enqueue does not. Plans
now carry a version watermark drawn from both daily_plan and its history, and
any ok=False archive response logs a warning regardless of outbox state.

Verified on the VM: provider wait counted once and no fallback written, plan
generated at v2 with 10 segments from the model, and the stored record
upserted from the 8-segment fallback to the same v2 content.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 04:16:06 +08:00

133 行
5.1 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

# -*- coding: utf-8 -*-
"""对话 Provider 就绪判定回归。
插件的主动循环比 AstrBot 装载 provider 早(实测早 0.8 秒),重启后第一轮维护
去要 provider 时注册表还是空的。此前这会被当成「模型不可用」,直接把模板兜底
写成当天日程——而兜底一旦带上今天的日期,后续 24 小时都不会再生成,一次 0.8 秒
的启动时序问题毁掉一整天。
"""
from __future__ import annotations
import importlib
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()
_PKG = "_prov_companion"
_pkg = types.ModuleType(_PKG)
_pkg.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])]
sys.modules.setdefault(_PKG, _pkg)
token_budget = importlib.import_module(f"{_PKG}.token_budget")
class FakeProvider:
def __init__(self, provider_id):
self._id = provider_id
def meta(self):
return types.SimpleNamespace(id=self._id)
class Ctx:
"""模拟 AstrBot Context 的三条取值路径,可分别关掉。"""
def __init__(self, using=None, all_providers=None, config=None, registered=None):
self._using = using
self._all = all_providers or []
self._config = config
# 已真正注册的实例;配置里写了 id 不等于实例已装载
self._registered = set(registered or [])
def get_provider_by_id(self, provider_id):
return FakeProvider(provider_id) if provider_id in self._registered else None
def get_using_provider(self, umo=None):
return self._using
def get_all_providers(self):
return list(self._all)
def get_config(self):
return self._config
# 直接继承真实 Mixin:用 setattr 搬运会把 staticmethod 变成实例方法
class Host(token_budget.TokenBudgetMixin):
def __init__(self, context=None, llm_provider_id=""):
self.context = context
self.llm_provider_id = llm_provider_id
self.data = {}
def make(**kwargs):
return Host(**kwargs)
class ProviderReadinessTests(unittest.TestCase):
def test_not_ready_when_registry_is_empty(self):
"""启动竞态:provider 一个都还没装载。"""
host = make(context=Ctx(using=None, all_providers=[], config={}))
self.assertFalse(host._chat_provider_ready())
def test_ready_via_get_using_provider(self):
host = make(context=Ctx(using=FakeProvider("BOT 1X/gpt-5.6-terra")))
self.assertTrue(host._chat_provider_ready())
self.assertEqual(host._default_chat_provider_id(), "BOT 1X/gpt-5.6-terra")
def test_falls_back_to_registry_listing(self):
"""get_using_provider 取不到时,注册表里已有 provider 也算就绪。"""
host = make(context=Ctx(using=None, all_providers=[FakeProvider("浅夜 1X/grok-4.5")]))
self.assertEqual(host._default_chat_provider_id(), "浅夜 1X/grok-4.5")
self.assertTrue(host._chat_provider_ready())
def test_falls_back_to_astrbot_config_when_instance_exists(self):
"""4.26.6 的 Context 只有 get_config(),没有 astrbot_config/config 属性。"""
host = make(context=Ctx(using=None, all_providers=[],
config={"provider_settings": {"default_provider_id": "BOT 1X/gpt-5.6-terra"}},
registered=["BOT 1X/gpt-5.6-terra"]))
self.assertEqual(host._default_chat_provider_id(), "BOT 1X/gpt-5.6-terra")
def test_configured_id_without_a_loaded_instance_is_not_ready(self):
"""启动竞态的真实形态:配置里有默认 provider id,实例却还没注册。
误判为就绪会拿到 "Provider ... not found",并把模板兜底固化成当天日程。"""
host = make(context=Ctx(using=None, all_providers=[],
config={"provider_settings": {"default_provider_id": "BOT 1X/gpt-5.6-terra"}},
registered=[]))
self.assertEqual(host._default_chat_provider_id(), "")
self.assertFalse(host._chat_provider_ready())
def test_explicit_plugin_provider_short_circuits(self):
"""插件显式配了 provider 就不必等 AstrBot 注册表。"""
host = make(context=Ctx(using=None, all_providers=[]),
llm_provider_id="浅夜 1X/gemini-3.6-flash-high")
self.assertTrue(host._chat_provider_ready())
def test_broken_context_does_not_raise(self):
class Boom:
def get_using_provider(self, umo=None):
raise RuntimeError("boom")
def get_all_providers(self):
raise RuntimeError("boom")
def get_config(self):
raise RuntimeError("boom")
host = make(context=Boom())
self.assertFalse(host._chat_provider_ready())
def test_max_waits_is_five(self):
"""与「5 分钟一次、共 5 次」的重试口径对齐;tick 本身 300 秒。"""
daily_state = importlib.import_module(f"{_PKG}.daily_state")
self.assertEqual(daily_state.DAILY_PLAN_PROVIDER_MAX_WAITS, 5)
if __name__ == "__main__":
unittest.main()