Compare commits

..
Author SHA1 Message Date
bot_dev1 03ae81a217 feat(#57): InferenceBackend 抽象接口定义(PRD 5.6 loadModel/infer/health/unload)
将原先内联在 gateway.py 的薄弱 InferenceBackend 提炼为正式抽象基类(ABC),
对齐 PRD 5.6「⑥ 部署底座」契约,为 #44/#45/#58/#59 各类后端提供统一接入点。

实现内容:
- 新增 core/llm-gateway/backends.py:
  · InferenceBackend(ABC):PRD 要求的四个生命周期方法 load_model / infer /
    health_check / unload(均幂等),能力声明 capabilities,并保留 generate()
    向后兼容(转发到 infer().text)
  · 值对象 BackendCapabilities(streaming/max_concurrency/on_premises/modalities)
    / BackendHealth(healthy/detail/checked_at)/ InferResult(text+审计元信息)
  · LocalBackend / CloudBackend 占位实现迁移至此并继承新 ABC,补齐生命周期
  · default_registry + build_backend:配置驱动切换后端(未知 name 报错并提示已知项)
- gateway.py:删除内联定义,改为从 backends.py 再导出,LLMGateway.ask() 调用路径不变
- __init__.py:再导出新符号(BackendCapabilities/BackendHealth/InferResult/
  build_backend/default_registry),InferenceBackend 现为 ABC

设计原则:业务代码仅依赖接口,不感知硬件;切换后端 = 换实现 + 改配置,业务零改动。

测试:core/llm-gateway 全量 97 个用例通过(新增 27 + 既有 70,零回归)。
运行:python -m unittest discover -s tests -v(在 core/llm-gateway 目录下)
2026-08-04 21:04:00 +08:00
9 changed files with 635 additions and 710 deletions
+15 -2
View File
@@ -16,6 +16,9 @@
高利害信度阈值 → 人工确认。 高利害信度阈值 → 人工确认。
- gateway 混合网关主编排(EPIC #6 主体):路由 → 生成 → 溯源校验 → - gateway 混合网关主编排(EPIC #6 主体):路由 → 生成 → 溯源校验 →
DLP 出站防线,端到端闭环。 DLP 出站防线,端到端闭环。
- backends 推理后端抽象(Issue #57,PRD 5.6):``InferenceBackend`` 抽象接口
(``load_model / infer / health_check / unload``),5090 实现(Triton/ONNX)
与昇腾实现(ACL/CANN)均实现该接口;业务代码仅依赖接口,不感知硬件。
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。 测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
""" """
@@ -45,10 +48,17 @@ from .hallucination import (
GuardVerdict, GuardVerdict,
HallucinationGuard, HallucinationGuard,
) )
from .backends import (
BackendCapabilities,
BackendHealth,
InferResult,
InferenceBackend,
build_backend,
default_registry,
)
from .gateway import ( from .gateway import (
CloudBackend, CloudBackend,
GatewayResult, GatewayResult,
InferenceBackend,
LLMGateway, LLMGateway,
LocalBackend, LocalBackend,
) )
@@ -62,7 +72,10 @@ __all__ = [
"PromptVersion", "PromptChange", "PromptRegistry", "validate_semver", "PromptVersion", "PromptChange", "PromptRegistry", "validate_semver",
# hallucination # hallucination
"GuardVerdict", "HallucinationGuard", "GuardVerdict", "HallucinationGuard",
# backends (Issue #57)
"BackendCapabilities", "BackendHealth", "InferResult", "InferenceBackend",
"build_backend", "default_registry",
# gateway # gateway
"InferenceBackend", "LocalBackend", "CloudBackend", "LocalBackend", "CloudBackend",
"GatewayResult", "LLMGateway", "GatewayResult", "LLMGateway",
] ]
+301
View File
@@ -0,0 +1,301 @@
# -*- coding: utf-8 -*-
"""iAOP-Core · LLM 网关 —— 推理后端抽象接口(Issue #57,PRD 5.6)。
PRD 5.6「⑥ 部署底座」明确要求:
定义统一 ``InferenceBackend`` 接口(``loadModel / infer / health / unload``),
5090 实现(Triton/ONNX)与昇腾实现(ACL/CANN)均实现该接口;
**业务代码仅依赖接口,不感知硬件**;切换后端 = 改适配层配置,不动业务代码。
本模块把原先内联在 ``gateway.py`` 里的薄弱 ``InferenceBackend`` 提炼为正式的
抽象基类(ABC),并补齐 PRD 要求的生命周期方法与能力声明,使后续子任务:
- #44 本地 70B 模型接入与推理封装(vLLM/TGI)
- #45 云端 API(Qwen/DeepSeek)接入与安全网关
- #58 GPU 后端实现(NVIDIA,Triton/ONNX)
- #59 昇腾 NPU 后端适配(CANN/ACL)
都能在**同一契约**下落地,业务编排(``LLMGateway``)零改动。
设计要点
--------
1. **接口最小且完备**:仅约束 PRD 列出的四个生命周期动作 ``load_model / infer /
health_check / unload``,外加能力声明 ``BackendCapabilities``(流式 / 最大并发 /
是否出厂内闭环),供路由与调度决策。
2. **向后兼容**:保留 ``generate(prompt, context)`` 便捷方法(默认转发到
``infer``),既有 ``LLMGateway.ask()`` 调用路径不变;老测试不受影响。
3. **可注入 / 可 mock**:所有方法纯逻辑、无外部 IO 依赖;真实硬件/网络交互由
各子类在 ``infer`` 内部完成(子类负责导入厂商 SDK 并做 ``ImportError`` 容错)。
4. **健康探针**:``health_check`` 返回结构化 ``BackendHealth``,供可用性监控探针
(Issue #61)与灰度发布(PRD 5.6 配置点)判定后端是否就绪。
测试:``python -m unittest discover -s tests -v``(在 core/llm-gateway 目录下执行)。
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Dict, Iterator, List, Optional, Sequence
# ---------------------------------------------------------------------------
# 值对象:能力声明 / 健康状态 / 推理结果
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class BackendCapabilities:
"""后端能力声明,供路由 / 调度 / 灰度决策。
Attributes:
streaming: 是否支持流式输出(逐 token 返回)。
max_concurrency: 最大并发推理数(None 表示不限 / 由外部限流)。
on_premises: 是否数据出厂内闭环(本地后端 True,云端 False)。
modalities: 支持的输出形态,如 ``("text",)``。
"""
streaming: bool = False
max_concurrency: Optional[int] = None
on_premises: bool = False
modalities: Sequence[str] = ("text",)
def supports(self, modality: str) -> bool:
"""是否支持某种输出形态(text / image / ...)。"""
return modality in self.modalities
def to_dict(self) -> Dict[str, object]:
return {
"streaming": self.streaming,
"max_concurrency": self.max_concurrency,
"on_premises": self.on_premises,
"modalities": list(self.modalities),
}
@dataclass(frozen=True)
class BackendHealth:
"""后端健康探针结果(Issue #61 可用性监控探针消费)。"""
healthy: bool
detail: str = ""
checked_at: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat())
def to_dict(self) -> Dict[str, object]:
return {
"healthy": self.healthy,
"detail": self.detail,
"checked_at": self.checked_at,
}
@dataclass(frozen=True)
class InferResult:
"""一次 ``infer`` 的结构化结果(含审计所需元信息)。
保留 ``text`` 主输出以兼容旧 ``generate`` 返回 ``str`` 的调用方;
``prompt_tokens`` / ``completion_tokens`` 供计费与配额(PRD 5.6 配置点)。
"""
text: str
backend_name: str
model_id: str = ""
prompt_tokens: Optional[int] = None
completion_tokens: Optional[int] = None
latency_ms: Optional[float] = None
def to_dict(self) -> Dict[str, object]:
return {
"text": self.text,
"backend_name": self.backend_name,
"model_id": self.model_id,
"prompt_tokens": self.prompt_tokens,
"completion_tokens": self.completion_tokens,
"latency_ms": self.latency_ms,
}
# ---------------------------------------------------------------------------
# 抽象接口(PRD 5.6:loadModel / infer / health / unload)
# ---------------------------------------------------------------------------
class InferenceBackend(ABC):
"""推理后端抽象接口(对齐 PRD 5.6 ``InferenceBackend`` 契约)。
业务编排(``LLMGateway``)只依赖本接口,**不感知**具体硬件 / 厂商;
切换后端 = 换实现类 + 改配置,业务代码不动。子类必须实现四个生命周期方法:
- :meth:`load_model`:加载 / 绑定模型(可幂等,重复加载返回已加载实例)。
- :meth:`infer`:给定 prompt 与 RAG 上下文生成回答(核心推理动作)。
- :meth:`health_check`:探针,返回 :class:`BackendHealth`。
- :meth:`unload`:释放模型资源(可幂等)。
便捷方法 :meth:`generate` 默认转发到 :meth:`infer` 并只取 ``text``,
保留与旧 ``LLMGateway.ask()`` 的二进制兼容。
"""
#: 后端短名(local-70b / cloud-api / gpu-triton / npu-cann ...),子类覆盖。
name: str = "base"
@property
def capabilities(self) -> BackendCapabilities:
"""后端能力声明,子类按需覆盖。默认:非流式、出厂外、仅文本。"""
return BackendCapabilities()
# -- 生命周期(子类必须实现)------------------------------------------
@abstractmethod
def load_model(self, model_id: str) -> None:
"""加载 / 绑定指定模型。幂等:重复加载同一 model_id 不报错。"""
@abstractmethod
def infer(self, prompt: str,
context: Optional[Sequence[str]] = None) -> InferResult:
"""根据 prompt 与 RAG 上下文生成回答(核心推理动作)。"""
@abstractmethod
def health_check(self) -> BackendHealth:
"""健康探针,返回结构化健康状态。"""
@abstractmethod
def unload(self) -> None:
"""释放模型资源。幂等:未加载时调用不报错。"""
# -- 向后兼容便捷方法 --------------------------------------------------
def generate(self, prompt: str, context: Sequence[str]) -> str:
"""旧调用入口:等价于 ``infer(prompt, context).text``。
保留是为了不破坏 ``LLMGateway.ask()`` 既有的 ``backend.generate(...)``
调用路径;新代码应直接使用 :meth:`infer` 拿到完整 :class:`InferResult`。
"""
return self.infer(prompt, context).text
def __repr__(self) -> str: # pragma: no cover - 调试辅助
return f"<{type(self).__name__} name={self.name!r}>"
# ---------------------------------------------------------------------------
# 占位实现(子任务 #44 / #45 / #58 / #59 将各自替换为真实后端)
# ---------------------------------------------------------------------------
class _PlaceholderBackend(InferenceBackend):
"""占位后端公共骨架:固定回显答案 + 引用溯源回显,供端到端测试与演示。
真实后端(#44 本地 70B / #45 云端 API / #58 GPU / #59 昇腾)继承本类后,
只需覆盖 :meth:`infer` 的生成逻辑与 :meth:`health_check` 的探针实现即可;
生命周期与能力声明已由本类 / 子类提供。
"""
placeholder_prefix = "[占位]"
def __init__(self, model_id: str, echo_context: bool = True) -> None:
self._model_id = model_id
self._loaded = False
self._loaded_model_id: Optional[str] = None
self.echo_context = echo_context
# 生命周期
def load_model(self, model_id: str) -> None:
# 幂等:重复加载同一 model_id 视作成功;换模型也允许(演示用)。
self._loaded = True
self._loaded_model_id = model_id or self._model_id
def infer(self, prompt: str,
context: Optional[Sequence[str]] = None) -> InferResult:
if not self._loaded:
# 演示态允许惰性自加载,真实后端可改为 raise RuntimeError("未加载模型")
self.load_model(self._model_id)
ctx = list(context or [])
head = f"{self.placeholder_prefix} {prompt[:40]}"
refs = ""
if self.echo_context:
for src in ctx[:3]:
refs += f"\n[来源: {src}]"
return InferResult(
text=head + refs,
backend_name=self.name,
model_id=self._loaded_model_id or self._model_id,
)
def health_check(self) -> BackendHealth:
return BackendHealth(
healthy=self._loaded,
detail="loaded" if self._loaded else "not_loaded",
)
def unload(self) -> None:
# 幂等:未加载也安全
self._loaded = False
self._loaded_model_id = None
class LocalBackend(_PlaceholderBackend):
"""本地 70B 后端占位实现:数据不出厂(敏感 / 核心走此通道)。
子任务 #44 / #58 将替换 ``infer`` 为真实本地模型推理封装(vLLM/TGI/Triton)。
"""
name = "local-70b"
placeholder_prefix = "[本地70B占位]"
def __init__(self, echo_context: bool = True,
model_id: str = "local-70b-base") -> None:
super().__init__(model_id=model_id, echo_context=echo_context)
@property
def capabilities(self) -> BackendCapabilities:
# 本地后端:出厂内闭环、可流式、单卡典型并发 8(演示默认值)
return BackendCapabilities(
streaming=True, max_concurrency=8, on_premises=True,
modalities=("text",))
class CloudBackend(_PlaceholderBackend):
"""云端 API 后端占位实现:仅接收 DLP 放行的脱敏 / 通用内容。
子任务 #45 将替换为 Qwen / DeepSeek API 接入 + 安全网关。
"""
name = "cloud-api"
placeholder_prefix = "[云端API占位]"
def __init__(self, echo_context: bool = True,
model_id: str = "cloud-qwen-plus") -> None:
super().__init__(model_id=model_id, echo_context=echo_context)
@property
def capabilities(self) -> BackendCapabilities:
# 云端后端:数据出厂、支持流式、并发受厂商配额限制(演示默认 4)
return BackendCapabilities(
streaming=True, max_concurrency=4, on_premises=False,
modalities=("text",))
# ---------------------------------------------------------------------------
# 后端注册表(配置驱动切换,对齐 PRD「切换后端 = 改适配层配置」)
# ---------------------------------------------------------------------------
def default_registry() -> Dict[str, type]:
"""默认后端注册表:name → 实现类。新增后端在此登记一行即可被配置选用。"""
return {
"local-70b": LocalBackend,
"cloud-api": CloudBackend,
}
def build_backend(name: str, **kwargs) -> InferenceBackend:
"""按 name 从默认注册表构造后端实例(配置驱动切换的入口)。
未知 name 抛 ``ValueError``,列出已知项便于排错。
"""
registry = default_registry()
cls = registry.get(name)
if cls is None:
known = ", ".join(sorted(registry))
raise ValueError(f"未知推理后端 {name!r},已知: {known}")
return cls(**kwargs)
+18 -61
View File
@@ -12,12 +12,15 @@
- `router`(SensitivityRouter):敏感度分级路由(local / cloud / block); - `router`(SensitivityRouter):敏感度分级路由(local / cloud / block);
- `prompts`(PromptRegistry):提示词模板版本绑定(可复现); - `prompts`(PromptRegistry):提示词模板版本绑定(可复现);
- `guard`(HallucinationGuard):引用溯源 + 信度阈值 → 人工确认; - `guard`(HallucinationGuard):引用溯源 + 信度阈值 → 人工确认;
- `backends`(LocalBackend / CloudBackend):推理后端抽象(可注入)。 - `backends`(InferenceBackend / LocalBackend / CloudBackend):推理后端抽象
(可注入)。接口定义已提炼到 `backends.py`(Issue #57,对齐 PRD 5.6)。
设计说明: 设计说明:
- 本版提供**编排闭环 + 后端抽象接口**,本地 70B / 云端 API 的具体接入 - 本版提供**编排闭环 + 后端抽象接口**,本地 70B / 云端 API 的具体接入
由子任务 #44 / #45 实现;`LocalBackend` / `CloudBackend` 默认内置一个 由子任务 #44 / #45 实现;`LocalBackend` / `CloudBackend` 默认内置一个
最小实现(返回固定占位答案 + 回显引用),供端到端测试与演示。 最小实现(返回固定占位答案 + 回显引用),供端到端测试与演示。
- 推理后端契约(`loadModel / infer / health_check / unload`)见 `backends.py`,
本模块仅消费其 `generate` / `name`,业务代码不感知具体硬件。
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。 测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
""" """
@@ -26,71 +29,25 @@ from __future__ import annotations
import uuid import uuid
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import Callable, Dict, List, Optional, Sequence from typing import Dict, List, Optional, Sequence
from .dlp import DlpEngine from .dlp import DlpEngine
from .router import RouteDecision, RouteTarget, SensitivityRouter from .router import RouteDecision, RouteTarget, SensitivityRouter
from .prompts import PromptRegistry from .prompts import PromptRegistry
from .hallucination import GuardVerdict, HallucinationGuard from .hallucination import GuardVerdict, HallucinationGuard
# 推理后端抽象(Issue #57):契约定义在 backends.py,这里仅做再导出,
# --------------------------------------------------------------------------- # 保持 ``from .gateway import InferenceBackend/LocalBackend/CloudBackend`` 的
# 推理后端抽象(Issue #44 / #45 将实现具体后端,业务代码只依赖本接口) # 向后兼容(既有 import 路径与 ``LLMGateway`` 依赖均不变)。
# --------------------------------------------------------------------------- from .backends import (
BackendCapabilities,
BackendHealth,
class InferenceBackend: CloudBackend,
"""推理后端接口抽象(对齐 PRD 5.6 InferenceBackend 思想)。 InferResult,
InferenceBackend,
业务代码只依赖本接口,不感知具体硬件/厂商;切换后端 = 换实现。 LocalBackend,
子任务 #44(本地 70B)、#45(云端 Qwen/DeepSeek)将各自实现本接口。 build_backend,
""" default_registry,
)
name: str = "base"
def generate(self, prompt: str, context: Sequence[str]) -> str:
"""根据 prompt 与 RAG 上下文生成回答。子类实现。"""
raise NotImplementedError
class LocalBackend(InferenceBackend):
"""本地 70B 后端占位实现:数据不出厂(敏感/核心走此通道)。
子任务 #44 将替换为真实本地模型推理封装(vLLM/TGI 等)。
"""
name = "local-70b"
def __init__(self, echo_context: bool = True) -> None:
self.echo_context = echo_context
def generate(self, prompt: str, context: Sequence[str]) -> str:
head = f"[本地70B占位] {prompt[:40]}"
refs = ""
if self.echo_context:
for i, src in enumerate(context[:3], 1):
refs += f"\n[来源: {src}]"
return head + refs
class CloudBackend(InferenceBackend):
"""云端 API 后端占位实现:仅接收 DLP 放行的脱敏/通用内容。
子任务 #45 将替换为 Qwen/DeepSeek API 接入 + 安全网关。
"""
name = "cloud-api"
def __init__(self, echo_context: bool = True) -> None:
self.echo_context = echo_context
def generate(self, prompt: str, context: Sequence[str]) -> str:
head = f"[云端API占位] {prompt[:40]}"
refs = ""
if self.echo_context:
for i, src in enumerate(context[:3], 1):
refs += f"\n[来源: {src}]"
return head + refs
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 网关输出 # 网关输出
+301
View File
@@ -0,0 +1,301 @@
# -*- coding: utf-8 -*-
"""推理后端抽象接口(backends,Issue #57,PRD 5.6)单元测试。
覆盖:
- 抽象基类不可直接实例化(必须由子类实现四个生命周期方法);
- 值对象 BackendCapabilities / BackendHealth / InferResult 的字段与序列化;
- LocalBackend / CloudBackend 占位实现的生命周期(load/infer/health/unload)与幂等;
- 向后兼容:``generate`` 转发到 ``infer`` 并返回 ``text``;
- 能力声明差异(本地出厂内闭环 / 云端出厂外);
- 注册表与 ``build_backend`` 的配置驱动构造 + 未知后端报错。
"""
import os
import sys
import unittest
from abc import ABC
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _bootstrap # noqa: F401
from llm_gateway.backends import ( # noqa: E402
BackendCapabilities,
BackendHealth,
CloudBackend,
InferResult,
InferenceBackend,
LocalBackend,
_PlaceholderBackend,
build_backend,
default_registry,
)
# ---------------------------------------------------------------------------
# 抽象基类契约
# ---------------------------------------------------------------------------
class AbstractionContractTest(unittest.TestCase):
"""PRD 5.6:InferenceBackend 是抽象接口,业务代码只依赖它。"""
def test_cannot_instantiate_abstract_base(self):
# 缺少四个抽象方法 → 不能实例化
with self.assertRaises(TypeError):
InferenceBackend() # noqa: E721
def test_is_abc_subclass(self):
self.assertTrue(issubclass(InferenceBackend, ABC))
def test_required_abstract_methods(self):
# PRD 5.6 明列的生命周期动作
abstract = InferenceBackend.__abstractmethods__
for name in ("load_model", "infer", "health_check", "unload"):
self.assertIn(name, abstract)
def test_concrete_backends_are_inference_backends(self):
for cls in (LocalBackend, CloudBackend):
self.assertTrue(issubclass(cls, InferenceBackend),
f"{cls.__name__} 必须实现 InferenceBackend")
# ---------------------------------------------------------------------------
# 值对象
# ---------------------------------------------------------------------------
class BackendCapabilitiesTest(unittest.TestCase):
def test_defaults(self):
cap = BackendCapabilities()
self.assertFalse(cap.streaming)
self.assertIsNone(cap.max_concurrency)
self.assertFalse(cap.on_premises)
self.assertEqual(cap.modalities, ("text",))
def test_supports_modality(self):
cap = BackendCapabilities(modalities=("text", "image"))
self.assertTrue(cap.supports("text"))
self.assertTrue(cap.supports("image"))
self.assertFalse(cap.supports("audio"))
def test_to_dict_roundtrip(self):
cap = BackendCapabilities(streaming=True, max_concurrency=4,
on_premises=False, modalities=("text",))
d = cap.to_dict()
self.assertEqual(d["streaming"], True)
self.assertEqual(d["max_concurrency"], 4)
self.assertEqual(d["modalities"], ["text"])
class BackendHealthTest(unittest.TestCase):
def test_fields(self):
h = BackendHealth(healthy=True, detail="ok")
self.assertTrue(h.healthy)
self.assertEqual(h.detail, "ok")
self.assertTrue(h.checked_at) # 自动生成时间戳
def test_to_dict(self):
d = BackendHealth(healthy=False, detail="down").to_dict()
self.assertEqual(d["healthy"], False)
self.assertIn("checked_at", d)
class InferResultTest(unittest.TestCase):
def test_required_fields(self):
r = InferResult(text="hello", backend_name="local-70b")
self.assertEqual(r.text, "hello")
self.assertEqual(r.backend_name, "local-70b")
self.assertIsNone(r.prompt_tokens)
def test_to_dict(self):
r = InferResult(text="a", backend_name="b", model_id="m",
prompt_tokens=3, completion_tokens=5)
d = r.to_dict()
self.assertEqual(d["text"], "a")
self.assertEqual(d["prompt_tokens"], 3)
self.assertEqual(d["completion_tokens"], 5)
# ---------------------------------------------------------------------------
# 占位实现生命周期
# ---------------------------------------------------------------------------
class PlaceholderLifecycleTest(unittest.TestCase):
def setUp(self):
self.b = LocalBackend()
def test_health_reflects_load_state(self):
# 未加载 → 不健康
self.assertFalse(self.b.health_check().healthy)
self.b.load_model("local-70b-base")
self.assertTrue(self.b.health_check().healthy)
def test_load_is_idempotent(self):
self.b.load_model("local-70b-base")
# 重复加载同一 model_id 不报错
self.b.load_model("local-70b-base")
self.assertTrue(self.b.health_check().healthy)
def test_infer_lazy_loads_when_not_loaded(self):
# 演示态:未显式 load_model 也能 infer(惰性自加载)
r = self.b.infer("炉温是多少", context=["SOP-炉温"])
self.assertIsInstance(r, InferResult)
self.assertEqual(r.backend_name, "local-70b")
self.assertIn("炉温是多少", r.text)
self.assertIn("[来源: SOP-炉温]", r.text)
def test_infer_after_explicit_load(self):
self.b.load_model("local-70b-base")
r = self.b.infer("hello")
self.assertEqual(r.model_id, "local-70b-base")
self.assertIn("hello", r.text)
def test_unload_is_idempotent(self):
self.b.load_model("local-70b-base")
self.b.unload()
self.assertFalse(self.b.health_check().healthy)
# 未加载再 unload 也不报错
self.b.unload()
def test_echo_context_disabled(self):
b = LocalBackend(echo_context=False)
b.load_model("m")
r = b.infer("q", context=["src1", "src2"])
self.assertNotIn("[来源:", r.text)
# ---------------------------------------------------------------------------
# 向后兼容:generate 转发到 infer
# ---------------------------------------------------------------------------
class BackwardCompatGenerateTest(unittest.TestCase):
def test_generate_returns_text_of_infer(self):
b = CloudBackend()
b.load_model("cloud-qwen-plus")
txt = b.generate("海绵钛是什么", context=["科普手册"])
# 与 infer().text 一致
self.assertEqual(txt, b.infer("海绵钛是什么", context=["科普手册"]).text)
self.assertIn("云端API占位", txt)
self.assertIn("[来源: 科普手册]", txt)
def test_gateway_still_works_with_new_backends(self):
# 集成校验:LLMGateway.ask() 经 generate 路径仍正常(不导入失败)。
# 复用 test_gateway.py 的模板配置加载 prompts,避免默认空注册表 KeyError。
from llm_gateway.dlp import DlpEngine
from llm_gateway.gateway import LLMGateway
from llm_gateway.prompts import PromptRegistry
from llm_gateway.router import SensitivityRouter
cfg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
prompts = PromptRegistry.from_template_config(
os.path.join(cfg_dir, "config", "prompts.template.yaml"))
router = SensitivityRouter.from_template_config(
os.path.join(cfg_dir, "config", "router.template.yaml"))
gw = LLMGateway(
dlp=DlpEngine(), router=router, prompts=prompts,
local=LocalBackend(), cloud=CloudBackend())
result = gw.ask("海绵钛是什么", rag_context=["科普手册"])
self.assertTrue(result.answer)
# 后端占位回显特征仍在(证明走的是新 backends 的 generate 路径)
self.assertIn("云端API占位", result.answer)
# ---------------------------------------------------------------------------
# 能力声明差异(本地 vs 云端)
# ---------------------------------------------------------------------------
class CapabilitiesDifferenceTest(unittest.TestCase):
def test_local_is_on_premises(self):
cap = LocalBackend().capabilities
self.assertTrue(cap.on_premises)
self.assertTrue(cap.streaming)
self.assertGreater(cap.max_concurrency, 0)
def test_cloud_is_off_premises(self):
cap = CloudBackend().capabilities
self.assertFalse(cap.on_premises)
self.assertTrue(cap.streaming)
def test_local_and_cloud_differ_on_premises(self):
# 关键差异:本地出厂内闭环,云端数据出厂
self.assertNotEqual(
LocalBackend().capabilities.on_premises,
CloudBackend().capabilities.on_premises,
)
# ---------------------------------------------------------------------------
# 注册表与配置驱动构造
# ---------------------------------------------------------------------------
class RegistryTest(unittest.TestCase):
def test_default_registry_has_known_backends(self):
reg = default_registry()
self.assertIn("local-70b", reg)
self.assertIn("cloud-api", reg)
self.assertIs(reg["local-70b"], LocalBackend)
self.assertIs(reg["cloud-api"], CloudBackend)
def test_build_backend_by_name(self):
b = build_backend("local-70b")
self.assertIsInstance(b, LocalBackend)
self.assertIsInstance(b, InferenceBackend)
self.assertEqual(b.name, "local-70b")
def test_build_unknown_backend_raises_with_hint(self):
with self.assertRaises(ValueError) as ctx:
build_backend("npu-cann") # 尚未实现(#59 才接入)
self.assertIn("npu-cann", str(ctx.exception))
self.assertIn("local-70b", str(ctx.exception)) # 提示已知项
def test_build_passes_kwargs(self):
b = build_backend("cloud-api", echo_context=False)
self.assertIsInstance(b, CloudBackend)
self.assertFalse(b.echo_context)
# ---------------------------------------------------------------------------
# 自定义后端通过实现接口接入(证明「业务代码不感知硬件」)
# ---------------------------------------------------------------------------
class CustomBackendImplementationTest(unittest.TestCase):
"""模拟 #59 昇腾后端:只需实现四个方法即可被当作 InferenceBackend 使用。"""
def test_custom_backend_satisfies_interface(self):
class NpuCannBackend(InferenceBackend):
name = "npu-cann"
def __init__(self):
self._loaded = False
def load_model(self, model_id):
self._loaded = True
def infer(self, prompt, context=None):
if not self._loaded:
self.load_model("ascend-cann")
return InferResult(text=f"[NPU] {prompt}", backend_name=self.name)
def health_check(self):
return BackendHealth(healthy=self._loaded)
def unload(self):
self._loaded = False
b = NpuCannBackend()
self.assertIsInstance(b, InferenceBackend)
self.assertFalse(b.health_check().healthy)
b.load_model("ascend-cann")
self.assertTrue(b.health_check().healthy)
self.assertEqual(b.infer("q").text, "[NPU] q")
# generate 兼容路径
self.assertEqual(b.generate("q", context=[]), "[NPU] q")
b.unload()
self.assertFalse(b.health_check().healthy)
if __name__ == "__main__":
unittest.main()
-37
View File
@@ -1,37 +0,0 @@
# -*- coding: utf-8 -*-
"""iAOP-Core · AI 模型框架(AI Model Framework)—— 配置驱动的可模板化模型内核。
对应 PRD 5.3「③ AI 模型框架」与 EPIC #5(平台化改造 RISK 项):
固定主干网络 + 可配置超参;Model Recipe 插件注册;FeatureSpec 声明式特征;
所有可变量外置为 **JSON 超参包**,同一框架切换模板仅改此包(零改码)。
模块组成(按 EPIC #5 拆分的 ≤0.5d 子任务逐步落地):
- hyperparam 超参包 JSON Schema 校验器(Issue #39):加载 + 校验超参包,
返回逐条校验报告,供配置台与训练/推理流水线复用。
- (后续)recipe Model Recipe 插件接口与样例协议(Issue #34)
- (后续)feature FeatureSpec 声明式特征定义引擎(Issue #35)
- (后续)registry 模型模板注册 / 加载 / 版本机制(Issue #41)
超参包 JSON 结构见 PRD 5.3「超参包 JSON 完整示例」与 ``config/`` 下样例。
测试:`python -m unittest discover -s tests -v`(在 core/model-framework 目录下执行)。
"""
from __future__ import annotations
from .hyperparam import (
HyperparamPack,
ValidationIssue,
ValidationReport,
load_pack,
validate_pack,
validate_pack_file,
)
__all__ = [
"HyperparamPack",
"ValidationIssue",
"ValidationReport",
"load_pack",
"validate_pack",
"validate_pack_file",
]
@@ -1,16 +0,0 @@
{
"model_id": "quality_predict_ti",
"template": "iAOP-Template-Ti",
"algorithm": "xgboost",
"features": [
{"name": "EMA_CLF_TEMP_5m", "spec": "EMA(CLF-01.TEMP, 5m)"},
{"name": "RollingStd_CL2_10", "spec": "RollingStd(CLF-01.CL2, 10)"},
{"name": "ROC_FURNACE_PRESS", "spec": "RateOfChange(CLF-01.PRES)"}
],
"target": "Ti_purity",
"objective": "reg:squarederror",
"hyperparams": {"max_depth": 6, "eta": 0.1, "n_estimators": 300},
"train_window": "180d",
"alarm_threshold": {"type": "zscore", "k": 3.0},
"drift_check": {"method": "psi", "limit": 0.2}
}
-339
View File
@@ -1,339 +0,0 @@
# -*- coding: utf-8 -*-
"""超参包(Hyperparam Pack)JSON Schema 校验器。
对应 issue #39(父 EPIC #5「③ AI 模型框架 配置化重构」)与 PRD 5.3
「超参包驱动」:所有可变量(输入特征清单、算法选型、超参、训练窗口、告警阈值、
目标函数)外置为 JSON 超参包,同一框架切换模板仅改此包。
本模块对超参包做 **结构化校验**(不依赖 jsonschema 第三方库,零外部依赖,
便于边缘 / 离线环境运行),返回逐条问题的校验报告,便于配置台一次性展示全部问题、
也便于训练/推理流水线在加载包时 fail-fast。
校验维度(对齐 PRD 5.3 超参包示例与 5.3「配置点」):
1. 顶层结构:必填字段 model_id / template / algorithm / features / target;
2. model_id / template:非空字符串;
3. algorithm:必须在合法算法集合内(xgboost / lightgbm / dnn / lstm / gnn /
isolation_forest / zscore / linear / ridge);未知算法报错并提示已知项
(对齐 PRD「新增结构走插件注册」——校验期即暴露非法选型);
4. features:非空列表;每项含 name(非空、包内唯一)与 spec(非空字符串,
FeatureSpec 文本,由 issue #35 引擎解释,此处只做存在性校验);
5. target:非空字符串;
6. objective(可选):若填写必须为已知目标函数(reg:squarederror /
binary:logistic / multi:softmax / regression / classification 等);
7. hyperparams(可选):若提供必须为对象(dict),且不含空键;
8. train_window(可选):若填写必须形如 ``<正整数><单位>``(单位 d/w/h/m),
如 ``180d`` / ``4w``;
9. alarm_threshold(可选):若提供必须为对象,且含 ``type``
(zscore / quantile / absolute)与对应阈值键;
10. drift_check(可选):若提供必须为对象,含 ``method``(psi / ks / chi2)
与 ``limit``(0~1 之间)。
注:返回报告而非抛异常,便于配置台聚合展示;``load_pack`` 在校验失败时抛
``ValueError`` 供流水线 fail-fast。
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# 合法取值集合(对齐 PRD 5.3「四类模型模板」+ 默认主干网络 + Recipe 插件扩展点)
# ---------------------------------------------------------------------------
#: 已注册算法(默认主干 + Recipe 可选结构)。新增结构应走插件注册(issue #34/#41),
#: 此处枚举的是内核自带项;校验期遇到未知 algorithm 会报错并列出已知项,避免
#: 静默落到错误分支。
KNOWN_ALGORITHMS: Tuple[str, ...] = (
# 监督回归 / 分类(质量预测)
"xgboost",
"lightgbm",
"linear",
"ridge",
# 神经网络主干(默认 DNN;Recipe 可选 LSTM/GNN)
"dnn",
"lstm",
"gnn",
# 无监督异常 / 杂质预警
"isolation_forest",
"zscore",
)
#: 已知目标函数(xgboost 风格 + 通用风格)。
KNOWN_OBJECTIVES: Tuple[str, ...] = (
"reg:squarederror",
"reg:squaredlogerror",
"binary:logistic",
"multi:softmax",
"multi:softprob",
"regression",
"classification",
)
#: 训练窗口合法时间单位。
_TRAIN_WINDOW_RE = re.compile(r"^\d+(\.\d+)?[dwhm]$")
#: FeatureSpec 仅校验非空文本(具体语法由 issue #35 引擎解释)。
_FEATURE_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
@dataclass
class ValidationIssue:
"""单条校验问题。"""
code: str # 错误码:missing_field / bad_type / unknown_algorithm / ...
path: str # JSON 路径,如 ``features[1].name`` / ``algorithm``
message: str # 人类可读描述
@dataclass
class ValidationReport:
"""校验报告。"""
issues: List[ValidationIssue] = field(default_factory=list)
@property
def ok(self) -> bool:
return not self.issues
def summary(self) -> str:
if self.ok:
return "超参包校验通过"
by_code: Dict[str, int] = {}
for it in self.issues:
by_code[it.code] = by_code.get(it.code, 0) + 1
parts = [f"{code}×{n}" for code, n in sorted(by_code.items())]
return f"超参包校验未通过({len(self.issues)} 个问题:" + ",".join(parts) + ")"
@dataclass
class HyperparamPack:
"""解析后的超参包(校验通过的视图)。
字段对齐 PRD 5.3 超参包示例;可选字段缺失时为 ``None``。
"""
model_id: str
template: str
algorithm: str
features: List[Dict[str, str]]
target: str
objective: Optional[str] = None
hyperparams: Optional[Dict[str, Any]] = None
train_window: Optional[str] = None
alarm_threshold: Optional[Dict[str, Any]] = None
drift_check: Optional[Dict[str, Any]] = None
raw: Dict[str, Any] = field(default_factory=dict)
@property
def feature_names(self) -> List[str]:
return [f["name"] for f in self.features]
# ---------------------------------------------------------------------------
# 校验主逻辑
# ---------------------------------------------------------------------------
def validate_pack(pack: Dict[str, Any]) -> ValidationReport:
"""校验一个已解析为 dict 的超参包,返回报告(不抛异常)。"""
report = ValidationReport()
def add(code: str, path: str, message: str) -> None:
report.issues.append(ValidationIssue(code, path, message))
# 0. 顶层必须是对象
if not isinstance(pack, dict):
add("bad_type", "$", f"超参包根节点必须为 JSON 对象,实际为 {type(pack).__name__}")
return report
# 1. 必填字段
required: Tuple[str, ...] = ("model_id", "template", "algorithm", "features", "target")
for key in required:
if key not in pack:
add("missing_field", key, f"缺少必填字段:{key}")
# 2. 标量字段类型与取值
model_id = pack.get("model_id")
if "model_id" in pack:
if not isinstance(model_id, str) or not model_id.strip():
add("bad_type", "model_id", "model_id 必须为非空字符串")
elif not _FEATURE_NAME_RE.match(model_id):
add("bad_format", "model_id", "model_id 含非法字符(仅字母/数字/下划线,首字符非数字)")
template = pack.get("template")
if "template" in pack and (not isinstance(template, str) or not template.strip()):
add("bad_type", "template", "template 必须为非空字符串")
algorithm = pack.get("algorithm")
if "algorithm" in pack:
if not isinstance(algorithm, str) or not algorithm.strip():
add("bad_type", "algorithm", "algorithm 必须为非空字符串")
elif algorithm not in KNOWN_ALGORITHMS:
known = "、".join(KNOWN_ALGORITHMS)
add(
"unknown_algorithm",
"algorithm",
f"未知算法 '{algorithm}';已知项:{known}(新增结构请走 Model Recipe 插件注册)",
)
target = pack.get("target")
if "target" in pack and (not isinstance(target, str) or not target.strip()):
add("bad_type", "target", "target 必须为非空字符串")
# 3. objective(可选)
objective = pack.get("objective")
if objective is not None:
if not isinstance(objective, str) or not objective.strip():
add("bad_type", "objective", "objective 若填写必须为非空字符串")
elif objective not in KNOWN_OBJECTIVES:
known = "、".join(KNOWN_OBJECTIVES)
add("unknown_objective", "objective", f"未知目标函数 '{objective}';已知项:{known}")
# 4. features(必填,非空列表)
features = pack.get("features")
if features is None:
# missing_field 已在步骤 1 记录
pass
elif not isinstance(features, list):
add("bad_type", "features", f"features 必须为数组,实际为 {type(features).__name__}")
elif len(features) == 0:
add("empty_features", "features", "features 不能为空(模型至少需要一个输入特征)")
else:
seen_names: Dict[str, int] = {}
for i, feat in enumerate(features):
fpath = f"features[{i}]"
if not isinstance(feat, dict):
add("bad_type", fpath, f"特征项必须为对象,实际为 {type(feat).__name__}")
continue
name = feat.get("name")
spec = feat.get("spec")
if not isinstance(name, str) or not name.strip():
add("missing_field", f"{fpath}.name", "特征缺少 name 或为空")
else:
if not _FEATURE_NAME_RE.match(name):
add("bad_format", f"{fpath}.name", f"特征名 '{name}' 含非法字符")
if name in seen_names:
add(
"dup_feature",
f"{fpath}.name",
f"特征名 '{name}' 重复(首次出现在 features[{seen_names[name]}])",
)
else:
seen_names[name] = i
if not isinstance(spec, str) or not spec.strip():
add("missing_field", f"{fpath}.spec", f"特征 '{name}' 缺少 spec(FeatureSpec 声明)或为空")
# 5. hyperparams(可选,对象)
hyperparams = pack.get("hyperparams")
if hyperparams is not None:
if not isinstance(hyperparams, dict):
add("bad_type", "hyperparams", f"hyperparams 必须为对象,实际为 {type(hyperparams).__name__}")
else:
for k, v in hyperparams.items():
if not isinstance(k, str) or not k.strip():
add("bad_format", "hyperparams", "hyperparams 含空键")
# 6. train_window(可选,<数><单位>)
train_window = pack.get("train_window")
if train_window is not None:
if not isinstance(train_window, str) or not _TRAIN_WINDOW_RE.match(train_window):
add(
"bad_format",
"train_window",
"train_window 必须形如 '<正数><单位>'(单位 d/w/h/m),如 '180d'、'4w'",
)
# 7. alarm_threshold(可选,对象,含 type)
alarm = pack.get("alarm_threshold")
if alarm is not None:
if not isinstance(alarm, dict):
add("bad_type", "alarm_threshold", f"alarm_threshold 必须为对象,实际为 {type(alarm).__name__}")
else:
atype = alarm.get("type")
known_alarm_types = ("zscore", "quantile", "absolute")
if not isinstance(atype, str) or atype not in known_alarm_types:
add(
"unknown_alarm_type",
"alarm_threshold.type",
f"alarm_threshold.type 必须为 {known_alarm_types} 之一",
)
if atype == "zscore" and "k" not in alarm:
add("missing_field", "alarm_threshold.k", "zscore 阈值缺少 k")
if atype == "quantile" and "q" not in alarm:
add("missing_field", "alarm_threshold.q", "quantile 阈值缺少 q")
if atype == "absolute" and "value" not in alarm:
add("missing_field", "alarm_threshold.value", "absolute 阈值缺少 value")
# 8. drift_check(可选,对象,method + limit)
drift = pack.get("drift_check")
if drift is not None:
if not isinstance(drift, dict):
add("bad_type", "drift_check", f"drift_check 必须为对象,实际为 {type(drift).__name__}")
else:
method = drift.get("method")
known_methods = ("psi", "ks", "chi2")
if not isinstance(method, str) or method not in known_methods:
add(
"unknown_drift_method",
"drift_check.method",
f"drift_check.method 必须为 {known_methods} 之一",
)
limit = drift.get("limit")
if limit is None:
add("missing_field", "drift_check.limit", "drift_check 缺少 limit")
elif not isinstance(limit, (int, float)) or isinstance(limit, bool):
add("bad_type", "drift_check.limit", "drift_check.limit 必须为数值")
elif not (0 < limit <= 1):
add("bad_range", "drift_check.limit", "drift_check.limit 必须在 (0, 1] 范围内")
return report
def load_pack(pack: Dict[str, Any]) -> HyperparamPack:
"""校验并把 dict 装配为 :class:`HyperparamPack`;校验失败抛 ``ValueError``。
供训练 / 推理流水线在加载超参包时 fail-fast 使用。
"""
report = validate_pack(pack)
if not report.ok:
raise ValueError(report.summary())
return HyperparamPack(
model_id=pack["model_id"],
template=pack["template"],
algorithm=pack["algorithm"],
features=list(pack["features"]),
target=pack["target"],
objective=pack.get("objective"),
hyperparams=pack.get("hyperparams"),
train_window=pack.get("train_window"),
alarm_threshold=pack.get("alarm_threshold"),
drift_check=pack.get("drift_check"),
raw=dict(pack),
)
def validate_pack_file(path: str) -> ValidationReport:
"""读取 JSON 文件并校验;文件 / JSON 解析错误也记入报告(不抛异常)。"""
report = ValidationReport()
def add(code: str, msg: str) -> None:
report.issues.append(ValidationIssue(code, "$", msg))
if not os.path.exists(path):
add("file_not_found", f"超参包文件不存在:{path}")
return report
try:
with open(path, "r", encoding="utf-8") as fh:
text = fh.read()
except OSError as exc:
add("file_read_error", f"读取超参包失败:{exc}")
return report
try:
pack = json.loads(text)
except json.JSONDecodeError as exc:
add("json_parse_error", f"超参包不是合法 JSON:{exc}")
return report
inner = validate_pack(pack)
report.issues.extend(inner.issues)
return report
-16
View File
@@ -1,16 +0,0 @@
# -*- coding: utf-8 -*-
"""测试引导:把 `core/model-framework` 以包名 `model_framework` 挂载到 sys.modules。
目录名 `model-framework` 含连字符,无法直接以包名 import;挂载后模块内相对导入
(`from .hyperparam import ...`)在 unittest 发现机制下可正常解析。
"""
import os
import sys
import types
MF_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, MF_DIR)
if "model_framework" not in sys.modules:
pkg = types.ModuleType("model_framework")
pkg.__path__ = [MF_DIR]
sys.modules["model_framework"] = pkg
@@ -1,239 +0,0 @@
# -*- coding: utf-8 -*-
"""超参包 JSON Schema 校验器测试(issue #39)。
覆盖:合法包通过 / 必填缺失 / 未知算法 / 特征重复与缺 spec / 目标函数 /
train_window 格式 / alarm_threshold / drift_check / 文件加载与 JSON 解析错误。
"""
import os
import tempfile
import unittest
import _bootstrap # noqa: F401 挂载包名
from model_framework.hyperparam import (
HyperparamPack,
load_pack,
validate_pack,
validate_pack_file,
)
def _good_pack():
"""PRD 5.3 示例的合法超参包。"""
return {
"model_id": "quality_predict_ti",
"template": "iAOP-Template-Ti",
"algorithm": "xgboost",
"features": [
{"name": "EMA_CLF_TEMP_5m", "spec": "EMA(CLF-01.TEMP, 5m)"},
{"name": "RollingStd_CL2_10", "spec": "RollingStd(CLF-01.CL2, 10)"},
],
"target": "Ti_purity",
"objective": "reg:squarederror",
"hyperparams": {"max_depth": 6, "eta": 0.1, "n_estimators": 300},
"train_window": "180d",
"alarm_threshold": {"type": "zscore", "k": 3.0},
"drift_check": {"method": "psi", "limit": 0.2},
}
class ValidatePackTest(unittest.TestCase):
def test_good_pack_passes(self):
report = validate_pack(_good_pack())
self.assertTrue(report.ok, report.summary())
self.assertEqual(report.issues, [])
def test_minimal_pack_passes(self):
report = validate_pack(
{
"model_id": "anomaly_resin",
"template": "iAOP-Template-Resin",
"algorithm": "isolation_forest",
"features": [{"name": "F1", "spec": "RateOfChange(炉压)"}],
"target": "anomaly_score",
}
)
self.assertTrue(report.ok, report.summary())
def test_missing_required_field(self):
pack = _good_pack()
del pack["algorithm"]
report = validate_pack(pack)
self.assertFalse(report.ok)
codes = [i.code for i in report.issues]
self.assertIn("missing_field", codes)
self.assertTrue(any(i.path == "algorithm" for i in report.issues))
def test_missing_all_required(self):
report = validate_pack({})
self.assertFalse(report.ok)
codes = [i.code for i in report.issues]
# 5 个必填字段全部缺失
self.assertEqual(codes.count("missing_field"), 5)
def test_unknown_algorithm_lists_known(self):
pack = _good_pack()
pack["algorithm"] = "magic_boost"
report = validate_pack(pack)
self.assertFalse(report.ok)
issue = next(i for i in report.issues if i.code == "unknown_algorithm")
self.assertIn("xgboost", issue.message)
self.assertIn("magic_boost", issue.message)
def test_empty_features_rejected(self):
pack = _good_pack()
pack["features"] = []
report = validate_pack(pack)
codes = [i.code for i in report.issues]
self.assertIn("empty_features", codes)
def test_duplicate_feature_name(self):
pack = _good_pack()
pack["features"] = [
{"name": "F1", "spec": "EMA(A, 5m)"},
{"name": "F1", "spec": "EMA(B, 5m)"},
]
report = validate_pack(pack)
codes = [i.code for i in report.issues]
self.assertIn("dup_feature", codes)
def test_feature_missing_spec(self):
pack = _good_pack()
pack["features"] = [{"name": "F1", "spec": ""}]
report = validate_pack(pack)
codes = [i.code for i in report.issues]
self.assertIn("missing_field", codes)
def test_feature_bad_name_format(self):
pack = _good_pack()
pack["features"] = [{"name": "1bad", "spec": "EMA(A,5m)"}]
report = validate_pack(pack)
codes = [i.code for i in report.issues]
self.assertIn("bad_format", codes)
def test_unknown_objective(self):
pack = _good_pack()
pack["objective"] = "reg:magic"
report = validate_pack(pack)
self.assertTrue(any(i.code == "unknown_objective" for i in report.issues))
def test_bad_train_window_format(self):
for bad in ["180", "180days", "abc", "", "1y"]:
pack = _good_pack()
pack["train_window"] = bad
report = validate_pack(pack)
self.assertTrue(
any(i.code == "bad_format" and i.path == "train_window" for i in report.issues),
f"应拒绝非法 train_window: {bad!r}",
)
def test_good_train_window_units(self):
for good in ["180d", "4w", "72h", "30m"]:
pack = _good_pack()
pack["train_window"] = good
report = validate_pack(pack)
self.assertTrue(report.ok, f"应接受合法 train_window: {good!r} -> {report.summary()}")
def test_alarm_threshold_zscore_missing_k(self):
pack = _good_pack()
pack["alarm_threshold"] = {"type": "zscore"}
report = validate_pack(pack)
self.assertTrue(any(i.code == "missing_field" and i.path == "alarm_threshold.k" for i in report.issues))
def test_alarm_threshold_unknown_type(self):
pack = _good_pack()
pack["alarm_threshold"] = {"type": "voodoo"}
report = validate_pack(pack)
self.assertTrue(any(i.code == "unknown_alarm_type" for i in report.issues))
def test_drift_check_limit_range(self):
for bad_limit in [0, 1.5, -0.1]:
pack = _good_pack()
pack["drift_check"] = {"method": "psi", "limit": bad_limit}
report = validate_pack(pack)
self.assertTrue(
any(i.code == "bad_range" for i in report.issues),
f"应拒绝非法 drift_check.limit: {bad_limit}",
)
def test_drift_check_unknown_method(self):
pack = _good_pack()
pack["drift_check"] = {"method": "magic", "limit": 0.2}
report = validate_pack(pack)
self.assertTrue(any(i.code == "unknown_drift_method" for i in report.issues))
def test_root_not_object(self):
report = validate_pack([1, 2, 3]) # type: ignore[arg-type]
self.assertFalse(report.ok)
self.assertEqual(report.issues[0].code, "bad_type")
def test_report_summary_ok(self):
self.assertEqual(validate_pack(_good_pack()).summary(), "超参包校验通过")
def test_report_summary_aggregates(self):
pack = _good_pack()
del pack["algorithm"]
del pack["target"]
summary = validate_pack(pack).summary()
self.assertIn("2 个问题", summary)
self.assertIn("missing_field", summary)
class LoadPackTest(unittest.TestCase):
def test_load_good_returns_pack(self):
pack = load_pack(_good_pack())
self.assertIsInstance(pack, HyperparamPack)
self.assertEqual(pack.model_id, "quality_predict_ti")
self.assertEqual(pack.algorithm, "xgboost")
self.assertEqual(pack.feature_names, ["EMA_CLF_TEMP_5m", "RollingStd_CL2_10"])
self.assertEqual(pack.hyperparams["max_depth"], 6)
def test_load_bad_raises(self):
pack = _good_pack()
del pack["features"]
with self.assertRaises(ValueError) as cm:
load_pack(pack)
self.assertIn("超参包校验未通过", str(cm.exception))
class ValidatePackFileTest(unittest.TestCase):
def setUp(self):
self._tmp = tempfile.mkdtemp()
self.path = os.path.join(self._tmp, "pack.json")
def _write(self, text):
with open(self.path, "w", encoding="utf-8") as fh:
fh.write(text)
return self.path
def test_valid_file_passes(self):
import json
self._write(json.dumps(_good_pack()))
report = validate_pack_file(self.path)
self.assertTrue(report.ok, report.summary())
def test_missing_file(self):
report = validate_pack_file(os.path.join(self._tmp, "nope.json"))
self.assertFalse(report.ok)
self.assertEqual(report.issues[0].code, "file_not_found")
def test_bad_json(self):
self._write("{ not json ")
report = validate_pack_file(self.path)
self.assertFalse(report.ok)
self.assertEqual(report.issues[0].code, "json_parse_error")
def test_file_with_schema_errors(self):
import json
bad = _good_pack()
bad["algorithm"] = "unknown_thing"
self._write(json.dumps(bad))
report = validate_pack_file(self.path)
self.assertFalse(report.ok)
self.assertEqual(report.issues[0].code, "unknown_algorithm")
if __name__ == "__main__":
unittest.main()