Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bc7ff957e | ||
|
|
f6cdc84860 | ||
|
|
c8d6e725a2 |
@@ -1,82 +0,0 @@
|
||||
# 配置化驾驶舱内核模块(iAOP-Core / cockpit)
|
||||
|
||||
对齐 PRD 5.5「⑤ 配置化驾驶舱」:把驾驶舱抽象为模板化配置资产,按"布局/配置"渲染,
|
||||
切换行业模板零改前端代码(PRD 5.5 验收口径)。
|
||||
|
||||
## 模块状态
|
||||
|
||||
| 能力 | Issue | 状态 |
|
||||
| --- | --- | --- |
|
||||
| 布局 JSON Schema 定义 + 校验/解析 | #50 | feature/issue-50(推进中) |
|
||||
| 图表组件配置化渲染引擎(RenderPlan) | #51 | feature/issue-51(推进中) |
|
||||
| **报警看板配置化(阈值/规则外置)** | **#52** | **本分支 feature/issue-52** |
|
||||
|
||||
#52「报警看板配置化」把告警面板(`alarm_panel`)的展示语义外置为模板配置资产,
|
||||
让"换行业只换配置、前端代码零改动"也覆盖到告警面板。配置点:
|
||||
|
||||
- **严重度→颜色映射**(`severityColors`):P0/P1/P2 三级各自的 `fg`/`bg`/可选 `icon`/`border`,
|
||||
覆盖主题默认告警色;驾驶舱红色告警(PRD 5.3 ③ 场景A)即由 `P0` 的 `fg` 决定。
|
||||
- **告警规则 / 阈值源绑定**(`rulesSource` / `thresholdsSource`):告警面板订阅哪份
|
||||
规则资产(`kind: asset` + `ref`)或内联规则(`kind: inline` + `data`)——把"看哪条规则"
|
||||
也变成配置项,避免把规则 id 写死在前端。
|
||||
- **SOP 联动**(`showSop`):PRD 场景A「LLM 生成原因+处置建议 → 值班长确认」是否在面板展开。
|
||||
- **确认 / 静默行为**(`requireAck` / `ackTimeoutS` / `muteLower`):关键告警是否强制人工确认、
|
||||
超时升级、是否静默低于某 severity 的提示。
|
||||
- **分组 / 排序 / 最大条数**(`groupBy` / `sortBy` / `maxItems`):大屏展示策略外置。
|
||||
|
||||
## 用法
|
||||
|
||||
```python
|
||||
from cockpit import (
|
||||
validate_alarm_config, load_alarm_config, render_alarm_panel_props,
|
||||
)
|
||||
|
||||
# 1) 配置资产(通常来自模板 YAML;这里用 dict 示意)
|
||||
config = {
|
||||
"$schema": "iAOP-cockpit-alarm-panel-v1",
|
||||
"severityColors": [
|
||||
{"severity": "P0", "fg": "#ff3b30", "bg": "rgba(255,59,48,0.12)", "icon": "alert-octagon"},
|
||||
{"severity": "P1", "fg": "#f5a623", "bg": "rgba(245,166,35,0.12)"},
|
||||
{"severity": "P2", "fg": "#3aa0ff", "bg": "rgba(58,160,255,0.10)"},
|
||||
],
|
||||
"rulesSource": {"kind": "asset", "ref": "ti-cl4/impurity-forecast/config/alert_rules.template.yaml"},
|
||||
"showSop": True, "requireAck": True, "ackTimeoutS": 300, "muteLower": "P2",
|
||||
"groupBy": "severity", "sortBy": "severity", "maxItems": 50,
|
||||
}
|
||||
|
||||
# 2) 校验(聚合全部字段级错误,便于配置台「错误列表」展示)
|
||||
result = validate_alarm_config(config)
|
||||
assert result.ok, result.errors
|
||||
|
||||
# 3) 加载为内存模型
|
||||
cfg = load_alarm_config(config)
|
||||
|
||||
# 4) 编译为 alarm_panel 组件的 props(#51 渲染层在 _build_props 里合并即可)
|
||||
props = render_alarm_panel_props(cfg)
|
||||
# -> {'subscribe': 'alarm_stream', 'severityStyles': {...}, 'rulesSource': {...},
|
||||
# 'showSop': True, 'requireAck': True, 'ackTimeoutS': 300, ...}
|
||||
```
|
||||
|
||||
切换行业模板(如树脂)= 换一份配置资产(不同配色 / 规则源),`render_alarm_panel_props`
|
||||
随配置变化产出不同 props,**前端代码零改动**。
|
||||
|
||||
## 设计要点
|
||||
|
||||
- **零运行时依赖**:只用标准库,配置资产是可 `json.dumps` 的纯 dict,便于配置台发布与审计。
|
||||
- **声明式 + 强校验**:`validate_alarm_config` 收集全部字段级错误(沿用 #50
|
||||
`LayoutValidationResult` 风格);`load_alarm_config` 校验失败抛 `AlarmConfigError`
|
||||
并携带错误清单。
|
||||
- **与 #50/#51 解耦**:本模块不 import `layout` / `renderer`(它们在各自 feature 分支上推进),
|
||||
避免对未合并分支形成硬依赖;`render_alarm_panel_props` 仅产出 `alarm_panel` 组件的 props dict,
|
||||
由 #51 渲染层在 `_build_props` 里合并即可。#50/#51 合入 main 后,本模块的 `__init__`
|
||||
会合并它们的导出(`CockpitLayout` / `validate_layout` / `RenderPlan` 等)。
|
||||
|
||||
## 测试 / 验收
|
||||
|
||||
```bash
|
||||
# 在 core/cockpit 目录下
|
||||
python -m unittest discover -s tests -p "test_alarm_config.py" -v # 28 用例
|
||||
python scripts/verify_alarm_config.py # 验收脚本
|
||||
```
|
||||
|
||||
参考资产:`templates/ti-cl4/dashboard/alarm_panel.ti.yaml`(氯化车间/海绵钛告警面板配置)。
|
||||
@@ -1,58 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""配置化驾驶舱内核模块(iAOP-Core / cockpit)—— 对齐 PRD 5.5「⑤ 配置化驾驶舱」。
|
||||
|
||||
当前对外暴露 issue #52「报警看板配置化(阈值/规则外置)」的能力:把告警面板的
|
||||
展示语义(严重度配色 / 规则源 / SOP / 确认 / 分组排序)外置为模板配置资产。
|
||||
|
||||
布局 JSON Schema(#50)与渲染层(#51)在其各自 feature 分支上推进;合入 main
|
||||
后,本 ``__init__`` 会合并它们的导出(``CockpitLayout`` / ``validate_layout`` /
|
||||
``RenderPlan`` 等)。当前只导出 #52 的告警面板配置 API,保证 #52 在 main 上
|
||||
可独立运行、可独立测试。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .alarm_config import ( # noqa: F401
|
||||
ALARM_CONFIG_SCHEMA_ID,
|
||||
ALARM_CONFIG_SCHEMA_VERSION,
|
||||
DEFAULT_ACK_TIMEOUT_S,
|
||||
DEFAULT_MAX_ITEMS,
|
||||
DEFAULT_MUTE_LOWER,
|
||||
MAX_ALLOWED_ITEMS,
|
||||
SEVERITY_RANK,
|
||||
VALID_GROUP_BY,
|
||||
VALID_SEVERITIES,
|
||||
VALID_SORT_BY,
|
||||
VALID_SOURCE_KINDS,
|
||||
AlarmConfigError,
|
||||
AlarmConfigValidationResult,
|
||||
AlarmPanelConfig,
|
||||
AlarmRulesSource,
|
||||
SeverityColor,
|
||||
filter_alarms_by_mute,
|
||||
load_alarm_config,
|
||||
render_alarm_panel_props,
|
||||
validate_alarm_config,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ALARM_CONFIG_SCHEMA_ID",
|
||||
"ALARM_CONFIG_SCHEMA_VERSION",
|
||||
"DEFAULT_ACK_TIMEOUT_S",
|
||||
"DEFAULT_MAX_ITEMS",
|
||||
"DEFAULT_MUTE_LOWER",
|
||||
"MAX_ALLOWED_ITEMS",
|
||||
"SEVERITY_RANK",
|
||||
"VALID_GROUP_BY",
|
||||
"VALID_SEVERITIES",
|
||||
"VALID_SORT_BY",
|
||||
"VALID_SOURCE_KINDS",
|
||||
"AlarmConfigError",
|
||||
"AlarmConfigValidationResult",
|
||||
"AlarmPanelConfig",
|
||||
"AlarmRulesSource",
|
||||
"SeverityColor",
|
||||
"filter_alarms_by_mute",
|
||||
"load_alarm_config",
|
||||
"render_alarm_panel_props",
|
||||
"validate_alarm_config",
|
||||
]
|
||||
@@ -1,519 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""报警看板配置化(issue #52 / PRD 5.5「⑤ 配置化驾驶舱」)。
|
||||
|
||||
PRD 5.5 的告警面板(``alarm_panel``)在 #50/#51 里被实现为「固定订阅
|
||||
``alarm_stream``、套用主题默认告警色」的硬编码组件。本模块把告警面板的
|
||||
**展示语义外置为模板配置**(PRD line 152/171:阈值/规则外置 JSON,行业工程师
|
||||
在配置台维护),让"换行业只换配置资产、前端代码零改动"这条验收口径也覆盖到
|
||||
告警面板。
|
||||
|
||||
外置的配置点(均由行业模板在配置台维护):
|
||||
|
||||
1. **严重度→颜色映射**(``severity_colors``):P0/P1/P2 三级各自的前景色 /
|
||||
背景色 / 图标,覆盖主题默认告警色;驾驶舱红色告警(PRD 5.3 ③ 场景A)
|
||||
即由 ``P0`` 的 ``fg`` 决定,**换行业只改这张映射表**。
|
||||
2. **告警规则 / 阈值源绑定**(``rules_source`` / ``thresholds_source``):
|
||||
告警面板订阅哪份规则资产(如 ``templates/ti-cl4/impurity-forecast/
|
||||
config/alert_rules.template.yaml``)与哪份阈值包——把"看哪条规则"
|
||||
也变成配置项,避免把规则 id 写死在前端。
|
||||
3. **SOP 联动开关**(``show_sop``):PRD 场景A「LLM 生成原因+处置建议 →
|
||||
值班长确认」,是否在面板里展开处置 SOP(高利害人工确认,PRD line 333)。
|
||||
4. **确认 / 静默行为**(``require_ack`` / ``ack_timeout_s`` / ``mute_lower``):
|
||||
关键告警是否强制人工确认、超时升级、是否静默低于某 severity 的提示。
|
||||
5. **分组 / 排序 / 最大条数**(``group_by`` / ``sort_by`` / ``max_items``):
|
||||
大屏展示策略外置(与 #51 的 perf 策略互补:这里是"展示多少/怎么排",
|
||||
#51 是"怎么渲染得快")。
|
||||
|
||||
设计要点
|
||||
--------
|
||||
- **零运行时依赖**:与 #50/#51、data-bus、rag-kb 一致,只用标准库;
|
||||
配置资产是可 ``json.dumps`` 的纯 dict,便于配置台发布与审计。
|
||||
- **声明式 + 强校验**:``validate_alarm_config`` 收集全部字段级错误
|
||||
(沿用 #50 ``LayoutValidationResult`` 风格),``load_alarm_config`` 在校验
|
||||
不通过时抛 ``AlarmConfigError`` 并携带错误清单,便于配置台「错误列表」展示。
|
||||
- **与 #50/#51 解耦**:本模块不 import ``layout`` / ``renderer``(它们尚未合入
|
||||
main),避免对未合并分支形成硬依赖;``render_alarm_panel_props`` 仅产出一份
|
||||
``alarm_panel`` 组件的 props dict,由 #51 渲染层在 ``_build_props`` 里合并即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 版本标识(被告警面板配置资产的 $schema 引用)
|
||||
# ---------------------------------------------------------------------------
|
||||
ALARM_CONFIG_SCHEMA_ID: str = "iAOP-cockpit-alarm-panel-v1"
|
||||
ALARM_CONFIG_SCHEMA_VERSION: int = 1
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 合法性集合
|
||||
# ---------------------------------------------------------------------------
|
||||
# 严重度三级(与 templates/ti-cl4/impurity-forecast/alert_rules.py 的 AlertSeverity 对齐)。
|
||||
VALID_SEVERITIES: Tuple[str, ...] = ("P0", "P1", "P2")
|
||||
|
||||
# severity 排序权重(越大越严重;用于 mute_lower / sort_by=severity 的排序基准)。
|
||||
SEVERITY_RANK: Dict[str, int] = {"P0": 3, "P1": 2, "P2": 1}
|
||||
|
||||
# severity_colors 里每个 severity 必须声明的颜色键。
|
||||
_REQUIRED_COLOR_KEYS: Tuple[str, ...] = ("fg", "bg")
|
||||
# severity_colors 里允许额外声明的可选颜色键(图标 / 边框)。
|
||||
_OPTIONAL_COLOR_KEYS: Tuple[str, ...] = ("icon", "border")
|
||||
|
||||
# rules_source / thresholds_source 允许的 ``kind`` 取值:
|
||||
# - asset : 指向模板仓库内的一份配置资产路径(如 alert_rules.template.yaml)
|
||||
# - inline : 内联在配置里(rules_source.data 直接给出规则声明列表)
|
||||
VALID_SOURCE_KINDS: Tuple[str, ...] = ("asset", "inline")
|
||||
|
||||
# 告警面板允许的分组维度(PRD 5.5 能力:可按 severity / 工序 / 规则分组)。
|
||||
VALID_GROUP_BY: Tuple[str, ...] = ("severity", "rule", "process")
|
||||
|
||||
# 告警面板允许的排序键(severity 按严重度;time 按触发时间倒序)。
|
||||
VALID_SORT_BY: Tuple[str, ...] = ("severity", "time")
|
||||
|
||||
# 静默下限:低于该 severity 的告警不展示(默认 P2 = 提示级也展示,即不静默)。
|
||||
DEFAULT_MUTE_LOWER: str = "P2"
|
||||
|
||||
# 单面板最大展示条数(PRD 5.5 大屏策略:超过则折叠 + 计数角标)。
|
||||
DEFAULT_MAX_ITEMS: int = 50
|
||||
MAX_ALLOWED_ITEMS: int = 500
|
||||
|
||||
# 确认超时下限(秒):require_ack=True 时,超时未确认自动升级 severity。
|
||||
DEFAULT_ACK_TIMEOUT_S: int = 300
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 异常 / 结果
|
||||
# ---------------------------------------------------------------------------
|
||||
class AlarmConfigError(ValueError):
|
||||
"""告警面板配置校验失败。``load_alarm_config`` 在校验不通过时抛出。
|
||||
|
||||
``errors`` 收集全部字段级错误,便于配置台「错误列表(行号+原因)」展示,
|
||||
沿用 #50 ``LayoutValidationError`` 的多错误聚合风格。
|
||||
"""
|
||||
|
||||
def __init__(self, errors: List[str]):
|
||||
super().__init__("; ".join(errors) if errors else "alarm panel config validation failed")
|
||||
self.errors: List[str] = list(errors)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AlarmConfigValidationResult:
|
||||
"""``validate_alarm_config`` 的返回值,区分「是否合法」与「全部错误清单」。"""
|
||||
|
||||
ok: bool
|
||||
errors: List[str] = field(default_factory=list)
|
||||
# 校验通过后回填的规范化配置(补默认值后的 dict),便于直接发布/渲染。
|
||||
normalized: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 内存模型(dataclass)
|
||||
# ---------------------------------------------------------------------------
|
||||
@dataclass
|
||||
class SeverityColor:
|
||||
"""单个严重度的展示配色(覆盖主题默认告警色)。
|
||||
|
||||
Attributes:
|
||||
severity: P0 / P1 / P2。
|
||||
fg: 前景色(告警文本 / 图标颜色;P0 的 fg 即驾驶舱「红色告警」)。
|
||||
bg: 背景色(告警条底色)。
|
||||
icon: 可选图标名(如 ``"alert-triangle"``)。
|
||||
border: 可选左边框色(用于告警条强调)。
|
||||
"""
|
||||
|
||||
severity: str
|
||||
fg: str
|
||||
bg: str
|
||||
icon: Optional[str] = None
|
||||
border: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
d: Dict[str, Any] = {"severity": self.severity, "fg": self.fg, "bg": self.bg}
|
||||
if self.icon is not None:
|
||||
d["icon"] = self.icon
|
||||
if self.border is not None:
|
||||
d["border"] = self.border
|
||||
return d
|
||||
|
||||
|
||||
@dataclass
|
||||
class AlarmRulesSource:
|
||||
"""告警规则 / 阈值的来源绑定(PRD「阈值外置 JSON」)。
|
||||
|
||||
Attributes:
|
||||
kind: ``asset``(模板仓库内资产路径)或 ``inline``(内联声明)。
|
||||
ref: ``asset`` 时的资产路径(相对模板根,如
|
||||
``ti-cl4/impurity-forecast/config/alert_rules.template.yaml``)。
|
||||
data: ``inline`` 时的规则声明列表(每条是 {id, severity, ...} dict)。
|
||||
"""
|
||||
|
||||
kind: str
|
||||
ref: Optional[str] = None
|
||||
data: Optional[List[Dict[str, Any]]] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
d: Dict[str, Any] = {"kind": self.kind}
|
||||
if self.ref is not None:
|
||||
d["ref"] = self.ref
|
||||
if self.data is not None:
|
||||
d["data"] = list(self.data)
|
||||
return d
|
||||
|
||||
|
||||
@dataclass
|
||||
class AlarmPanelConfig:
|
||||
"""一份告警面板配置的内存模型(对应一份模板级配置资产)。
|
||||
|
||||
渲染层(Vue3 / 配置台)消费本对象即可驱动 ``AlarmPanel`` 组件的全部展示
|
||||
行为:切换行业模板 = 加载另一份 ``AlarmPanelConfig``,**前端代码零改动**。
|
||||
"""
|
||||
|
||||
severity_colors: List[SeverityColor]
|
||||
rules_source: AlarmRulesSource
|
||||
thresholds_source: Optional[AlarmRulesSource] = None
|
||||
show_sop: bool = True
|
||||
require_ack: bool = False
|
||||
ack_timeout_s: int = DEFAULT_ACK_TIMEOUT_S
|
||||
mute_lower: str = DEFAULT_MUTE_LOWER
|
||||
group_by: str = "severity"
|
||||
sort_by: str = "severity"
|
||||
max_items: int = DEFAULT_MAX_ITEMS
|
||||
schema: str = ALARM_CONFIG_SCHEMA_ID
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""序列化为可发布的配置资产 dict(结构对齐校验器输入)。"""
|
||||
d: Dict[str, Any] = {
|
||||
"$schema": self.schema,
|
||||
"severityColors": [c.to_dict() for c in self.severity_colors],
|
||||
"rulesSource": self.rules_source.to_dict(),
|
||||
"showSop": self.show_sop,
|
||||
"requireAck": self.require_ack,
|
||||
"muteLower": self.mute_lower,
|
||||
"groupBy": self.group_by,
|
||||
"sortBy": self.sort_by,
|
||||
"maxItems": self.max_items,
|
||||
}
|
||||
if self.thresholds_source is not None:
|
||||
d["thresholdsSource"] = self.thresholds_source.to_dict()
|
||||
if self.require_ack:
|
||||
d["ackTimeoutS"] = self.ack_timeout_s
|
||||
return d
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 校验器
|
||||
# ---------------------------------------------------------------------------
|
||||
def _is_str_nonempty(value: Any) -> bool:
|
||||
return isinstance(value, str) and value.strip() != ""
|
||||
|
||||
|
||||
def _validate_source(
|
||||
source: Any, field_name: str, errors: List[str], required: bool
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""校验一个 rules_source / thresholds_source dict。
|
||||
|
||||
返回规范化后的 dict(校验通过时),或 None(非法 / 缺失)。
|
||||
"""
|
||||
ctx = field_name
|
||||
if source is None:
|
||||
if required:
|
||||
errors.append(f"{ctx}: 缺失(告警面板必须绑定 rulesSource)")
|
||||
return None
|
||||
if not isinstance(source, dict):
|
||||
errors.append(f"{ctx}: 必须是对象(dict),实际为 {type(source).__name__}")
|
||||
return None
|
||||
|
||||
kind = source.get("kind")
|
||||
if kind not in VALID_SOURCE_KINDS:
|
||||
errors.append(
|
||||
f"{ctx}.kind: 非法 {kind!r},合法值 {list(VALID_SOURCE_KINDS)}"
|
||||
)
|
||||
return None
|
||||
|
||||
normalized: Dict[str, Any] = {"kind": kind}
|
||||
|
||||
if kind == "asset":
|
||||
ref = source.get("ref")
|
||||
if not _is_str_nonempty(ref):
|
||||
errors.append(f"{ctx}.ref: kind=asset 时必须给出非空资产路径")
|
||||
else:
|
||||
normalized["ref"] = ref
|
||||
else: # inline
|
||||
data = source.get("data")
|
||||
if not isinstance(data, list) or not data:
|
||||
errors.append(f"{ctx}.data: kind=inline 时必须给出非空规则声明列表")
|
||||
else:
|
||||
# 每条内联规则至少要有 id(便于驾驶舱引用 / 审计)
|
||||
bad = [
|
||||
str(i)
|
||||
for i, item in enumerate(data)
|
||||
if not isinstance(item, dict) or not _is_str_nonempty(item.get("id"))
|
||||
]
|
||||
if bad:
|
||||
errors.append(
|
||||
f"{ctx}.data: 内联规则项 {','.join(bad)} 缺失 id 或非对象"
|
||||
)
|
||||
else:
|
||||
normalized["data"] = list(data)
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def validate_alarm_config(config: Any) -> AlarmConfigValidationResult:
|
||||
"""对一份告警面板配置资产做结构 + 语义校验,返回校验结果。
|
||||
|
||||
非法资产不会提前返回:尽量收集全部字段级错误,便于配置台一次性展示
|
||||
「错误列表(字段 + 原因)」,与 #50 ``validate_layout`` 行为一致。
|
||||
"""
|
||||
errors: List[str] = []
|
||||
|
||||
if not isinstance(config, dict):
|
||||
return AlarmConfigValidationResult(
|
||||
ok=False, errors=[f"配置必须是对象(dict),实际为 {type(config).__name__}"]
|
||||
)
|
||||
|
||||
# $schema(选填,但若给出必须对齐版本标识)
|
||||
schema = config.get("$schema")
|
||||
if schema is not None and schema != ALARM_CONFIG_SCHEMA_ID:
|
||||
errors.append(
|
||||
f"$schema: 应为 {ALARM_CONFIG_SCHEMA_ID!r},实际为 {schema!r}"
|
||||
)
|
||||
|
||||
# severityColors:必填、至少覆盖 P0/P1/P2 三级、每级颜色键齐全
|
||||
raw_colors = config.get("severityColors", config.get("severity_colors"))
|
||||
color_by_sev: Dict[str, Dict[str, Any]] = {}
|
||||
if not isinstance(raw_colors, list) or not raw_colors:
|
||||
errors.append("severityColors: 缺失或非列表(至少需要 P0/P1/P2 三级配色)")
|
||||
else:
|
||||
for i, item in enumerate(raw_colors):
|
||||
ctx = f"severityColors[{i}]"
|
||||
if not isinstance(item, dict):
|
||||
errors.append(f"{ctx}: 必须是对象(dict)")
|
||||
continue
|
||||
sev = item.get("severity")
|
||||
if sev not in VALID_SEVERITIES:
|
||||
errors.append(
|
||||
f"{ctx}.severity: 非法 {sev!r},合法值 {list(VALID_SEVERITIES)}"
|
||||
)
|
||||
continue
|
||||
if sev in color_by_sev:
|
||||
errors.append(f"{ctx}.severity: {sev!r} 重复声明")
|
||||
continue
|
||||
norm_color: Dict[str, Any] = {"severity": sev}
|
||||
color_ok = True
|
||||
for key in _REQUIRED_COLOR_KEYS:
|
||||
v = item.get(key)
|
||||
if not _is_str_nonempty(v):
|
||||
errors.append(f"{ctx}.{key}: 缺失或非非空字符串")
|
||||
color_ok = False
|
||||
else:
|
||||
norm_color[key] = v
|
||||
for key in _OPTIONAL_COLOR_KEYS:
|
||||
v = item.get(key)
|
||||
if v is None:
|
||||
continue
|
||||
if not _is_str_nonempty(v):
|
||||
errors.append(f"{ctx}.{key}: 给出则必须是非空字符串")
|
||||
else:
|
||||
norm_color[key] = v
|
||||
if color_ok:
|
||||
color_by_sev[sev] = norm_color
|
||||
|
||||
for sev in VALID_SEVERITIES:
|
||||
if sev not in color_by_sev:
|
||||
errors.append(f"severityColors: 缺少 {sev} 级配色(必须覆盖 P0/P1/P2)")
|
||||
|
||||
# rulesSource:必填
|
||||
raw_rules = config.get("rulesSource", config.get("rules_source"))
|
||||
norm_rules = _validate_source(raw_rules, "rulesSource", errors, required=True)
|
||||
|
||||
# thresholdsSource:选填(阈值可与规则同源,也可独立)
|
||||
raw_thr = config.get("thresholdsSource", config.get("thresholds_source"))
|
||||
norm_thr = _validate_source(raw_thr, "thresholdsSource", errors, required=False)
|
||||
|
||||
# showSop:布尔
|
||||
show_sop = config.get("showSop", config.get("show_sop", True))
|
||||
if not isinstance(show_sop, bool):
|
||||
errors.append(f"showSop: 必须是布尔,实际为 {type(show_sop).__name__}")
|
||||
|
||||
# requireAck:布尔
|
||||
require_ack = config.get("requireAck", config.get("require_ack", False))
|
||||
if not isinstance(require_ack, bool):
|
||||
errors.append(f"requireAck: 必须是布尔,实际为 {type(require_ack).__name__}")
|
||||
|
||||
# ackTimeoutS:require_ack 时才生效,给出则必须是正整数
|
||||
ack_timeout = config.get("ackTimeoutS", config.get("ack_timeout_s", DEFAULT_ACK_TIMEOUT_S))
|
||||
if isinstance(ack_timeout, bool) or not isinstance(ack_timeout, int) or ack_timeout <= 0:
|
||||
errors.append(f"ackTimeoutS: 必须是正整数(秒),实际为 {ack_timeout!r}")
|
||||
|
||||
# muteLower:必须是合法 severity
|
||||
mute_lower = config.get("muteLower", config.get("mute_lower", DEFAULT_MUTE_LOWER))
|
||||
if mute_lower not in VALID_SEVERITIES:
|
||||
errors.append(
|
||||
f"muteLower: 非法 {mute_lower!r},合法值 {list(VALID_SEVERITIES)}"
|
||||
)
|
||||
|
||||
# groupBy / sortBy:枚举
|
||||
group_by = config.get("groupBy", config.get("group_by", "severity"))
|
||||
if group_by not in VALID_GROUP_BY:
|
||||
errors.append(f"groupBy: 非法 {group_by!r},合法值 {list(VALID_GROUP_BY)}")
|
||||
sort_by = config.get("sortBy", config.get("sort_by", "severity"))
|
||||
if sort_by not in VALID_SORT_BY:
|
||||
errors.append(f"sortBy: 非法 {sort_by!r},合法值 {list(VALID_SORT_BY)}")
|
||||
|
||||
# maxItems:1..MAX_ALLOWED_ITEMS
|
||||
max_items = config.get("maxItems", config.get("max_items", DEFAULT_MAX_ITEMS))
|
||||
if (
|
||||
isinstance(max_items, bool)
|
||||
or not isinstance(max_items, int)
|
||||
or not (1 <= max_items <= MAX_ALLOWED_ITEMS)
|
||||
):
|
||||
errors.append(
|
||||
f"maxItems: 必须是 1..{MAX_ALLOWED_ITEMS} 的整数,实际为 {max_items!r}"
|
||||
)
|
||||
|
||||
if errors:
|
||||
return AlarmConfigValidationResult(ok=False, errors=errors)
|
||||
|
||||
# 规范化输出(统一字段名 + 补默认值),便于直接发布 / 渲染。
|
||||
normalized: Dict[str, Any] = {
|
||||
"$schema": ALARM_CONFIG_SCHEMA_ID,
|
||||
"severityColors": [color_by_sev[sev] for sev in VALID_SEVERITIES],
|
||||
"rulesSource": norm_rules,
|
||||
"showSop": show_sop,
|
||||
"requireAck": require_ack,
|
||||
"ackTimeoutS": ack_timeout if require_ack else DEFAULT_ACK_TIMEOUT_S,
|
||||
"muteLower": mute_lower,
|
||||
"groupBy": group_by,
|
||||
"sortBy": sort_by,
|
||||
"maxItems": max_items,
|
||||
}
|
||||
if norm_thr is not None:
|
||||
normalized["thresholdsSource"] = norm_thr
|
||||
|
||||
return AlarmConfigValidationResult(ok=True, errors=[], normalized=normalized)
|
||||
|
||||
|
||||
def load_alarm_config(config: Any) -> AlarmPanelConfig:
|
||||
"""从已解析的 dict 构造 ``AlarmPanelConfig``(校验失败抛 ``AlarmConfigError``)。
|
||||
|
||||
与 #50 ``load_layout`` 对称:先 ``validate_alarm_config``,再按规范化结果
|
||||
构造内存模型;校验不通过时把全部错误聚合到异常里。
|
||||
"""
|
||||
result = validate_alarm_config(config)
|
||||
if not result.ok:
|
||||
raise AlarmConfigError(result.errors)
|
||||
assert result.normalized is not None # 校验通过一定回填 normalized
|
||||
|
||||
norm = result.normalized
|
||||
|
||||
severity_colors = [
|
||||
SeverityColor(
|
||||
severity=c["severity"],
|
||||
fg=c["fg"],
|
||||
bg=c["bg"],
|
||||
icon=c.get("icon"),
|
||||
border=c.get("border"),
|
||||
)
|
||||
for c in norm["severityColors"]
|
||||
]
|
||||
|
||||
def _to_source(d: Dict[str, Any]) -> AlarmRulesSource:
|
||||
return AlarmRulesSource(
|
||||
kind=d["kind"],
|
||||
ref=d.get("ref"),
|
||||
data=d.get("data"),
|
||||
)
|
||||
|
||||
thresholds_source = None
|
||||
if norm.get("thresholdsSource") is not None:
|
||||
thresholds_source = _to_source(norm["thresholdsSource"])
|
||||
|
||||
return AlarmPanelConfig(
|
||||
severity_colors=severity_colors,
|
||||
rules_source=_to_source(norm["rulesSource"]),
|
||||
thresholds_source=thresholds_source,
|
||||
show_sop=norm["showSop"],
|
||||
require_ack=norm["requireAck"],
|
||||
ack_timeout_s=norm["ackTimeoutS"],
|
||||
mute_lower=norm["muteLower"],
|
||||
group_by=norm["groupBy"],
|
||||
sort_by=norm["sortBy"],
|
||||
max_items=norm["maxItems"],
|
||||
schema=ALARM_CONFIG_SCHEMA_ID,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 渲染辅助:把告警面板配置编译成 alarm_panel 组件的 props
|
||||
# ---------------------------------------------------------------------------
|
||||
def render_alarm_panel_props(config: AlarmPanelConfig) -> Dict[str, Any]:
|
||||
"""把一份 ``AlarmPanelConfig`` 编译成 ``alarm_panel`` 组件的 props dict。
|
||||
|
||||
#51 渲染层在 ``_build_props`` 里对 ``alarm_panel`` 原本只写死
|
||||
``subscribe="alarm_stream"``;合入本模块后改为合并本函数的输出即可,
|
||||
前端 ``AlarmPanel`` 组件据此驱动「颜色 / 规则源 / SOP / 确认 / 分组排序」,
|
||||
**切换行业模板只换配置资产,前端代码零改动**(PRD 5.5 验收口径)。
|
||||
|
||||
返回的 props 与 #51 的 props 风格一致:扁平、可直接 ``json.dumps``、
|
||||
键名用前端友好的 camelCase。
|
||||
"""
|
||||
# severity → 展示描述(颜色 + 可选图标 / 边框),驱动告警条着色
|
||||
severity_styles: Dict[str, Dict[str, Any]] = {}
|
||||
for c in config.severity_colors:
|
||||
style: Dict[str, Any] = {"fg": c.fg, "bg": c.bg}
|
||||
if c.icon is not None:
|
||||
style["icon"] = c.icon
|
||||
if c.border is not None:
|
||||
style["border"] = c.border
|
||||
severity_styles[c.severity] = style
|
||||
|
||||
# 规则 / 阈值源:asset 透传 ref,inline 透传 data
|
||||
def _source_props(src: AlarmRulesSource) -> Dict[str, Any]:
|
||||
if src.kind == "asset":
|
||||
return {"kind": "asset", "ref": src.ref or ""}
|
||||
return {"kind": "inline", "data": list(src.data or [])}
|
||||
|
||||
props: Dict[str, Any] = {
|
||||
# 保留 #51 原有的订阅语义(向后兼容)
|
||||
"subscribe": "alarm_stream",
|
||||
"severityStyles": severity_styles,
|
||||
"rulesSource": _source_props(config.rules_source),
|
||||
"showSop": config.show_sop,
|
||||
"requireAck": config.require_ack,
|
||||
"muteLower": config.mute_lower,
|
||||
"groupBy": config.group_by,
|
||||
"sortBy": config.sort_by,
|
||||
"maxItems": config.max_items,
|
||||
}
|
||||
if config.thresholds_source is not None:
|
||||
props["thresholdsSource"] = _source_props(config.thresholds_source)
|
||||
if config.require_ack:
|
||||
props["ackTimeoutS"] = config.ack_timeout_s
|
||||
|
||||
return props
|
||||
|
||||
|
||||
def filter_alarms_by_mute(
|
||||
alarms: List[Dict[str, Any]],
|
||||
mute_lower: str = DEFAULT_MUTE_LOWER,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""按 ``mute_lower`` 过滤告警列表(演示配置如何驱动展示策略)。
|
||||
|
||||
给定一批告警 dict(每条含 ``severity``),返回严重度 ≥ ``mute_lower`` 的子集。
|
||||
用于验证「静默下限」配置点真正生效——配置台改 ``muteLower`` 即可改变面板
|
||||
展示内容,无需改前端代码。``sort_by=severity`` 时同时按严重度降序排序。
|
||||
"""
|
||||
if mute_lower not in SEVERITY_RANK:
|
||||
raise AlarmConfigError([f"mute_lower 非法: {mute_lower!r}"])
|
||||
floor = SEVERITY_RANK[mute_lower]
|
||||
kept = [
|
||||
a for a in alarms
|
||||
if isinstance(a, dict) and SEVERITY_RANK.get(a.get("severity"), 0) >= floor
|
||||
]
|
||||
return sorted(
|
||||
kept,
|
||||
key=lambda a: SEVERITY_RANK.get(a.get("severity"), 0),
|
||||
reverse=True,
|
||||
)
|
||||
@@ -1,187 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""报警看板配置化验收脚本(issue #52,PRD 5.5 验收口径)。
|
||||
|
||||
验证四个能力点(覆盖 PRD 5.5「切换模板零改码」对告警面板的覆盖):
|
||||
1. **Ti 行业模板配置资产合法**:``templates/ti-cl4/dashboard/alarm_panel.ti.yaml``
|
||||
所描述的配置(等价 dict)通过 ``iAOP-cockpit-alarm-panel-v1`` 校验,
|
||||
并能渲染成 ``alarm_panel`` 组件 props(证明告警面板已配置化);
|
||||
2. **树脂模板同样可配置**:换一份配置资产(不同配色 / 规则源)即得到不同 props,
|
||||
前端代码零改动(PRD 5.5 验收口径「切换模板零改码」);
|
||||
3. **配置点真实生效**:``mute_lower`` 改变 → ``filter_alarms_by_mute`` 过滤结果
|
||||
改变;``require_ack`` 关闭 → props 里不再出现 ``ackTimeoutS``;
|
||||
4. **负例**:一份故意破坏的配置(缺 P0 配色 / 非法 severity / 缺 rulesSource)
|
||||
被正确拒绝并聚合多条错误(对齐 #50 校验器风格)。
|
||||
|
||||
用法(在 core/cockpit 目录下):
|
||||
python scripts/verify_alarm_config.py
|
||||
退出码:0 = 全部通过;1 = 存在未达标项。
|
||||
|
||||
说明:Ti 模板资产本身是 YAML;本脚本不依赖 PyYAML(避免引入运行时依赖),
|
||||
而是用与该 YAML 文件内容等价的 dict 进行校验——字段语义完全一致,
|
||||
若安装了 PyYAML,可直接解析原文件复现(见文末注释)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 本脚本位于 core/cockpit/scripts/,需要把 core/ 加入 sys.path,
|
||||
# 才能 `from cockpit import ...`(cockpit 包位于 core/cockpit)
|
||||
sys.path.insert(
|
||||
0,
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||
)
|
||||
|
||||
from cockpit import ( # noqa: E402
|
||||
ALARM_CONFIG_SCHEMA_ID,
|
||||
filter_alarms_by_mute,
|
||||
load_alarm_config,
|
||||
render_alarm_panel_props,
|
||||
validate_alarm_config,
|
||||
)
|
||||
|
||||
|
||||
def _ti_config() -> dict:
|
||||
"""与 templates/ti-cl4/dashboard/alarm_panel.ti.yaml 等价的 dict。"""
|
||||
return {
|
||||
"$schema": ALARM_CONFIG_SCHEMA_ID,
|
||||
"severityColors": [
|
||||
{"severity": "P0", "fg": "#ff3b30", "bg": "rgba(255,59,48,0.12)",
|
||||
"icon": "alert-octagon", "border": "#ff3b30"},
|
||||
{"severity": "P1", "fg": "#f5a623", "bg": "rgba(245,166,35,0.12)",
|
||||
"icon": "alert-triangle", "border": "#f5a623"},
|
||||
{"severity": "P2", "fg": "#3aa0ff", "bg": "rgba(58,160,255,0.10)",
|
||||
"icon": "info"},
|
||||
],
|
||||
"rulesSource": {
|
||||
"kind": "asset",
|
||||
"ref": "ti-cl4/impurity-forecast/config/alert_rules.template.yaml",
|
||||
},
|
||||
"thresholdsSource": {
|
||||
"kind": "asset",
|
||||
"ref": "ti-cl4/impurity-forecast/config/alert_rules.template.yaml",
|
||||
},
|
||||
"showSop": True,
|
||||
"requireAck": True,
|
||||
"ackTimeoutS": 300,
|
||||
"muteLower": "P2",
|
||||
"groupBy": "severity",
|
||||
"sortBy": "severity",
|
||||
"maxItems": 50,
|
||||
}
|
||||
|
||||
|
||||
def _resin_config() -> dict:
|
||||
"""树脂行业模板的等价配置(不同配色 + 内联规则,证明换模板零改码)。"""
|
||||
return {
|
||||
"severityColors": [
|
||||
{"severity": "P0", "fg": "#e63329", "bg": "rgba(230,51,41,0.12)"},
|
||||
{"severity": "P1", "fg": "#ffb000", "bg": "rgba(255,176,0,0.12)"},
|
||||
{"severity": "P2", "fg": "#2bb673", "bg": "rgba(43,182,115,0.10)"},
|
||||
],
|
||||
"rulesSource": {
|
||||
"kind": "inline",
|
||||
"data": [
|
||||
{"id": "resin-temp-high", "severity": "P0"},
|
||||
{"id": "resin-crosslink-low", "severity": "P1"},
|
||||
],
|
||||
},
|
||||
"showSop": False,
|
||||
"requireAck": False,
|
||||
"muteLower": "P1", # 树脂模板只看 P0/P1,静默 P2 提示
|
||||
}
|
||||
|
||||
|
||||
def _check(name: str, fn) -> bool:
|
||||
try:
|
||||
ok = fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"[FAIL] {name}: 抛异常 {exc!r}")
|
||||
return False
|
||||
status = "PASS" if ok else "FAIL"
|
||||
print(f"[{status}] {name}")
|
||||
return bool(ok)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("== 报警看板配置化验收(issue #52 / PRD 5.5)==")
|
||||
all_ok = True
|
||||
|
||||
# 1) Ti 模板资产合法 + 可渲染为 props
|
||||
def check_ti_valid() -> bool:
|
||||
res = validate_alarm_config(_ti_config())
|
||||
if not res.ok:
|
||||
for e in res.errors:
|
||||
print(f" - {e}")
|
||||
return False
|
||||
cfg = load_alarm_config(_ti_config())
|
||||
props = render_alarm_panel_props(cfg)
|
||||
# P0 红色告警配色进入 props;requireAck=True 携带 ackTimeoutS
|
||||
return (
|
||||
props["severityStyles"]["P0"]["fg"] == "#ff3b30"
|
||||
and props["requireAck"] is True
|
||||
and props.get("ackTimeoutS") == 300
|
||||
and props["rulesSource"]["ref"].endswith("alert_rules.template.yaml")
|
||||
)
|
||||
|
||||
all_ok &= _check("Ti 模板配置合法 + 渲染 props 正确", check_ti_valid)
|
||||
|
||||
# 2) 树脂模板换配置 → props 不同,前端代码零改动
|
||||
def check_resin_differs() -> bool:
|
||||
cfg = load_alarm_config(_resin_config())
|
||||
props = render_alarm_panel_props(cfg)
|
||||
# 树脂 P0 用不同红色;内联规则透传 data;requireAck 关闭不带 ackTimeoutS
|
||||
return (
|
||||
props["severityStyles"]["P0"]["fg"] == "#e63329"
|
||||
and props["rulesSource"]["kind"] == "inline"
|
||||
and len(props["rulesSource"]["data"]) == 2
|
||||
and "ackTimeoutS" not in props
|
||||
and props["showSop"] is False
|
||||
)
|
||||
|
||||
all_ok &= _check("树脂模板换配置 → props 随之变化(切换模板零改码)", check_resin_differs)
|
||||
|
||||
# 3) mute_lower 配置点真实驱动展示策略
|
||||
def check_mute_lower() -> bool:
|
||||
alarms = [
|
||||
{"severity": "P2", "id": "a"},
|
||||
{"severity": "P0", "id": "b"},
|
||||
{"severity": "P1", "id": "c"},
|
||||
]
|
||||
keep_all = filter_alarms_by_mute(alarms, "P2")
|
||||
only_p0_p1 = filter_alarms_by_mute(alarms, "P1")
|
||||
# mute=P2 全保留且按严重度降序;mute=P1 过滤掉 P2
|
||||
return (
|
||||
[a["id"] for a in keep_all] == ["b", "c", "a"]
|
||||
and [a["id"] for a in only_p0_p1] == ["b", "c"]
|
||||
)
|
||||
|
||||
all_ok &= _check("muteLower 配置点真实过滤 + 排序告警", check_mute_lower)
|
||||
|
||||
# 4) 负例:破坏的配置被拒绝并聚合多条错误
|
||||
def check_negative() -> bool:
|
||||
bad = {
|
||||
"severityColors": [
|
||||
{"severity": "P0", "fg": "#f00", "bg": "#000"},
|
||||
# 缺 P1 / P2
|
||||
{"severity": "P0", "fg": "#f00", "bg": "#000"}, # 重复 P0
|
||||
{"severity": "P9", "fg": "#f00", "bg": "#000"}, # 非法 severity
|
||||
],
|
||||
"rulesSource": {"kind": "asset"}, # 缺 ref
|
||||
"ackTimeoutS": 0, # 非正整数
|
||||
"sortBy": "color", # 非法排序键
|
||||
"maxItems": 0, # 越界
|
||||
}
|
||||
res = validate_alarm_config(bad)
|
||||
# 应收集到多条错误(聚合而非首条即返)
|
||||
return (not res.ok) and len(res.errors) >= 5
|
||||
|
||||
all_ok &= _check("负例:破坏的配置被拒绝并聚合多条错误", check_negative)
|
||||
|
||||
print("=" * 48)
|
||||
print("结果: " + ("全部通过 ✅" if all_ok else "存在未达标项 ❌"))
|
||||
return 0 if all_ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,338 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""报警看板配置化单元测试(issue #52 / PRD 5.5「⑤ 配置化驾驶舱」)。
|
||||
|
||||
覆盖:
|
||||
1. 合法配置(Ti 模板)→ 校验通过、可解析为 ``AlarmPanelConfig``、序列化往返一致;
|
||||
2. 默认值与字段别名(snake_case / camelCase 都接受)、thresholds_source 选填;
|
||||
3. ``render_alarm_panel_props`` 正确编译 severity 样式 / 规则源 / 确认策略;
|
||||
4. ``filter_alarms_by_mute`` 静默下限 + severity 降序排序;
|
||||
5. 各类非法情况:非对象、错误 $schema、severityColors 缺级/重复/非法、
|
||||
rulesSource 缺失/asset 缺 ref/inline 缺 data、布尔/整数/枚举/区间非法;
|
||||
6. ``load_alarm_config`` 校验失败抛 ``AlarmConfigError`` 并携带全部错误。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import unittest
|
||||
|
||||
from cockpit import ( # type: ignore[import-not-found]
|
||||
ALARM_CONFIG_SCHEMA_ID,
|
||||
DEFAULT_ACK_TIMEOUT_S,
|
||||
DEFAULT_MAX_ITEMS,
|
||||
AlarmConfigError,
|
||||
AlarmPanelConfig,
|
||||
filter_alarms_by_mute,
|
||||
load_alarm_config,
|
||||
render_alarm_panel_props,
|
||||
validate_alarm_config,
|
||||
)
|
||||
|
||||
|
||||
def _valid_config() -> dict:
|
||||
"""返回一份合法的告警面板配置(Ti 模板风格)。"""
|
||||
return {
|
||||
"$schema": ALARM_CONFIG_SCHEMA_ID,
|
||||
"severityColors": [
|
||||
{"severity": "P0", "fg": "#ff3b30", "bg": "rgba(255,59,48,0.12)",
|
||||
"icon": "alert-octagon", "border": "#ff3b30"},
|
||||
{"severity": "P1", "fg": "#f5a623", "bg": "rgba(245,166,35,0.12)"},
|
||||
{"severity": "P2", "fg": "#3aa0ff", "bg": "rgba(58,160,255,0.10)"},
|
||||
],
|
||||
"rulesSource": {"kind": "asset", "ref": "ti-cl4/cfg/alert_rules.yaml"},
|
||||
"showSop": True,
|
||||
"requireAck": True,
|
||||
"ackTimeoutS": 300,
|
||||
"muteLower": "P2",
|
||||
"groupBy": "severity",
|
||||
"sortBy": "severity",
|
||||
"maxItems": 50,
|
||||
}
|
||||
|
||||
|
||||
class ValidateTest(unittest.TestCase):
|
||||
def test_valid_config_passes(self):
|
||||
res = validate_alarm_config(_valid_config())
|
||||
self.assertTrue(res.ok, msg=res.errors)
|
||||
self.assertEqual(res.errors, [])
|
||||
norm = res.normalized
|
||||
assert norm is not None
|
||||
# 规范化:severityColors 按 P0/P1/P2 顺序回填
|
||||
self.assertEqual([c["severity"] for c in norm["severityColors"]], ["P0", "P1", "P2"])
|
||||
# P0 的可选 icon/border 保留
|
||||
self.assertEqual(norm["severityColors"][0]["icon"], "alert-octagon")
|
||||
|
||||
def test_non_dict_rejected(self):
|
||||
res = validate_alarm_config(["not", "a", "dict"])
|
||||
self.assertFalse(res.ok)
|
||||
self.assertIn("对象(dict)", res.errors[0])
|
||||
|
||||
def test_wrong_schema_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["$schema"] = "something-else"
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("$schema" in e for e in res.errors))
|
||||
|
||||
def test_snake_case_aliases_accepted(self):
|
||||
# snake_case 字段名同样接受(向后兼容手写 YAML)
|
||||
cfg = {
|
||||
"severity_colors": [
|
||||
{"severity": "P0", "fg": "#f", "bg": "#0"},
|
||||
{"severity": "P1", "fg": "#f", "bg": "#0"},
|
||||
{"severity": "P2", "fg": "#f", "bg": "#0"},
|
||||
],
|
||||
"rules_source": {"kind": "asset", "ref": "a.yaml"},
|
||||
"show_sop": False,
|
||||
"require_ack": False,
|
||||
"mute_lower": "P2",
|
||||
"group_by": "severity",
|
||||
"sort_by": "severity",
|
||||
"max_items": 10,
|
||||
}
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertTrue(res.ok, msg=res.errors)
|
||||
|
||||
def test_missing_severity_level_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["severityColors"] = cfg["severityColors"][:2] # 只留 P0/P1
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("缺少 P2" in e for e in res.errors))
|
||||
|
||||
def test_duplicate_and_invalid_severity_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["severityColors"] = [
|
||||
{"severity": "P0", "fg": "#f", "bg": "#0"},
|
||||
{"severity": "P0", "fg": "#f", "bg": "#0"}, # 重复
|
||||
{"severity": "P9", "fg": "#f", "bg": "#0"}, # 非法
|
||||
]
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
joined = "; ".join(res.errors)
|
||||
self.assertIn("重复", joined)
|
||||
self.assertIn("P9", joined)
|
||||
|
||||
def test_missing_required_color_key_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["severityColors"][0] = {"severity": "P0", "fg": "#f"} # 缺 bg
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("bg" in e for e in res.errors))
|
||||
|
||||
def test_missing_rules_source_rejected(self):
|
||||
cfg = _valid_config()
|
||||
del cfg["rulesSource"]
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("rulesSource" in e for e in res.errors))
|
||||
|
||||
def test_asset_source_without_ref_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["rulesSource"] = {"kind": "asset"} # 缺 ref
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("ref" in e for e in res.errors))
|
||||
|
||||
def test_inline_source_without_data_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["rulesSource"] = {"kind": "inline"} # 缺 data
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("data" in e for e in res.errors))
|
||||
|
||||
def test_inline_source_item_without_id_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["rulesSource"] = {"kind": "inline", "data": [{"severity": "P0"}]} # 缺 id
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("id" in e for e in res.errors))
|
||||
|
||||
def test_invalid_source_kind_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["rulesSource"] = {"kind": "graphql", "ref": "x"}
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("kind" in e for e in res.errors))
|
||||
|
||||
def test_bool_fields_type_checked(self):
|
||||
for field in ("showSop", "requireAck"):
|
||||
cfg = _valid_config()
|
||||
cfg[field] = "yes"
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok, msg=field)
|
||||
self.assertTrue(any(field in e for e in res.errors), msg=field)
|
||||
|
||||
def test_ack_timeout_must_be_positive_int(self):
|
||||
cfg = _valid_config()
|
||||
cfg["ackTimeoutS"] = 0
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("ackTimeoutS" in e for e in res.errors))
|
||||
# bool 不应被当成 int 接受
|
||||
cfg["ackTimeoutS"] = True
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
|
||||
def test_enum_fields_validated(self):
|
||||
for field, valid, invalid in [
|
||||
("muteLower", ["P0", "P1", "P2"], "P9"),
|
||||
("groupBy", ["severity", "rule", "process"], "color"),
|
||||
("sortBy", ["severity", "time"], "color"),
|
||||
]:
|
||||
for v in valid:
|
||||
cfg = _valid_config()
|
||||
cfg[field] = v
|
||||
# muteLower=P0 合法但会过滤掉 P1/P2,不影响校验合法性
|
||||
self.assertTrue(validate_alarm_config(cfg).ok, msg=f"{field}={v}")
|
||||
cfg = _valid_config()
|
||||
cfg[field] = invalid
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertFalse(res.ok, msg=f"{field}={invalid}")
|
||||
self.assertTrue(any(field in e for e in res.errors), msg=field)
|
||||
|
||||
def test_max_items_range(self):
|
||||
cfg = _valid_config()
|
||||
cfg["maxItems"] = 0
|
||||
self.assertFalse(validate_alarm_config(cfg).ok)
|
||||
cfg["maxItems"] = 501
|
||||
self.assertFalse(validate_alarm_config(cfg).ok)
|
||||
cfg["maxItems"] = 500
|
||||
self.assertTrue(validate_alarm_config(cfg).ok)
|
||||
cfg["maxItems"] = True # bool 不被当成 int
|
||||
self.assertFalse(validate_alarm_config(cfg).ok)
|
||||
|
||||
def test_defaults_applied_when_optional_omitted(self):
|
||||
cfg = {
|
||||
"severityColors": [
|
||||
{"severity": "P0", "fg": "#f", "bg": "#0"},
|
||||
{"severity": "P1", "fg": "#f", "bg": "#0"},
|
||||
{"severity": "P2", "fg": "#f", "bg": "#0"},
|
||||
],
|
||||
"rulesSource": {"kind": "asset", "ref": "a.yaml"},
|
||||
}
|
||||
res = validate_alarm_config(cfg)
|
||||
self.assertTrue(res.ok, msg=res.errors)
|
||||
assert res.normalized is not None
|
||||
self.assertEqual(res.normalized["showSop"], True)
|
||||
self.assertEqual(res.normalized["requireAck"], False)
|
||||
self.assertEqual(res.normalized["ackTimeoutS"], DEFAULT_ACK_TIMEOUT_S)
|
||||
self.assertEqual(res.normalized["muteLower"], "P2")
|
||||
self.assertEqual(res.normalized["groupBy"], "severity")
|
||||
self.assertEqual(res.normalized["sortBy"], "severity")
|
||||
self.assertEqual(res.normalized["maxItems"], DEFAULT_MAX_ITEMS)
|
||||
# thresholds_source 选填,未给出则 normalized 不含它
|
||||
self.assertNotIn("thresholdsSource", res.normalized)
|
||||
|
||||
def test_multiple_errors_aggregated(self):
|
||||
# 一次性破坏多个字段,校验器应聚合多条错误而非首条即返
|
||||
bad = {
|
||||
"severityColors": [{"severity": "P0", "fg": "#f", "bg": "#0"}], # 缺 P1/P2
|
||||
"rulesSource": {"kind": "asset"}, # 缺 ref
|
||||
"ackTimeoutS": -1,
|
||||
"sortBy": "color",
|
||||
}
|
||||
res = validate_alarm_config(bad)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertGreaterEqual(len(res.errors), 4)
|
||||
|
||||
|
||||
class LoadTest(unittest.TestCase):
|
||||
def test_load_valid_returns_model(self):
|
||||
cfg = load_alarm_config(_valid_config())
|
||||
self.assertIsInstance(cfg, AlarmPanelConfig)
|
||||
self.assertEqual(cfg.schema, ALARM_CONFIG_SCHEMA_ID)
|
||||
self.assertEqual(len(cfg.severity_colors), 3)
|
||||
self.assertEqual(cfg.rules_source.kind, "asset")
|
||||
self.assertEqual(cfg.rules_source.ref, "ti-cl4/cfg/alert_rules.yaml")
|
||||
self.assertTrue(cfg.require_ack)
|
||||
|
||||
def test_load_roundtrip(self):
|
||||
original = _valid_config()
|
||||
cfg = load_alarm_config(original)
|
||||
# 内存模型序列化后再次校验仍合法(往返一致)
|
||||
res = validate_alarm_config(cfg.to_dict())
|
||||
self.assertTrue(res.ok, msg=res.errors)
|
||||
|
||||
def test_load_invalid_raises_with_errors(self):
|
||||
bad = copy.deepcopy(_valid_config())
|
||||
del bad["rulesSource"]
|
||||
with self.assertRaises(AlarmConfigError) as cm:
|
||||
load_alarm_config(bad)
|
||||
# 异常携带全部错误清单
|
||||
self.assertGreaterEqual(len(cm.exception.errors), 1)
|
||||
self.assertTrue(any("rulesSource" in e for e in cm.exception.errors))
|
||||
|
||||
|
||||
class RenderPropsTest(unittest.TestCase):
|
||||
def test_props_contain_severity_styles_and_sources(self):
|
||||
cfg = load_alarm_config(_valid_config())
|
||||
props = render_alarm_panel_props(cfg)
|
||||
# 保留 #51 的订阅语义(向后兼容)
|
||||
self.assertEqual(props["subscribe"], "alarm_stream")
|
||||
# severity 样式:P0 红色 + 可选 border
|
||||
self.assertEqual(props["severityStyles"]["P0"]["fg"], "#ff3b30")
|
||||
self.assertEqual(props["severityStyles"]["P0"]["border"], "#ff3b30")
|
||||
# asset 规则源透传 ref
|
||||
self.assertEqual(props["rulesSource"]["kind"], "asset")
|
||||
self.assertTrue(props["rulesSource"]["ref"].endswith("alert_rules.yaml"))
|
||||
# require_ack=True 携带 ackTimeoutS
|
||||
self.assertEqual(props["ackTimeoutS"], 300)
|
||||
self.assertTrue(props["showSop"])
|
||||
|
||||
def test_props_ack_omitted_when_not_required(self):
|
||||
cfg = _valid_config()
|
||||
cfg["requireAck"] = False
|
||||
props = render_alarm_panel_props(load_alarm_config(cfg))
|
||||
self.assertNotIn("ackTimeoutS", props)
|
||||
self.assertFalse(props["requireAck"])
|
||||
|
||||
def test_props_inline_source_data_passed_through(self):
|
||||
cfg = _valid_config()
|
||||
cfg["rulesSource"] = {
|
||||
"kind": "inline",
|
||||
"data": [{"id": "r1", "severity": "P0"}, {"id": "r2", "severity": "P1"}],
|
||||
}
|
||||
props = render_alarm_panel_props(load_alarm_config(cfg))
|
||||
self.assertEqual(props["rulesSource"]["kind"], "inline")
|
||||
self.assertEqual(len(props["rulesSource"]["data"]), 2)
|
||||
|
||||
def test_props_thresholds_source_optional(self):
|
||||
# 未声明 thresholds_source → props 不含该键
|
||||
props = render_alarm_panel_props(load_alarm_config(_valid_config()))
|
||||
self.assertNotIn("thresholdsSource", props)
|
||||
# 声明后 → 透传
|
||||
cfg = _valid_config()
|
||||
cfg["thresholdsSource"] = {"kind": "asset", "ref": "thr.yaml"}
|
||||
props = render_alarm_panel_props(load_alarm_config(cfg))
|
||||
self.assertEqual(props["thresholdsSource"]["ref"], "thr.yaml")
|
||||
|
||||
|
||||
class FilterMuteTest(unittest.TestCase):
|
||||
def test_filter_keeps_above_floor_and_sorts_desc(self):
|
||||
alarms = [
|
||||
{"severity": "P2", "id": "a"},
|
||||
{"severity": "P0", "id": "b"},
|
||||
{"severity": "P1", "id": "c"},
|
||||
]
|
||||
# mute=P2:全保留,按严重度降序
|
||||
kept = filter_alarms_by_mute(alarms, "P2")
|
||||
self.assertEqual([a["id"] for a in kept], ["b", "c", "a"])
|
||||
# mute=P1:滤掉 P2
|
||||
kept = filter_alarms_by_mute(alarms, "P1")
|
||||
self.assertEqual([a["id"] for a in kept], ["b", "c"])
|
||||
# mute=P0:只留 P0
|
||||
kept = filter_alarms_by_mute(alarms, "P0")
|
||||
self.assertEqual([a["id"] for a in kept], ["b"])
|
||||
|
||||
def test_filter_ignores_unknown_severity(self):
|
||||
alarms = [{"severity": "P9", "id": "x"}, {"severity": "P0", "id": "y"}]
|
||||
kept = filter_alarms_by_mute(alarms, "P2")
|
||||
self.assertEqual([a["id"] for a in kept], ["y"])
|
||||
|
||||
def test_filter_invalid_mute_raises(self):
|
||||
with self.assertRaises(AlarmConfigError):
|
||||
filter_alarms_by_mute([], "P9")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,79 @@
|
||||
# 移动端交接班摘要模块(iAOP-Core / shift-handover)
|
||||
|
||||
对齐 PRD **场景C(辅助)** 与 **5.4「④ LLM 网关」**:
|
||||
|
||||
> 交接班 → LLM 汇总本班关键事件/能耗/待办 → 生成交接班报告 → 推送下一班。
|
||||
|
||||
以及 PRD 验收口径:交接班报告生成 ≤ 2 分钟(line 350)、移动端交接班摘要可用(line 284/351)。
|
||||
|
||||
## 模块状态
|
||||
|
||||
| 能力 | Issue | 状态 |
|
||||
| --- | --- | --- |
|
||||
| **移动端交接班摘要生成(NL)** | **#53** | **本分支 feature/issue-53** |
|
||||
|
||||
`#53` 把"本班原始数据 → 移动端交接班摘要"这条链路**模板化、可配置、可测试**:
|
||||
班次数据归一化(`ShiftRecord`)→ 按 `HandoverBriefConfig` 经 LLM(或离线确定性降级)
|
||||
生成摘要 → 编译成移动端只读卡片可直接消费的 props。
|
||||
|
||||
## 设计要点
|
||||
|
||||
- **零运行时依赖**:与 cockpit / data-bus / llm-gateway 一致,只用标准库;LLM 调用以
|
||||
**依赖注入**形式传入(`llm_generate: Callable[[str], str]`),内核不绑定云端 SDK,
|
||||
便于本地闭环与离线降级。
|
||||
- **离线/故障自动降级**:未注入 LLM 或调用失败时回落到 `render_deterministic_brief`
|
||||
(PRD「模型服务故障自动降级」「可用性 ≥ 99.8%」),保证交接班链路不中断。
|
||||
- **声明式 + 强校验**:`validate_handover_config` 收集全部字段级错误(沿用 #50/#52
|
||||
风格),`load_handover_config` 校验失败抛 `HandoverConfigError` 并携带错误清单。
|
||||
- **与未合并分支解耦**:不 import `llm-gateway` 的 `PromptRegistry`;仅按约定的
|
||||
`prompt_template` 名字产出 LLM 输入文本,待 llm-gateway 合入后由调用方注入真正的
|
||||
LLM 生成函数。
|
||||
|
||||
## 配置点(外置为模板资产,切换模板零改码)
|
||||
|
||||
| 配置点 | 字段 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 提示词模板 | `promptTemplate` / `promptVersion` | 绑定 `shift_handover` v1.0.1(current) |
|
||||
| 章节 | `sections` | overview/abnormal/safety/energy/todos |
|
||||
| 展示策略 | `maxEvents` / `maxTodos` / `collapseThreshold` | 移动端折叠与截断 |
|
||||
| 字号 | `fontSize` | sm/md/lg |
|
||||
| 高利害确认 | `requireConfirm` | 默认 false;含 P0/安全事件时内核强制 true |
|
||||
|
||||
## 用法
|
||||
|
||||
```python
|
||||
import sys, types, os
|
||||
# 含连字符目录挂载为 shift_handover 包(同 core/data-bus 的做法)
|
||||
_d = os.path.join("core", "shift-handover")
|
||||
if "shift_handover" not in sys.modules:
|
||||
_p = types.ModuleType("shift_handover"); _p.__path__ = [_d]; sys.modules["shift_handover"] = _p
|
||||
|
||||
from shift_handover.handover import (
|
||||
normalize_shift_record, render_handover_brief, generate_handover_brief,
|
||||
)
|
||||
|
||||
# 1) 班次数据(来自驾驶舱/总线/告警面板聚合)
|
||||
record = normalize_shift_record({
|
||||
"shift": "夜班 2026-08-05 00:00~08:00", "operator": "张工",
|
||||
"overview": "TiCl4 产量 36.2t。",
|
||||
"events": [{"time": "01:20", "title": "炉层温度越上限", "severity": "P1"}],
|
||||
"todos": [{"title": "白班复测 3 层温度", "priority": "high"}],
|
||||
"safety": "注意 3 层高温区巡检。",
|
||||
})
|
||||
|
||||
# 2) 生成摘要(llm_generate=None 时离线降级;注入则用 LLM 输出)
|
||||
summary = generate_handover_brief(record, llm_generate=my_llm_fn)
|
||||
|
||||
# 3) 编译移动端只读卡片 props
|
||||
props = render_handover_brief(record, summary=summary)
|
||||
```
|
||||
|
||||
## 测试与验收
|
||||
|
||||
```bash
|
||||
# 单元测试(在 core/shift-handover 目录下)
|
||||
python -m unittest discover -s tests -v # 32 用例全通过
|
||||
|
||||
# 验收脚本(4 能力点:配置合法 / LLM+降级 / 配置点驱动展示 / ≤2 分钟)
|
||||
python scripts/verify_handover_brief.py
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""iAOP-Core · 交接班摘要模块(shift-handover)—— 对齐 PRD 场景C / 5.4「④ LLM 网关」。
|
||||
|
||||
对外暴露 issue #53「移动端交接班摘要生成(NL)」的能力:把本班关键事件/能耗/待办/
|
||||
异常归一为 ``ShiftRecord``,按模板配置(``HandoverBriefConfig``)经 LLM(或离线
|
||||
确定性降级)生成交接班摘要,并编译成移动端只读卡片可直接消费的 props。
|
||||
|
||||
LLM 以依赖注入形式传入(``llm_generate``),内核不绑定具体云端 SDK;未注入或调用
|
||||
失败时自动降级为 ``render_deterministic_brief``(PRD「模型服务故障自动降级」、
|
||||
「可用性 ≥ 99.8%」),保证离线/降级时交接班链路不中断。
|
||||
|
||||
测试:`python -m unittest discover -s tests -v`(在 core/shift-handover 目录下)。
|
||||
验收:`python scripts/verify_handover_brief.py`。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .handover import ( # noqa: F401
|
||||
DEFAULT_COLLAPSE_THRESHOLD,
|
||||
DEFAULT_MAX_EVENTS,
|
||||
DEFAULT_MAX_TODOS,
|
||||
DEFAULT_PROMPT_TEMPLATE,
|
||||
DEFAULT_PROMPT_VERSION,
|
||||
DEFAULT_REQUIRE_CONFIRM,
|
||||
HANDOVER_CONFIG_SCHEMA_ID,
|
||||
HANDOVER_CONFIG_SCHEMA_VERSION,
|
||||
HANDOVER_GENERATION_BUDGET_MS,
|
||||
MAX_ALLOWED_EVENTS,
|
||||
MAX_ALLOWED_TODOS,
|
||||
VALID_FONT_SIZES,
|
||||
VALID_SECTIONS,
|
||||
HandoverBriefConfig,
|
||||
HandoverConfigError,
|
||||
HandoverConfigValidationResult,
|
||||
ShiftEvent,
|
||||
ShiftRecord,
|
||||
ShiftTodo,
|
||||
build_llm_input,
|
||||
generate_handover_brief,
|
||||
load_handover_config,
|
||||
normalize_shift_record,
|
||||
render_deterministic_brief,
|
||||
render_handover_brief,
|
||||
validate_handover_config,
|
||||
within_generation_budget,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_COLLAPSE_THRESHOLD",
|
||||
"DEFAULT_MAX_EVENTS",
|
||||
"DEFAULT_MAX_TODOS",
|
||||
"DEFAULT_PROMPT_TEMPLATE",
|
||||
"DEFAULT_PROMPT_VERSION",
|
||||
"DEFAULT_REQUIRE_CONFIRM",
|
||||
"HANDOVER_CONFIG_SCHEMA_ID",
|
||||
"HANDOVER_CONFIG_SCHEMA_VERSION",
|
||||
"HANDOVER_GENERATION_BUDGET_MS",
|
||||
"MAX_ALLOWED_EVENTS",
|
||||
"MAX_ALLOWED_TODOS",
|
||||
"VALID_FONT_SIZES",
|
||||
"VALID_SECTIONS",
|
||||
"HandoverBriefConfig",
|
||||
"HandoverConfigError",
|
||||
"HandoverConfigValidationResult",
|
||||
"ShiftEvent",
|
||||
"ShiftRecord",
|
||||
"ShiftTodo",
|
||||
"build_llm_input",
|
||||
"generate_handover_brief",
|
||||
"load_handover_config",
|
||||
"normalize_shift_record",
|
||||
"render_deterministic_brief",
|
||||
"render_handover_brief",
|
||||
"validate_handover_config",
|
||||
"within_generation_budget",
|
||||
]
|
||||
@@ -0,0 +1,685 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""移动端交接班摘要生成(issue #53 / PRD 5.4「④ LLM 网关」+ 场景C「⑤ 配置化驾驶舱」)。
|
||||
|
||||
对应 PRD **场景C(辅助)**:
|
||||
|
||||
交接班 → LLM 汇总本班关键事件/能耗/待办 → 生成交接班报告 → 推送下一班。
|
||||
|
||||
以及 PRD 验收口径:
|
||||
- 「LLM 报警解释/交接班报告/ NL查询可用 …… **交接班报告生成 ≤ 2 分钟**」;
|
||||
- 「驾驶舱按 Ti 布局渲染,**移动端交接班摘要可用**」(PRD line 284/351)。
|
||||
|
||||
本模块把"本班原始数据 → 移动端交接班摘要"这条链路**模板化、可配置、可测试**:
|
||||
|
||||
1. **班次数据归一化**(``ShiftRecord`` / ``normalize_shift_record``):把本班
|
||||
关键事件 / 能耗 / 待办 / 异常告警等异构输入归一为一份内存模型;
|
||||
2. **移动端摘要配置**(``HandoverBriefConfig``):摘要包含哪些章节、移动端
|
||||
展示策略(折叠/字号/最多条数/是否高利害人工确认)、绑定的 LLM 提示词模板名
|
||||
(``shift_handover`` v1.0.1,见 ``core/llm-gateway/config/prompts.template.yaml``);
|
||||
3. **LLM 出参渲染**(``build_llm_input``):把班次数据填入 ``shift_handover``
|
||||
提示词的占位符(``{query}``),产出给 LLM 网关的输入;
|
||||
4. **摘要生成**(``generate_handover_brief``):调用传入的 LLM 生成函数;当
|
||||
未配置 LLM(dry-run / 离线 / 单测)时回落到**确定性模板渲染**,保证:
|
||||
- 离线/降级时仍有可用摘要(PRD「可用性 ≥ 99.8%」「模型服务故障自动降级」);
|
||||
- 单测无需真实 LLM 即可断言结构与耗时(验收线 ≤ 2 分钟);
|
||||
5. **移动端负载编译**(``render_handover_brief``):把摘要 + 班次要点编译成
|
||||
移动端只读卡片可直接消费的 props dict(camelCase、扁平、可 ``json.dumps``)。
|
||||
|
||||
设计要点
|
||||
--------
|
||||
- **零运行时依赖**:与 cockpit / data-bus / llm-gateway 一致,只用标准库;
|
||||
LLM 调用以**依赖注入**形式传入(``llm_generate: Callable[[str], str]``),
|
||||
不在内核里硬编码云端 SDK,便于本地闭环与离线降级。
|
||||
- **声明式 + 强校验**:``validate_handover_config`` 收集全部字段级错误
|
||||
(沿用 #50 / #52 的多错误聚合风格),``load_handover_config`` 校验失败抛
|
||||
``HandoverConfigError`` 并携带错误清单。
|
||||
- **与未合并分支解耦**:不 import ``llm-gateway`` 的 ``PromptRegistry``(其
|
||||
feature 分支尚未合入 main);仅按约定的 ``prompt_template`` 名字产出 LLM
|
||||
输入文本,待 llm-gateway 合入后由调用方注入真正的 LLM 生成函数。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 版本标识(被交接班摘要配置资产的 $schema 引用)
|
||||
# ---------------------------------------------------------------------------
|
||||
HANDOVER_CONFIG_SCHEMA_ID: str = "iAOP-cockpit-handover-brief-v1"
|
||||
HANDOVER_CONFIG_SCHEMA_VERSION: int = 1
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 提示词模板绑定(与 core/llm-gateway/config/prompts.template.yaml 对齐)
|
||||
# ---------------------------------------------------------------------------
|
||||
# PRD 5.4「Prompt 版本管理」:交接班摘要绑定的提示词模板名 + 版本。
|
||||
# prompts.template.yaml 中 shift_handover v1.0.1(current)正文含
|
||||
# 「生产概况/异常事项/安全注意事项」三个章节(v1.0.1 相对 v1.0.0 补充安全章节)。
|
||||
DEFAULT_PROMPT_TEMPLATE: str = "shift_handover"
|
||||
DEFAULT_PROMPT_VERSION: str = "1.0.1"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 移动端展示策略(默认值,可被模板配置资产覆盖)
|
||||
# ---------------------------------------------------------------------------
|
||||
# PRD NFR:移动端只读并发 ≥ 200;交接班摘要是只读卡片,默认折叠次要章节。
|
||||
DEFAULT_MAX_EVENTS: int = 8
|
||||
MAX_ALLOWED_EVENTS: int = 50
|
||||
DEFAULT_MAX_TODOS: int = 5
|
||||
MAX_ALLOWED_TODOS: int = 30
|
||||
|
||||
# 移动端章节折叠阈值:超过该条数则折叠为「展开更多」。
|
||||
DEFAULT_COLLAPSE_THRESHOLD: int = 4
|
||||
|
||||
# 移动端字号档位(与驾驶舱主题档位对齐)。
|
||||
VALID_FONT_SIZES: Tuple[str, ...] = ("sm", "md", "lg")
|
||||
|
||||
# 合法的章节顺序键(与 shift_handover 提示词三章节 + 摘要额外章节对齐)。
|
||||
VALID_SECTIONS: Tuple[str, ...] = (
|
||||
"overview", # 生产概况
|
||||
"abnormal", # 异常事项
|
||||
"safety", # 安全注意事项
|
||||
"energy", # 能耗
|
||||
"todos", # 待办(交下一班)
|
||||
)
|
||||
|
||||
# 高利害标记:交接班摘要通常非高利害(scenarios.template.yaml: high_stakes=false),
|
||||
# 但若本班出现 P0 告警 / 安全事件,可强制 require_confirm=true(PRD 高利害人工确认)。
|
||||
DEFAULT_REQUIRE_CONFIRM: bool = False
|
||||
|
||||
# 验收线:交接班报告生成 ≤ 2 分钟(PRD line 350),单位毫秒。
|
||||
HANDOVER_GENERATION_BUDGET_MS: int = 120_000
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 异常 / 结果
|
||||
# ---------------------------------------------------------------------------
|
||||
class HandoverConfigError(ValueError):
|
||||
"""交接班摘要配置校验失败。``load_handover_config`` 在校验不通过时抛出。
|
||||
|
||||
``errors`` 收集全部字段级错误,沿用 #50 / #52 的多错误聚合风格。
|
||||
"""
|
||||
|
||||
def __init__(self, errors: List[str]):
|
||||
super().__init__(
|
||||
"; ".join(errors) if errors else "handover brief config validation failed"
|
||||
)
|
||||
self.errors: List[str] = list(errors)
|
||||
|
||||
|
||||
@dataclass
|
||||
class HandoverConfigValidationResult:
|
||||
"""``validate_handover_config`` 的返回值。"""
|
||||
|
||||
ok: bool
|
||||
errors: List[str] = field(default_factory=list)
|
||||
normalized: Optional[Dict[str, Any]] = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 班次数据内存模型
|
||||
# ---------------------------------------------------------------------------
|
||||
@dataclass
|
||||
class ShiftEvent:
|
||||
"""本班一条关键事件(告警 / 操作 / 质量波动等)。
|
||||
|
||||
Attributes:
|
||||
time: 事件时间(ISO 字符串或可读文本,如 ``"03:12"``)。
|
||||
title: 事件标题(移动端卡片主文案)。
|
||||
severity: 严重度(``P0`` / ``P1`` / ``P2`` / ``info``;与告警面板对齐)。
|
||||
detail: 可选详情(移动端「展开更多」)。
|
||||
"""
|
||||
|
||||
time: str
|
||||
title: str
|
||||
severity: str = "info"
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ShiftTodo:
|
||||
"""交接给下一班的待办。
|
||||
|
||||
Attributes:
|
||||
title: 待办内容。
|
||||
priority: 优先级(``high`` / ``medium`` / ``low``)。
|
||||
due: 可选截止提示(如 ``"接班后 30min 内"``)。
|
||||
"""
|
||||
|
||||
title: str
|
||||
priority: str = "medium"
|
||||
due: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ShiftRecord:
|
||||
"""一个班次的归一化数据(移动端交接班摘要的输入)。
|
||||
|
||||
所有字段均有合理默认值:哪怕只给 ``shift`` / ``operator`` 也能产出一份
|
||||
可用摘要(降级友好)。
|
||||
|
||||
Attributes:
|
||||
shift: 班次标识(如 ``"夜班 2026-08-05 00:00~08:00"``)。
|
||||
operator: 交班人/值班长。
|
||||
overview: 生产概况自由文本(产量/批次/质量达成等)。
|
||||
events: 关键事件列表(按时间顺序)。
|
||||
todos: 交接待办列表。
|
||||
energy: 能耗小结(自由文本或结构化键值,如 ``"总电耗 12.4 万 kWh"``)。
|
||||
safety: 安全注意事项自由文本。
|
||||
next_shift: 下一班接班人(可选,用于推送)。
|
||||
"""
|
||||
|
||||
shift: str
|
||||
operator: str
|
||||
overview: str = ""
|
||||
events: List[ShiftEvent] = field(default_factory=list)
|
||||
todos: List[ShiftTodo] = field(default_factory=list)
|
||||
energy: str = ""
|
||||
safety: str = ""
|
||||
next_shift: Optional[str] = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 摘要配置内存模型
|
||||
# ---------------------------------------------------------------------------
|
||||
@dataclass
|
||||
class HandoverBriefConfig:
|
||||
"""一份移动端交接班摘要配置(对应一份模板级配置资产)。
|
||||
|
||||
切换行业模板 = 加载另一份 ``HandoverBriefConfig``,移动端卡片代码零改动
|
||||
(与 #52 告警面板配置化同一验收口径)。
|
||||
"""
|
||||
|
||||
prompt_template: str = DEFAULT_PROMPT_TEMPLATE
|
||||
prompt_version: str = DEFAULT_PROMPT_VERSION
|
||||
sections: List[str] = field(
|
||||
default_factory=lambda: list(VALID_SECTIONS)
|
||||
)
|
||||
max_events: int = DEFAULT_MAX_EVENTS
|
||||
max_todos: int = DEFAULT_MAX_TODOS
|
||||
collapse_threshold: int = DEFAULT_COLLAPSE_THRESHOLD
|
||||
font_size: str = "md"
|
||||
require_confirm: bool = DEFAULT_REQUIRE_CONFIRM
|
||||
schema: str = HANDOVER_CONFIG_SCHEMA_ID
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 校验器
|
||||
# ---------------------------------------------------------------------------
|
||||
def _is_str_nonempty(value: Any) -> bool:
|
||||
return isinstance(value, str) and value.strip() != ""
|
||||
|
||||
|
||||
def validate_handover_config(config: Any) -> HandoverConfigValidationResult:
|
||||
"""对一份交接班摘要配置资产做结构 + 语义校验,返回校验结果。
|
||||
|
||||
非法资产不提前返回:尽量收集全部字段级错误,便于配置台一次性展示
|
||||
「错误列表(字段 + 原因)」,与 #50 / #52 行为一致。
|
||||
"""
|
||||
errors: List[str] = []
|
||||
|
||||
if not isinstance(config, dict):
|
||||
return HandoverConfigValidationResult(
|
||||
ok=False,
|
||||
errors=[f"配置必须是对象(dict),实际为 {type(config).__name__}"],
|
||||
)
|
||||
|
||||
# $schema(选填,但若给出必须对齐版本标识)
|
||||
schema = config.get("$schema")
|
||||
if schema is not None and schema != HANDOVER_CONFIG_SCHEMA_ID:
|
||||
errors.append(
|
||||
f"$schema: 应为 {HANDOVER_CONFIG_SCHEMA_ID!r},实际为 {schema!r}"
|
||||
)
|
||||
|
||||
# promptTemplate:非空字符串
|
||||
prompt_template = config.get(
|
||||
"promptTemplate", config.get("prompt_template", DEFAULT_PROMPT_TEMPLATE)
|
||||
)
|
||||
if not _is_str_nonempty(prompt_template):
|
||||
errors.append("promptTemplate: 缺失或非非空字符串")
|
||||
|
||||
# promptVersion:非空字符串(semver 由 llm-gateway 校验,这里只要求非空)
|
||||
prompt_version = config.get(
|
||||
"promptVersion", config.get("prompt_version", DEFAULT_PROMPT_VERSION)
|
||||
)
|
||||
if not _is_str_nonempty(prompt_version):
|
||||
errors.append("promptVersion: 缺失或非非空字符串")
|
||||
|
||||
# sections:列表、每项在 VALID_SECTIONS 内、至少 1 项、无重复
|
||||
raw_sections = config.get("sections", list(VALID_SECTIONS))
|
||||
norm_sections: List[str] = []
|
||||
if not isinstance(raw_sections, list) or not raw_sections:
|
||||
errors.append(
|
||||
f"sections: 缺失或非列表(至少 1 项,合法值 {list(VALID_SECTIONS)})"
|
||||
)
|
||||
else:
|
||||
seen: set = set()
|
||||
for i, s in enumerate(raw_sections):
|
||||
if not _is_str_nonempty(s):
|
||||
errors.append(f"sections[{i}]: 必须是非空字符串")
|
||||
continue
|
||||
if s not in VALID_SECTIONS:
|
||||
errors.append(
|
||||
f"sections[{i}]: 非法 {s!r},合法值 {list(VALID_SECTIONS)}"
|
||||
)
|
||||
continue
|
||||
if s in seen:
|
||||
errors.append(f"sections[{i}]: {s!r} 重复声明")
|
||||
continue
|
||||
seen.add(s)
|
||||
norm_sections.append(s)
|
||||
|
||||
# maxEvents:1..MAX_ALLOWED_EVENTS
|
||||
max_events = config.get("maxEvents", config.get("max_events", DEFAULT_MAX_EVENTS))
|
||||
if (
|
||||
isinstance(max_events, bool)
|
||||
or not isinstance(max_events, int)
|
||||
or not (1 <= max_events <= MAX_ALLOWED_EVENTS)
|
||||
):
|
||||
errors.append(
|
||||
f"maxEvents: 必须是 1..{MAX_ALLOWED_EVENTS} 的整数,实际为 {max_events!r}"
|
||||
)
|
||||
|
||||
# maxTodos:1..MAX_ALLOWED_TODOS
|
||||
max_todos = config.get("maxTodos", config.get("max_todos", DEFAULT_MAX_TODOS))
|
||||
if (
|
||||
isinstance(max_todos, bool)
|
||||
or not isinstance(max_todos, int)
|
||||
or not (1 <= max_todos <= MAX_ALLOWED_TODOS)
|
||||
):
|
||||
errors.append(
|
||||
f"maxTodos: 必须是 1..{MAX_ALLOWED_TODOS} 的整数,实际为 {max_todos!r}"
|
||||
)
|
||||
|
||||
# collapseThreshold:0..max(maxEvents, maxTodos)
|
||||
collapse_threshold = config.get(
|
||||
"collapseThreshold", config.get("collapse_threshold", DEFAULT_COLLAPSE_THRESHOLD)
|
||||
)
|
||||
if (
|
||||
isinstance(collapse_threshold, bool)
|
||||
or not isinstance(collapse_threshold, int)
|
||||
or collapse_threshold < 0
|
||||
):
|
||||
errors.append(
|
||||
f"collapseThreshold: 必须是非负整数,实际为 {collapse_threshold!r}"
|
||||
)
|
||||
|
||||
# fontSize:枚举
|
||||
font_size = config.get("fontSize", config.get("font_size", "md"))
|
||||
if font_size not in VALID_FONT_SIZES:
|
||||
errors.append(
|
||||
f"fontSize: 非法 {font_size!r},合法值 {list(VALID_FONT_SIZES)}"
|
||||
)
|
||||
|
||||
# requireConfirm:布尔
|
||||
require_confirm = config.get(
|
||||
"requireConfirm", config.get("require_confirm", DEFAULT_REQUIRE_CONFIRM)
|
||||
)
|
||||
if not isinstance(require_confirm, bool):
|
||||
errors.append(
|
||||
f"requireConfirm: 必须是布尔,实际为 {type(require_confirm).__name__}"
|
||||
)
|
||||
|
||||
if errors:
|
||||
return HandoverConfigValidationResult(ok=False, errors=errors)
|
||||
|
||||
normalized: Dict[str, Any] = {
|
||||
"$schema": HANDOVER_CONFIG_SCHEMA_ID,
|
||||
"promptTemplate": prompt_template,
|
||||
"promptVersion": prompt_version,
|
||||
"sections": norm_sections or list(VALID_SECTIONS),
|
||||
"maxEvents": max_events,
|
||||
"maxTodos": max_todos,
|
||||
"collapseThreshold": collapse_threshold,
|
||||
"fontSize": font_size,
|
||||
"requireConfirm": require_confirm,
|
||||
}
|
||||
return HandoverConfigValidationResult(ok=True, errors=[], normalized=normalized)
|
||||
|
||||
|
||||
def load_handover_config(config: Any) -> HandoverBriefConfig:
|
||||
"""从已解析的 dict 构造 ``HandoverBriefConfig``(校验失败抛 ``HandoverConfigError``)。
|
||||
|
||||
与 #52 ``load_alarm_config`` 对称:先校验再按规范化结果构造内存模型。
|
||||
"""
|
||||
result = validate_handover_config(config)
|
||||
if not result.ok:
|
||||
raise HandoverConfigError(result.errors)
|
||||
assert result.normalized is not None
|
||||
n = result.normalized
|
||||
return HandoverBriefConfig(
|
||||
prompt_template=n["promptTemplate"],
|
||||
prompt_version=n["promptVersion"],
|
||||
sections=n["sections"],
|
||||
max_events=n["maxEvents"],
|
||||
max_todos=n["maxTodos"],
|
||||
collapse_threshold=n["collapseThreshold"],
|
||||
font_size=n["fontSize"],
|
||||
require_confirm=n["requireConfirm"],
|
||||
schema=HANDOVER_CONFIG_SCHEMA_ID,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 班次数据归一化(从 dict → ShiftRecord)
|
||||
# ---------------------------------------------------------------------------
|
||||
def normalize_shift_record(raw: Any) -> ShiftRecord:
|
||||
"""把一份班次数据 dict 归一为 ``ShiftRecord``。
|
||||
|
||||
用于从驾驶舱 / 总线 / 告警面板聚合出的原始数据(JSON)转入内存模型。
|
||||
宽松解析:缺字段给默认值;非法字段抛 ``HandoverConfigError`` 携带错误清单。
|
||||
"""
|
||||
errors: List[str] = []
|
||||
if not isinstance(raw, dict):
|
||||
raise HandoverConfigError(
|
||||
[f"班次数据必须是对象(dict),实际为 {type(raw).__name__}"]
|
||||
)
|
||||
|
||||
shift = raw.get("shift", "")
|
||||
operator = raw.get("operator", "")
|
||||
if not _is_str_nonempty(shift):
|
||||
errors.append("shift: 缺失或非非空字符串(班次标识必填)")
|
||||
if not _is_str_nonempty(operator):
|
||||
errors.append("operator: 缺失或非非空字符串(交班人必填)")
|
||||
|
||||
events: List[ShiftEvent] = []
|
||||
raw_events = raw.get("events", [])
|
||||
if raw_events is None:
|
||||
raw_events = []
|
||||
if not isinstance(raw_events, list):
|
||||
errors.append("events: 必须是列表")
|
||||
else:
|
||||
for i, e in enumerate(raw_events):
|
||||
if not isinstance(e, dict):
|
||||
errors.append(f"events[{i}]: 必须是对象(dict)")
|
||||
continue
|
||||
t = e.get("time")
|
||||
title = e.get("title")
|
||||
if not _is_str_nonempty(t):
|
||||
errors.append(f"events[{i}].time: 缺失或非非空字符串")
|
||||
continue
|
||||
if not _is_str_nonempty(title):
|
||||
errors.append(f"events[{i}].title: 缺失或非非空字符串")
|
||||
continue
|
||||
events.append(
|
||||
ShiftEvent(
|
||||
time=t,
|
||||
title=title,
|
||||
severity=e.get("severity", "info"),
|
||||
detail=e.get("detail"),
|
||||
)
|
||||
)
|
||||
|
||||
todos: List[ShiftTodo] = []
|
||||
raw_todos = raw.get("todos", [])
|
||||
if raw_todos is None:
|
||||
raw_todos = []
|
||||
if not isinstance(raw_todos, list):
|
||||
errors.append("todos: 必须是列表")
|
||||
else:
|
||||
for i, td in enumerate(raw_todos):
|
||||
if not isinstance(td, dict):
|
||||
errors.append(f"todos[{i}]: 必须是对象(dict)")
|
||||
continue
|
||||
title = td.get("title")
|
||||
if not _is_str_nonempty(title):
|
||||
errors.append(f"todos[{i}].title: 缺失或非非空字符串")
|
||||
continue
|
||||
todos.append(
|
||||
ShiftTodo(
|
||||
title=title,
|
||||
priority=td.get("priority", "medium"),
|
||||
due=td.get("due"),
|
||||
)
|
||||
)
|
||||
|
||||
if errors:
|
||||
raise HandoverConfigError(errors)
|
||||
|
||||
return ShiftRecord(
|
||||
shift=str(shift),
|
||||
operator=str(operator),
|
||||
overview=str(raw.get("overview", "")) or "",
|
||||
events=events,
|
||||
todos=todos,
|
||||
energy=str(raw.get("energy", "")) or "",
|
||||
safety=str(raw.get("safety", "")) or "",
|
||||
next_shift=raw.get("next_shift"),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM 输入渲染(填 shift_handover 提示词占位符)
|
||||
# ---------------------------------------------------------------------------
|
||||
def build_llm_input(
|
||||
record: ShiftRecord,
|
||||
config: Optional[HandoverBriefConfig] = None,
|
||||
) -> Tuple[str, str]:
|
||||
"""把班次数据填入 ``shift_handover`` 提示词,产出给 LLM 网关的输入。
|
||||
|
||||
返回 ``(prompt_template_name, rendered_text)``:
|
||||
- ``prompt_template_name`` 来自配置(默认 ``shift_handover``),调用方据此
|
||||
绑定 llm-gateway 的 ``PromptRegistry`` 版本(PRD「运行时绑定模板版本」);
|
||||
- ``rendered_text`` 是提示词正文(占位符 ``{query}`` 已替换为本班结构化摘要)。
|
||||
|
||||
与 prompts.template.yaml 中 ``shift_handover v1.0.1`` 正文
|
||||
(「生成交接班摘要,包含:生产概况、异常事项、安全注意事项。班次:{query}」)
|
||||
对齐:把结构化班次数据序列化为 ``{query}`` 占位的班次文本。
|
||||
"""
|
||||
if config is None:
|
||||
config = HandoverBriefConfig()
|
||||
|
||||
# 班次结构化摘要文本(作为 {query} 的填充)
|
||||
parts: List[str] = [f"班次:{record.shift}", f"交班人:{record.operator}"]
|
||||
if record.overview:
|
||||
parts.append(f"生产概况:{record.overview}")
|
||||
if record.events:
|
||||
lines = ["关键事件:"]
|
||||
for e in record.events:
|
||||
tag = f"[{e.severity}]" if e.severity and e.severity != "info" else ""
|
||||
line = f"- {e.time} {tag} {e.title}".rstrip()
|
||||
if e.detail:
|
||||
line += f"({e.detail})"
|
||||
lines.append(line)
|
||||
parts.append("\n".join(lines))
|
||||
if record.energy:
|
||||
parts.append(f"能耗:{record.energy}")
|
||||
if record.safety:
|
||||
parts.append(f"安全注意事项:{record.safety}")
|
||||
if record.todos:
|
||||
lines = ["待办(交下一班):"]
|
||||
for td in record.todos:
|
||||
line = f"- [{td.priority}] {td.title}"
|
||||
if td.due:
|
||||
line += f"({td.due})"
|
||||
lines.append(line)
|
||||
parts.append("\n".join(lines))
|
||||
|
||||
query = "\n".join(parts)
|
||||
# shift_handover 提示词正文:生成交接班摘要,包含:生产概况、异常事项、安全注意事项。班次:{query}
|
||||
rendered = (
|
||||
"生成交接班摘要,包含:生产概况、异常事项、安全注意事项。班次:\n" + query
|
||||
)
|
||||
return config.prompt_template, rendered
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 确定性降级渲染(无 LLM 时的离线摘要)
|
||||
# ---------------------------------------------------------------------------
|
||||
def render_deterministic_brief(
|
||||
record: ShiftRecord,
|
||||
config: Optional[HandoverBriefConfig] = None,
|
||||
) -> str:
|
||||
"""无 LLM(dry-run / 离线 / LLM 故障降级)时的确定性交接班摘要。
|
||||
|
||||
PRD NFR「可用性 ≥ 99.8%」「模型服务故障自动降级」:当 LLM 网关不可用时,
|
||||
交接班摘要链路不能中断,回落到基于班次数据的模板拼接摘要。输出与
|
||||
``shift_handover`` 提示词三章节(生产概况/异常事项/安全注意事项)结构对齐,
|
||||
额外补充能耗与待办章节。
|
||||
"""
|
||||
if config is None:
|
||||
config = HandoverBriefConfig()
|
||||
|
||||
sections = config.sections
|
||||
blocks: List[str] = [f"# {record.shift} 交接班摘要", f"交班人:{record.operator}"]
|
||||
|
||||
def _add(title: str, body: str) -> None:
|
||||
if body and body.strip():
|
||||
blocks.append(f"\n## {title}\n{body.strip()}")
|
||||
|
||||
if "overview" in sections:
|
||||
_add("生产概况", record.overview or "(本班生产平稳,无显著波动)")
|
||||
if "abnormal" in sections:
|
||||
if record.events:
|
||||
lines = []
|
||||
for e in record.events:
|
||||
tag = f"[{e.severity}]" if e.severity and e.severity != "info" else ""
|
||||
line = f"- {e.time} {tag} {e.title}".rstrip()
|
||||
if e.detail:
|
||||
line += f"({e.detail})"
|
||||
lines.append(line)
|
||||
_add("异常事项", "\n".join(lines))
|
||||
else:
|
||||
_add("异常事项", "本班无关键异常事件。")
|
||||
if "safety" in sections:
|
||||
_add("安全注意事项", record.safety or "无特殊安全注意事项。")
|
||||
if "energy" in sections:
|
||||
_add("能耗", record.energy or "(未填报能耗数据)")
|
||||
if "todos" in sections:
|
||||
if record.todos:
|
||||
lines = [
|
||||
f"- [{td.priority}] {td.title}" + (f"({td.due})" if td.due else "")
|
||||
for td in record.todos
|
||||
]
|
||||
_add("待办(交下一班)", "\n".join(lines))
|
||||
else:
|
||||
_add("待办(交下一班)", "无待办事项。")
|
||||
|
||||
return "\n".join(blocks)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 摘要生成主入口(注入 LLM,离线自动降级)
|
||||
# ---------------------------------------------------------------------------
|
||||
def generate_handover_brief(
|
||||
record: ShiftRecord,
|
||||
config: Optional[HandoverBriefConfig] = None,
|
||||
llm_generate: Optional[Callable[[str], str]] = None,
|
||||
) -> str:
|
||||
"""生成交接班摘要文本(PRD 场景C,验收线 ≤ 2 分钟)。
|
||||
|
||||
Args:
|
||||
record: 归一化班次数据。
|
||||
config: 摘要配置(章节/移动端策略/提示词模板);None 用默认。
|
||||
llm_generate: LLM 生成函数(输入提示词文本,返回摘要文本)。None 或
|
||||
调用失败时**自动降级**为 ``render_deterministic_brief``(离线可用)。
|
||||
|
||||
Returns:
|
||||
交接班摘要文本(含生产概况/异常事项/安全注意事项等章节)。
|
||||
|
||||
设计:LLM 以依赖注入传入,内核不绑定具体云端 SDK,保证本地闭环与离线降级。
|
||||
"""
|
||||
if config is None:
|
||||
config = HandoverBriefConfig()
|
||||
|
||||
if llm_generate is None:
|
||||
return render_deterministic_brief(record, config)
|
||||
|
||||
_, rendered = build_llm_input(record, config)
|
||||
try:
|
||||
text = llm_generate(rendered)
|
||||
except Exception:
|
||||
# LLM 故障 → 降级为确定性摘要(PRD「模型服务故障自动降级」)
|
||||
return render_deterministic_brief(record, config)
|
||||
|
||||
if not _is_str_nonempty(text):
|
||||
return render_deterministic_brief(record, config)
|
||||
return text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 移动端负载编译(摘要 + 班次要点 → 移动端只读卡片 props)
|
||||
# ---------------------------------------------------------------------------
|
||||
def render_handover_brief(
|
||||
record: ShiftRecord,
|
||||
config: Optional[HandoverBriefConfig] = None,
|
||||
summary: Optional[str] = None,
|
||||
llm_generate: Optional[Callable[[str], str]] = None,
|
||||
generated_at: Optional[datetime] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""把班次数据 + 摘要编译成移动端只读卡片可直接消费的 props dict。
|
||||
|
||||
Args:
|
||||
record: 班次数据。
|
||||
config: 摘要配置;None 用默认。
|
||||
summary: 已生成的摘要文本;None 则调用 ``generate_handover_brief`` 生成。
|
||||
llm_generate: 透传给 ``generate_handover_brief``(None 时离线降级)。
|
||||
generated_at: 摘要生成时间(用于卡片时间戳);None 取当前 UTC。
|
||||
|
||||
Returns:
|
||||
扁平、camelCase、可 ``json.dumps`` 的 props dict,移动端 ``HandoverBrief``
|
||||
组件据此渲染标题/章节/事件/待办/折叠策略/字号(**切换行业模板只换配置资产,
|
||||
移动端代码零改动**,与 #52 同一验收口径)。
|
||||
"""
|
||||
if config is None:
|
||||
config = HandoverBriefConfig()
|
||||
|
||||
if summary is None:
|
||||
summary = generate_handover_brief(record, config, llm_generate)
|
||||
|
||||
if generated_at is None:
|
||||
generated_at = datetime.now(timezone.utc)
|
||||
|
||||
# 按 maxEvents / maxTodos 截断,移动端展示策略由配置驱动
|
||||
truncated_events = record.events[: config.max_events]
|
||||
truncated_todos = record.todos[: config.max_todos]
|
||||
|
||||
# 是否含 P0 / safety 事件 → 强制 requireConfirm(PRD 高利害人工确认)
|
||||
has_critical = any(e.severity == "P0" for e in record.events) or bool(
|
||||
record.safety and record.safety.strip()
|
||||
)
|
||||
require_confirm = config.require_confirm or has_critical
|
||||
|
||||
props: Dict[str, Any] = {
|
||||
"schema": config.schema,
|
||||
"shift": record.shift,
|
||||
"operator": record.operator,
|
||||
"nextShift": record.next_shift,
|
||||
"summary": summary,
|
||||
"generatedAt": generated_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"promptTemplate": config.prompt_template,
|
||||
"promptVersion": config.prompt_version,
|
||||
"sections": list(config.sections),
|
||||
"events": [
|
||||
{
|
||||
"time": e.time,
|
||||
"title": e.title,
|
||||
"severity": e.severity,
|
||||
"detail": e.detail,
|
||||
}
|
||||
for e in truncated_events
|
||||
],
|
||||
"todos": [
|
||||
{"title": t.title, "priority": t.priority, "due": t.due}
|
||||
for t in truncated_todos
|
||||
],
|
||||
"eventOverflow": max(0, len(record.events) - config.max_events),
|
||||
"todoOverflow": max(0, len(record.todos) - config.max_todos),
|
||||
"collapseThreshold": config.collapse_threshold,
|
||||
"fontSize": config.font_size,
|
||||
"requireConfirm": require_confirm,
|
||||
# 演示「配置点真实驱动展示」:章节开关决定卡片渲染哪些区块
|
||||
"showOverview": "overview" in config.sections,
|
||||
"showAbnormal": "abnormal" in config.sections,
|
||||
"showSafety": "safety" in config.sections,
|
||||
"showEnergy": "energy" in config.sections,
|
||||
"showTodos": "todos" in config.sections,
|
||||
}
|
||||
return props
|
||||
|
||||
|
||||
def within_generation_budget(elapsed_ms: float) -> bool:
|
||||
"""判断本次摘要生成是否满足 PRD 验收线「交接班报告生成 ≤ 2 分钟」。
|
||||
|
||||
供验收脚本断言耗时用。
|
||||
"""
|
||||
return elapsed_ms <= HANDOVER_GENERATION_BUDGET_MS
|
||||
@@ -0,0 +1,208 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""移动端交接班摘要验收脚本(issue #53,PRD 场景C 验收口径)。
|
||||
|
||||
验证四个能力点(覆盖 PRD「交接班报告生成 ≤ 2 分钟」「移动端交接班摘要可用」):
|
||||
1. **Ti 行业模板配置资产合法**:交接班摘要配置通过 ``iAOP-cockpit-handover-brief-v1``
|
||||
校验,并能构造 ``HandoverBriefConfig``;
|
||||
2. **LLM 注入生成 + 离线降级**:注入 LLM 时用其输出;LLM 故障/未注入时自动降级为
|
||||
确定性摘要(PRD「模型服务故障自动降级」「可用性 ≥ 99.8%」),且降级摘要含
|
||||
「生产概况/异常事项/安全注意事项」三章节(对齐 shift_handover 提示词);
|
||||
3. **配置点真实驱动展示**:``sections`` / ``maxEvents`` / ``requireConfirm`` 配置项
|
||||
改变 → 移动端 props 随之变化(切换模板零改码,与 #52 同一验收口径);含 P0 事件
|
||||
→ ``requireConfirm`` 被强制为 true(PRD 高利害人工确认);
|
||||
4. **生成耗时达标**:确定性降级路径在 2 分钟验收线内(PRD line 350)。
|
||||
|
||||
用法(在 core/shift-handover 目录下):
|
||||
python scripts/verify_handover_brief.py
|
||||
退出码:0 = 全部通过;1 = 存在未达标项。
|
||||
|
||||
说明:本脚本不依赖 PyYAML(保持零运行时依赖),用与 Ti 模板资产等价的 dict 校验。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
# 本脚本位于 core/shift-handover/scripts/,需把 core/ 加入 sys.path
|
||||
sys.path.insert(
|
||||
0,
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||
)
|
||||
|
||||
# 含连字符的目录无法直接以包名 import:挂载为 shift_handover 后导入子模块
|
||||
import types # noqa: E402
|
||||
|
||||
_SHIFT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if "shift_handover" not in sys.modules:
|
||||
_pkg = types.ModuleType("shift_handover")
|
||||
_pkg.__path__ = [_SHIFT_DIR]
|
||||
sys.modules["shift_handover"] = _pkg
|
||||
|
||||
from shift_handover.handover import ( # noqa: E402
|
||||
HANDOVER_CONFIG_SCHEMA_ID,
|
||||
HANDOVER_GENERATION_BUDGET_MS,
|
||||
HandoverBriefConfig,
|
||||
generate_handover_brief,
|
||||
load_handover_config,
|
||||
normalize_shift_record,
|
||||
render_handover_brief,
|
||||
within_generation_budget,
|
||||
)
|
||||
|
||||
|
||||
def _ti_config() -> dict:
|
||||
"""与 templates/ti-cl4/dashboard/handover_brief.ti.yaml 等价的 dict。"""
|
||||
return {
|
||||
"$schema": HANDOVER_CONFIG_SCHEMA_ID,
|
||||
"promptTemplate": "shift_handover",
|
||||
"promptVersion": "1.0.1",
|
||||
"sections": ["overview", "abnormal", "safety", "energy", "todos"],
|
||||
"maxEvents": 8,
|
||||
"maxTodos": 5,
|
||||
"collapseThreshold": 4,
|
||||
"fontSize": "md",
|
||||
"requireConfirm": False,
|
||||
}
|
||||
|
||||
|
||||
def _ti_shift_record() -> dict:
|
||||
"""Ti 氯化车间夜班典型班次数据。"""
|
||||
return {
|
||||
"shift": "夜班 2026-08-05 00:00~08:00",
|
||||
"operator": "张工",
|
||||
"overview": "TiCl4 产量 36.2t,质量达成率 98.6%。",
|
||||
"events": [
|
||||
{"time": "01:20", "title": "炉层温度越上限",
|
||||
"severity": "P1", "detail": "CLF-01 第3层 942℃,已调风量回落"},
|
||||
{"time": "03:05", "title": "夜巡正常", "severity": "info"},
|
||||
],
|
||||
"todos": [
|
||||
{"title": "白班复测 3 层温度趋势", "priority": "high", "due": "接班后 1h"},
|
||||
{"title": "补录 LIMS 03:00 批次", "priority": "medium"},
|
||||
],
|
||||
"energy": "总电耗 12.4 万 kWh",
|
||||
"safety": "夜班无安全事件;注意 3 层高温区巡检。",
|
||||
"next_shift": "李工",
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
all_ok = True
|
||||
|
||||
def _check(title: str, fn):
|
||||
nonlocal all_ok
|
||||
try:
|
||||
ok = fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
ok = False
|
||||
print(f" ✗ {title}:异常 {exc!r}")
|
||||
status = "✅" if ok else "❌"
|
||||
print(f" {status} {title}")
|
||||
all_ok = all_ok and ok
|
||||
|
||||
print("=" * 64)
|
||||
print("移动端交接班摘要验收(issue #53 / PRD 场景C)")
|
||||
print("=" * 64)
|
||||
|
||||
# 1) Ti 模板配置资产合法
|
||||
def check_config_valid() -> bool:
|
||||
cfg = load_handover_config(_ti_config())
|
||||
return (
|
||||
isinstance(cfg, HandoverBriefConfig)
|
||||
and cfg.prompt_template == "shift_handover"
|
||||
and cfg.prompt_version == "1.0.1"
|
||||
and cfg.font_size == "md"
|
||||
)
|
||||
|
||||
_check("Ti 模板配置资产合法(iAOP-cockpit-handover-brief-v1)", check_config_valid)
|
||||
|
||||
# 2) LLM 注入生成 + 离线降级
|
||||
def check_llm_and_fallback() -> bool:
|
||||
rec = normalize_shift_record(_ti_shift_record())
|
||||
# 注入 LLM:用其输出
|
||||
def llm(prompt: str) -> str:
|
||||
return "【LLM 摘要】本班平稳,3 层温度曾越限已处置,交白班复测。"
|
||||
with_llm = generate_handover_brief(rec, llm_generate=llm)
|
||||
# 离线降级(不注入 LLM)
|
||||
fallback = generate_handover_brief(rec)
|
||||
# LLM 故障降级
|
||||
def broken(prompt: str) -> str:
|
||||
raise RuntimeError("LLM 网关不可达")
|
||||
degraded = generate_handover_brief(rec, llm_generate=broken)
|
||||
return (
|
||||
with_llm.startswith("【LLM 摘要】")
|
||||
and "交接班摘要" in fallback
|
||||
and "生产概况" in fallback
|
||||
and "异常事项" in fallback
|
||||
and "安全注意事项" in fallback
|
||||
and "交接班摘要" in degraded # 故障也降级为可用摘要
|
||||
)
|
||||
|
||||
_check("LLM 注入生成 + 离线/故障降级为可用摘要", check_llm_and_fallback)
|
||||
|
||||
# 3) 配置点真实驱动移动端展示
|
||||
def check_config_drives_props() -> bool:
|
||||
rec = normalize_shift_record(_ti_shift_record())
|
||||
props = render_handover_brief(rec)
|
||||
# 默认配置下事件/待办齐全、章节开关正确
|
||||
base_ok = (
|
||||
len(props["events"]) == 2
|
||||
and len(props["todos"]) == 2
|
||||
and props["showOverview"] is True
|
||||
and props["showAbnormal"] is True
|
||||
and props["eventOverflow"] == 0
|
||||
)
|
||||
# sections 收窄 → 对应章节开关关闭
|
||||
cfg2 = HandoverBriefConfig(sections=["overview"])
|
||||
props2 = render_handover_brief(rec, cfg2)
|
||||
sections_ok = (
|
||||
props2["showOverview"] is True
|
||||
and props2["showAbnormal"] is False
|
||||
and props2["showTodos"] is False
|
||||
)
|
||||
# maxEvents 截断 + 溢出计数
|
||||
many = {
|
||||
"shift": "夜班", "operator": "张工",
|
||||
"events": [{"time": f"0{i}:00", "title": f"事件{i}"} for i in range(12)],
|
||||
}
|
||||
rec_many = normalize_shift_record(many)
|
||||
cfg3 = HandoverBriefConfig(max_events=5)
|
||||
props3 = render_handover_brief(rec_many, cfg3)
|
||||
trunc_ok = len(props3["events"]) == 5 and props3["eventOverflow"] == 7
|
||||
# 含 P0 事件 → requireConfirm 被强制为 true
|
||||
critical = {
|
||||
"shift": "夜班", "operator": "张工",
|
||||
"events": [{"time": "01:00", "title": "严重告警", "severity": "P0"}],
|
||||
}
|
||||
rec_crit = normalize_shift_record(critical)
|
||||
props4 = render_handover_brief(rec_crit, HandoverBriefConfig(require_confirm=False))
|
||||
crit_ok = props4["requireConfirm"] is True
|
||||
return base_ok and sections_ok and trunc_ok and crit_ok
|
||||
|
||||
_check("配置点(sections/maxEvents/requireConfirm)真实驱动移动端展示", check_config_drives_props)
|
||||
|
||||
# 4) 生成耗时达标(≤ 2 分钟验收线)
|
||||
def check_generation_budget() -> bool:
|
||||
rec = normalize_shift_record(_ti_shift_record())
|
||||
start = time.perf_counter()
|
||||
for _ in range(50):
|
||||
generate_handover_brief(rec) # 离线降级路径
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000.0
|
||||
# 单次远小于预算(取平均更稳),且预算判定函数正确
|
||||
per_call = elapsed_ms / 50.0
|
||||
return (
|
||||
per_call < HANDOVER_GENERATION_BUDGET_MS
|
||||
and within_generation_budget(per_call)
|
||||
and not within_generation_budget(HANDOVER_GENERATION_BUDGET_MS + 1)
|
||||
)
|
||||
|
||||
_check("生成耗时达标(PRD:交接班报告生成 ≤ 2 分钟)", check_generation_budget)
|
||||
|
||||
print("=" * 64)
|
||||
print("结果: " + ("全部通过 ✅" if all_ok else "存在未达标项 ❌"))
|
||||
return 0 if all_ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""测试引导:把 `core/shift-handover` 以包名 `shift_handover` 挂载到 sys.modules。
|
||||
|
||||
目录名 `shift-handover` 含连字符,无法直接以包名 import;挂载后模块内相对导入
|
||||
(`from .handover import ...`)在 unittest 发现机制下可正常解析。
|
||||
(沿用 core/data-bus/tests/_bootstrap.py 的同一做法。)
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
|
||||
SHIFT_HANDOVER_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, SHIFT_HANDOVER_DIR)
|
||||
if "shift_handover" not in sys.modules:
|
||||
pkg = types.ModuleType("shift_handover")
|
||||
pkg.__path__ = [SHIFT_HANDOVER_DIR]
|
||||
sys.modules["shift_handover"] = pkg
|
||||
@@ -0,0 +1,400 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""移动端交接班摘要生成单元测试(issue #53 / PRD 场景C / 5.4「④ LLM 网关」)。
|
||||
|
||||
覆盖:
|
||||
1. 配置校验:合法配置通过、默认值与字段别名、sections 去重与枚举校验、
|
||||
maxEvents/maxTodos/collapseThreshold/fontSize/requireConfirm 各类非法情况;
|
||||
2. ``load_handover_config`` 校验失败抛 ``HandoverConfigError`` 并携带全部错误;
|
||||
3. ``normalize_shift_record``:合法 dict → ShiftRecord;缺必填/非法结构被拒;
|
||||
4. ``build_llm_input``:占位符填充正确、含班次/事件/能耗/待办;
|
||||
5. ``render_deterministic_brief``:章节与配置 sections 联动;
|
||||
6. ``generate_handover_brief``:注入 LLM 用其输出;LLM 抛异常/返回空 → 自动降级;
|
||||
7. ``render_handover_brief``:props 结构正确、截断/溢出计数/高利害强制确认;
|
||||
8. ``within_generation_budget``:2 分钟验收线判定。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import _bootstrap # noqa: F401 把 core/shift-handover 挂载为 shift_handover 包
|
||||
|
||||
from shift_handover.handover import ( # type: ignore[import-not-found]
|
||||
DEFAULT_PROMPT_TEMPLATE,
|
||||
DEFAULT_PROMPT_VERSION,
|
||||
HANDOVER_CONFIG_SCHEMA_ID,
|
||||
HANDOVER_GENERATION_BUDGET_MS,
|
||||
HandoverBriefConfig,
|
||||
HandoverConfigError,
|
||||
HandoverConfigValidationResult,
|
||||
ShiftEvent,
|
||||
ShiftRecord,
|
||||
ShiftTodo,
|
||||
build_llm_input,
|
||||
generate_handover_brief,
|
||||
load_handover_config,
|
||||
normalize_shift_record,
|
||||
render_deterministic_brief,
|
||||
render_handover_brief,
|
||||
validate_handover_config,
|
||||
within_generation_budget,
|
||||
)
|
||||
|
||||
|
||||
def _valid_config() -> dict:
|
||||
"""返回一份合法的交接班摘要配置(Ti 模板风格)。"""
|
||||
return {
|
||||
"$schema": HANDOVER_CONFIG_SCHEMA_ID,
|
||||
"promptTemplate": "shift_handover",
|
||||
"promptVersion": "1.0.1",
|
||||
"sections": ["overview", "abnormal", "safety", "energy", "todos"],
|
||||
"maxEvents": 8,
|
||||
"maxTodos": 5,
|
||||
"collapseThreshold": 4,
|
||||
"fontSize": "md",
|
||||
"requireConfirm": False,
|
||||
}
|
||||
|
||||
|
||||
def _full_record_dict() -> dict:
|
||||
return {
|
||||
"shift": "夜班 2026-08-05 00:00~08:00",
|
||||
"operator": "张工",
|
||||
"overview": "TiCl4 产量 36.2t,质量达成率 98.6%。",
|
||||
"events": [
|
||||
{"time": "01:20", "title": "炉层温度越上限", "severity": "P1",
|
||||
"detail": "CLF-01 第3层 942℃ → 已调风量"},
|
||||
{"time": "03:05", "title": "夜巡正常", "severity": "info"},
|
||||
],
|
||||
"todos": [
|
||||
{"title": "白班复测 3 层温度趋势", "priority": "high", "due": "接班后 1h"},
|
||||
{"title": "补录 LIMS 03:00 批次", "priority": "medium"},
|
||||
],
|
||||
"energy": "总电耗 12.4 万 kWh",
|
||||
"safety": "夜班无安全事件;注意 3 层高温区巡检。",
|
||||
"next_shift": "李工",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1) 配置校验
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestValidateConfig(unittest.TestCase):
|
||||
def test_valid_config_passes(self):
|
||||
res = validate_handover_config(_valid_config())
|
||||
self.assertTrue(res.ok, msg=res.errors)
|
||||
self.assertEqual(res.errors, [])
|
||||
self.assertEqual(res.normalized["$schema"], HANDOVER_CONFIG_SCHEMA_ID)
|
||||
|
||||
def test_defaults_and_aliases(self):
|
||||
# snake_case 与 camelCase 都接受;缺省给默认值
|
||||
cfg = {"prompt_template": "shift_handover", "prompt_version": "1.0.0"}
|
||||
res = validate_handover_config(cfg)
|
||||
self.assertTrue(res.ok, msg=res.errors)
|
||||
n = res.normalized
|
||||
self.assertEqual(n["maxEvents"], 8)
|
||||
self.assertEqual(n["maxTodos"], 5)
|
||||
self.assertEqual(n["fontSize"], "md")
|
||||
self.assertEqual(n["collapseThreshold"], 4)
|
||||
self.assertFalse(n["requireConfirm"])
|
||||
# sections 默认为全部合法章节
|
||||
self.assertEqual(
|
||||
n["sections"],
|
||||
["overview", "abnormal", "safety", "energy", "todos"],
|
||||
)
|
||||
|
||||
def test_wrong_schema_rejected(self):
|
||||
cfg = _valid_config()
|
||||
cfg["$schema"] = "something-else"
|
||||
res = validate_handover_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertTrue(any("$schema" in e for e in res.errors))
|
||||
|
||||
def test_non_dict_rejected(self):
|
||||
res = validate_handover_config(["not", "a", "dict"])
|
||||
self.assertFalse(res.ok)
|
||||
self.assertEqual(len(res.errors), 1)
|
||||
|
||||
def test_sections_validation(self):
|
||||
# 非法章节、重复、空列表、非列表
|
||||
cases = [
|
||||
(["overview", "unknown"], "非法枚举"),
|
||||
(["overview", "overview"], "重复"),
|
||||
([], "空列表"),
|
||||
("not-a-list", "非列表"),
|
||||
]
|
||||
for bad_sections, hint in cases:
|
||||
cfg = _valid_config()
|
||||
cfg["sections"] = bad_sections
|
||||
res = validate_handover_config(cfg)
|
||||
self.assertFalse(res.ok, msg=f"{hint} 应被拒绝: {res.errors}")
|
||||
|
||||
def test_numeric_bounds(self):
|
||||
for field, bad in [
|
||||
("maxEvents", 0), ("maxEvents", 51), ("maxEvents", True),
|
||||
("maxTodos", 0), ("maxTodos", 31), ("maxTodos", "5"),
|
||||
("collapseThreshold", -1), ("collapseThreshold", True),
|
||||
]:
|
||||
cfg = _valid_config()
|
||||
cfg[field] = bad
|
||||
res = validate_handover_config(cfg)
|
||||
self.assertFalse(res.ok, msg=f"{field}={bad!r} 应被拒绝: {res.errors}")
|
||||
|
||||
def test_font_size_enum(self):
|
||||
cfg = _valid_config()
|
||||
cfg["fontSize"] = "xl"
|
||||
res = validate_handover_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
|
||||
def test_require_confirm_type(self):
|
||||
cfg = _valid_config()
|
||||
cfg["requireConfirm"] = "yes"
|
||||
res = validate_handover_config(cfg)
|
||||
self.assertFalse(res.ok)
|
||||
|
||||
def test_aggregates_multiple_errors(self):
|
||||
bad = {
|
||||
"promptTemplate": "",
|
||||
"sections": ["oops"],
|
||||
"maxEvents": 0,
|
||||
"fontSize": "xxl",
|
||||
"requireConfirm": 1,
|
||||
}
|
||||
res = validate_handover_config(bad)
|
||||
self.assertFalse(res.ok)
|
||||
# 至少 5 条字段级错误被聚合
|
||||
self.assertGreaterEqual(len(res.errors), 5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2) load_handover_config
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestLoadConfig(unittest.TestCase):
|
||||
def test_load_valid(self):
|
||||
cfg = load_handover_config(_valid_config())
|
||||
self.assertIsInstance(cfg, HandoverBriefConfig)
|
||||
self.assertEqual(cfg.prompt_template, "shift_handover")
|
||||
self.assertEqual(cfg.prompt_version, "1.0.1")
|
||||
self.assertEqual(cfg.font_size, "md")
|
||||
|
||||
def test_load_invalid_raises_with_errors(self):
|
||||
with self.assertRaises(HandoverConfigError) as ctx:
|
||||
load_handover_config({"promptTemplate": "", "maxEvents": 0})
|
||||
# 异常携带错误清单
|
||||
self.assertGreaterEqual(len(ctx.exception.errors), 2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3) normalize_shift_record
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestNormalizeRecord(unittest.TestCase):
|
||||
def test_full_record(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
self.assertIsInstance(rec, ShiftRecord)
|
||||
self.assertEqual(rec.shift, "夜班 2026-08-05 00:00~08:00")
|
||||
self.assertEqual(rec.operator, "张工")
|
||||
self.assertEqual(len(rec.events), 2)
|
||||
self.assertEqual(rec.events[0].severity, "P1")
|
||||
self.assertEqual(rec.todos[0].priority, "high")
|
||||
self.assertEqual(rec.next_shift, "李工")
|
||||
|
||||
def test_minimal_record(self):
|
||||
rec = normalize_shift_record({"shift": "白班", "operator": "王五"})
|
||||
self.assertEqual(rec.events, [])
|
||||
self.assertEqual(rec.todos, [])
|
||||
self.assertEqual(rec.overview, "")
|
||||
|
||||
def test_missing_required_rejected(self):
|
||||
with self.assertRaises(HandoverConfigError):
|
||||
normalize_shift_record({"shift": "白班"}) # 缺 operator
|
||||
|
||||
def test_bad_event_rejected(self):
|
||||
raw = _full_record_dict()
|
||||
raw["events"][0] = {"time": "01:00"} # 缺 title
|
||||
with self.assertRaises(HandoverConfigError):
|
||||
normalize_shift_record(raw)
|
||||
|
||||
def test_bad_todo_rejected(self):
|
||||
raw = _full_record_dict()
|
||||
raw["todos"] = [{"priority": "high"}] # 缺 title
|
||||
with self.assertRaises(HandoverConfigError):
|
||||
normalize_shift_record(raw)
|
||||
|
||||
def test_non_dict_rejected(self):
|
||||
with self.assertRaises(HandoverConfigError):
|
||||
normalize_shift_record("not a dict")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4) build_llm_input
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestBuildLLMInput(unittest.TestCase):
|
||||
def test_renders_prompt_with_placeholders(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
name, text = build_llm_input(rec)
|
||||
self.assertEqual(name, DEFAULT_PROMPT_TEMPLATE)
|
||||
# 正文以 shift_handover 提示词开头
|
||||
self.assertTrue(text.startswith("生成交接班摘要"))
|
||||
# 班次与关键字段都被填入 {query}
|
||||
self.assertIn("夜班 2026-08-05", text)
|
||||
self.assertIn("张工", text)
|
||||
self.assertIn("炉层温度越上限", text)
|
||||
self.assertIn("总电耗", text)
|
||||
self.assertIn("复测 3 层温度趋势", text)
|
||||
|
||||
def test_respects_config_template_name(self):
|
||||
rec = normalize_shift_record({"shift": "夜班", "operator": "张工"})
|
||||
cfg = HandoverBriefConfig(prompt_template="custom_tmpl")
|
||||
name, _ = build_llm_input(rec, cfg)
|
||||
self.assertEqual(name, "custom_tmpl")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5) render_deterministic_brief
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestDeterministicBrief(unittest.TestCase):
|
||||
def test_contains_all_sections(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
text = render_deterministic_brief(rec)
|
||||
self.assertIn("交接班摘要", text)
|
||||
self.assertIn("生产概况", text)
|
||||
self.assertIn("异常事项", text)
|
||||
self.assertIn("安全注意事项", text)
|
||||
self.assertIn("能耗", text)
|
||||
self.assertIn("待办", text)
|
||||
|
||||
def test_sections_filter(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
cfg = HandoverBriefConfig(sections=["overview"])
|
||||
text = render_deterministic_brief(rec, cfg)
|
||||
self.assertIn("生产概况", text)
|
||||
# 只开 overview,异常/能耗等章节不应出现为标题
|
||||
self.assertNotIn("## 异常事项", text)
|
||||
self.assertNotIn("## 能耗", text)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6) generate_handover_brief(LLM 注入 + 降级)
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestGenerateBrief(unittest.TestCase):
|
||||
def test_uses_llm_output(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
|
||||
def llm(prompt: str) -> str:
|
||||
return "LLM 摘要:本班平稳,3 层温度曾越限已处置。"
|
||||
|
||||
out = generate_handover_brief(rec, llm_generate=llm)
|
||||
self.assertEqual(out, "LLM 摘要:本班平稳,3 层温度曾越限已处置。")
|
||||
|
||||
def test_falls_back_when_no_llm(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
out = generate_handover_brief(rec) # llm_generate=None
|
||||
self.assertIn("交接班摘要", out)
|
||||
self.assertIn("炉层温度越上限", out)
|
||||
|
||||
def test_falls_back_on_llm_exception(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
|
||||
def broken(prompt: str) -> str:
|
||||
raise RuntimeError("LLM 网关不可达")
|
||||
|
||||
out = generate_handover_brief(rec, llm_generate=broken)
|
||||
# LLM 故障 → 降级为确定性摘要
|
||||
self.assertIn("交接班摘要", out)
|
||||
|
||||
def test_falls_back_on_empty_llm_output(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
|
||||
def empty(prompt: str) -> str:
|
||||
return " "
|
||||
|
||||
out = generate_handover_brief(rec, llm_generate=empty)
|
||||
self.assertIn("交接班摘要", out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7) render_handover_brief(移动端 props)
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestRenderBriefProps(unittest.TestCase):
|
||||
def test_props_structure(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
props = render_handover_brief(rec)
|
||||
self.assertEqual(props["schema"], HANDOVER_CONFIG_SCHEMA_ID)
|
||||
self.assertEqual(props["shift"], "夜班 2026-08-05 00:00~08:00")
|
||||
self.assertEqual(props["operator"], "张工")
|
||||
self.assertEqual(props["nextShift"], "李工")
|
||||
self.assertEqual(props["promptTemplate"], DEFAULT_PROMPT_TEMPLATE)
|
||||
self.assertEqual(props["promptVersion"], DEFAULT_PROMPT_VERSION)
|
||||
self.assertEqual(len(props["events"]), 2)
|
||||
self.assertEqual(len(props["todos"]), 2)
|
||||
self.assertEqual(props["eventOverflow"], 0)
|
||||
self.assertEqual(props["todoOverflow"], 0)
|
||||
self.assertEqual(props["fontSize"], "md")
|
||||
# generatedAt 是 ISO 时间戳
|
||||
self.assertRegex(props["generatedAt"], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")
|
||||
|
||||
def test_truncation_and_overflow(self):
|
||||
raw = {
|
||||
"shift": "夜班", "operator": "张工",
|
||||
"events": [{"time": f"0{i}:00", "title": f"事件{i}"} for i in range(12)],
|
||||
"todos": [{"title": f"待办{i}"} for i in range(8)],
|
||||
}
|
||||
rec = normalize_shift_record(raw)
|
||||
cfg = HandoverBriefConfig(max_events=5, max_todos=3)
|
||||
props = render_handover_brief(rec, cfg)
|
||||
self.assertEqual(len(props["events"]), 5)
|
||||
self.assertEqual(len(props["todos"]), 3)
|
||||
self.assertEqual(props["eventOverflow"], 7)
|
||||
self.assertEqual(props["todoOverflow"], 5)
|
||||
|
||||
def test_critical_event_forces_confirm(self):
|
||||
raw = {
|
||||
"shift": "夜班", "operator": "张工",
|
||||
"events": [{"time": "01:00", "title": "严重告警", "severity": "P0"}],
|
||||
}
|
||||
rec = normalize_shift_record(raw)
|
||||
cfg = HandoverBriefConfig(require_confirm=False)
|
||||
props = render_handover_brief(rec, cfg)
|
||||
# 含 P0 事件 → requireConfirm 被强制为 true(PRD 高利害人工确认)
|
||||
self.assertTrue(props["requireConfirm"])
|
||||
|
||||
def test_safety_text_forces_confirm(self):
|
||||
raw = {
|
||||
"shift": "夜班", "operator": "张工",
|
||||
"safety": "注意 3 层高温区巡检。",
|
||||
}
|
||||
rec = normalize_shift_record(raw)
|
||||
cfg = HandoverBriefConfig(require_confirm=False)
|
||||
props = render_handover_brief(rec, cfg)
|
||||
self.assertTrue(props["requireConfirm"])
|
||||
|
||||
def test_section_switches(self):
|
||||
rec = normalize_shift_record(_full_record_dict())
|
||||
cfg = HandoverBriefConfig(sections=["overview", "abnormal"])
|
||||
props = render_handover_brief(rec, cfg)
|
||||
self.assertTrue(props["showOverview"])
|
||||
self.assertTrue(props["showAbnormal"])
|
||||
self.assertFalse(props["showSafety"])
|
||||
self.assertFalse(props["showEnergy"])
|
||||
self.assertFalse(props["showTodos"])
|
||||
|
||||
def test_injected_summary_passes_through(self):
|
||||
rec = normalize_shift_record({"shift": "夜班", "operator": "张工"})
|
||||
props = render_handover_brief(rec, summary="自定义摘要")
|
||||
self.assertEqual(props["summary"], "自定义摘要")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 8) 验收线
|
||||
# ---------------------------------------------------------------------------
|
||||
class TestGenerationBudget(unittest.TestCase):
|
||||
def test_within_budget(self):
|
||||
self.assertTrue(within_generation_budget(60_000)) # 1 分钟
|
||||
self.assertTrue(within_generation_budget(HANDOVER_GENERATION_BUDGET_MS))
|
||||
self.assertFalse(within_generation_budget(HANDOVER_GENERATION_BUDGET_MS + 1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,55 @@
|
||||
# 可用性监控探针(Availability Probe)
|
||||
|
||||
对应 EPIC #8「⑥ 部署底座」子任务 **#61**(0.5d,对齐 PRD 5.6 验收):
|
||||
对已部署服务按周期轮询健康端点(`GET /health`),统计窗口可用率,
|
||||
目标 **≥ 99.8%**。
|
||||
|
||||
## 文件
|
||||
|
||||
```
|
||||
deploy/k8s/healthz/
|
||||
├── probe_availability.py 探针实现(AvailabilityProbe + CLI)
|
||||
├── test_probe.py 单元测试(本地 HTTP 端点模拟)
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 用法(CLI)
|
||||
|
||||
```bash
|
||||
# 轮询 60 轮(每 1s 一次),目标 99.8%
|
||||
python probe_availability.py --endpoints http://10.20.0.30:8000 \
|
||||
--rounds 60 --interval 1 --target 0.998
|
||||
|
||||
# 多端点
|
||||
python probe_availability.py --endpoints http://a:8000,http://b:8000 \
|
||||
--rounds 120 --interval 5
|
||||
```
|
||||
|
||||
退出码:`0` = 可用率达标(PASS);`1` = 低于目标(FAIL),
|
||||
供 CronJob / 监控告警使用。
|
||||
|
||||
## 编程接口
|
||||
|
||||
```python
|
||||
from probe_availability import AvailabilityProbe
|
||||
|
||||
probe = AvailabilityProbe(["http://iaop-inference:8000"])
|
||||
report = probe.run(rounds=60, interval=1)
|
||||
print(report.to_dict())
|
||||
# {'total': 60, 'success': 60, 'availability': 1.0,
|
||||
# 'target': 0.998, 'meets_target': True, 'failures': 0, ...}
|
||||
```
|
||||
|
||||
## 验收口径(PRD 5.6)
|
||||
|
||||
- 可用率 = 成功探测数 / 总探测数,窗口内 ≥ 99.8%;
|
||||
- 探针**只读**(GET /health),不影响服务状态;
|
||||
- 失败明细(URL/原因/延迟)随报告输出,便于定位。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
python -m unittest test_probe -v
|
||||
```
|
||||
覆盖:稳定端点 100% 达标、单次故障(1/500=0.2%)恰好达标、
|
||||
50% 故障率判定 FAIL、失败明细记录。
|
||||
@@ -0,0 +1,153 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""可用性监控探针 —— 目标 ≥ 99.8%(issue #61 / PRD 5.6「⑥ 部署底座」)。
|
||||
|
||||
对已部署服务(推理服务 /health、驾驶舱等)按周期轮询健康端点,
|
||||
统计窗口内可用率(success / total),断言 ≥ 99.8% 验收阈值:
|
||||
|
||||
- 探针只读(GET /health),不修改任何状态;
|
||||
- 每次探测记录:时间戳 / 状态 / 延迟;
|
||||
- 报告输出:窗口可用率、总探测数、失败明细、最近一次延迟;
|
||||
- 可作为 CronJob 或边车(sidecar)周期性运行,结果喂给监控告警。
|
||||
|
||||
用法(CLI):
|
||||
python probe_availability.py --endpoints http://localhost:8000/health \
|
||||
--rounds 60 --interval 1 --target 0.998
|
||||
退出码:0 = 可用率达标;1 = 低于目标。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProbeResult:
|
||||
"""单次探测结果。"""
|
||||
|
||||
url: str
|
||||
ok: bool
|
||||
latency_ms: float = 0.0
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProbeReport:
|
||||
"""窗口统计报告。"""
|
||||
|
||||
total: int = 0
|
||||
success: int = 0
|
||||
availability: float = 0.0
|
||||
target: float = 0.998
|
||||
failures: List[ProbeResult] = field(default_factory=list)
|
||||
last_latency_ms: float = 0.0
|
||||
|
||||
def meets_target(self) -> bool:
|
||||
"""可用率 ≥ 目标(默认 99.8%)。"""
|
||||
return self.availability >= self.target
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"total": self.total,
|
||||
"success": self.success,
|
||||
"availability": round(self.availability, 6),
|
||||
"target": self.target,
|
||||
"meets_target": self.meets_target(),
|
||||
"failures": len(self.failures),
|
||||
"last_latency_ms": round(self.last_latency_ms, 2),
|
||||
}
|
||||
|
||||
|
||||
class AvailabilityProbe:
|
||||
"""可用性探针:周期轮询健康端点,统计可用率。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
endpoints: Sequence[str],
|
||||
timeout_seconds: float = 5.0,
|
||||
target: float = 0.998,
|
||||
) -> None:
|
||||
self.endpoints = [u.rstrip("/") for u in endpoints]
|
||||
self.timeout = float(timeout_seconds)
|
||||
self.target = float(target)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
def probe_once(self, url: str) -> ProbeResult:
|
||||
"""探测单个端点:GET /health,200 即可用。"""
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
url + "/health", timeout=self.timeout) as resp:
|
||||
ok = resp.status == 200
|
||||
return ProbeResult(
|
||||
url=url, ok=ok,
|
||||
latency_ms=round((time.monotonic() - started) * 1000, 2),
|
||||
detail=f"http-{resp.status}")
|
||||
except Exception as exc: # noqa: BLE001 - 探测失败即视为不可用
|
||||
return ProbeResult(
|
||||
url=url, ok=False,
|
||||
latency_ms=round((time.monotonic() - started) * 1000, 2),
|
||||
detail=f"error: {exc}")
|
||||
|
||||
def run(
|
||||
self,
|
||||
rounds: int = 60,
|
||||
interval: float = 1.0,
|
||||
) -> ProbeReport:
|
||||
"""执行 rounds 轮轮询(每轮探测全部端点),返回窗口报告。"""
|
||||
report = ProbeReport(target=self.target)
|
||||
for _ in range(max(1, rounds)):
|
||||
for url in self.endpoints:
|
||||
result = self.probe_once(url)
|
||||
report.total += 1
|
||||
if result.ok:
|
||||
report.success += 1
|
||||
report.last_latency_ms = result.latency_ms
|
||||
else:
|
||||
report.failures.append(result)
|
||||
if interval > 0:
|
||||
time.sleep(interval)
|
||||
report.availability = (
|
||||
report.success / report.total if report.total else 0.0)
|
||||
return report
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="可用性监控探针(目标 ≥ 99.8%,issue #61)")
|
||||
parser.add_argument("--endpoints", required=True,
|
||||
help="健康端点(逗号分隔,如 http://host:8000)")
|
||||
parser.add_argument("--rounds", type=int, default=60, help="轮询轮数")
|
||||
parser.add_argument("--interval", type=float, default=1.0, help="轮询间隔(秒)")
|
||||
parser.add_argument("--timeout", type=float, default=5.0, help="单次探测超时")
|
||||
parser.add_argument("--target", type=float, default=0.998,
|
||||
help="可用率目标(默认 0.998 = 99.8%)")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
probe = AvailabilityProbe(
|
||||
endpoints=[u for u in args.endpoints.split(",") if u],
|
||||
timeout_seconds=args.timeout, target=args.target)
|
||||
report = probe.run(rounds=args.rounds, interval=args.interval)
|
||||
|
||||
summary = report.to_dict()
|
||||
print(f"可用率 {summary['availability']:.4%} "
|
||||
f"({summary['success']}/{summary['total']},"
|
||||
f"目标 {summary['target']:.4%})"
|
||||
f" -> {'PASS' if summary['meets_target'] else 'FAIL'}")
|
||||
if report.failures:
|
||||
print("失败明细(前 10 条):")
|
||||
for f in report.failures[:10]:
|
||||
print(f" - {f.url}: {f.detail} ({f.latency_ms:.0f}ms)")
|
||||
return 0 if report.meets_target() else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,104 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""可用性监控探针测试(issue #61)。
|
||||
|
||||
用本地 ThreadingHTTPServer 模拟健康端点:
|
||||
1. 稳定 200 → 可用率 100% ≥ 99.8%;
|
||||
2. 间歇 503 → 可用率按失败比例下降,探针统计正确;
|
||||
3. 阈值判断:间歇失败超 0.2% 时 meets_target=False;
|
||||
4. 失败明细记录(URL + 原因)。
|
||||
"""
|
||||
import http.server
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from probe_availability import AvailabilityProbe # noqa: E402
|
||||
|
||||
|
||||
class _HealthHandler(http.server.BaseHTTPRequestHandler):
|
||||
"""可配置成功/失败模式的 /health 处理器。"""
|
||||
|
||||
fail_mode = [] # [True/False...] 按请求序号循环
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/health":
|
||||
if self.fail_mode and self.fail_mode[0]:
|
||||
self.fail_mode[0] = False # 一次性失败
|
||||
self.send_response(503)
|
||||
else:
|
||||
self.send_response(200)
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *args): # 静默日志
|
||||
pass
|
||||
|
||||
|
||||
def start_server(fail_once=False):
|
||||
handler = _HealthHandler
|
||||
handler.fail_mode = [True] if fail_once else []
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
thread = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
return srv
|
||||
|
||||
|
||||
class TestProbe(unittest.TestCase):
|
||||
"""探针统计与阈值判断。"""
|
||||
|
||||
def test_stable_endpoint_100pct(self):
|
||||
srv = start_server()
|
||||
try:
|
||||
url = f"http://127.0.0.1:{srv.server_port}"
|
||||
probe = AvailabilityProbe([url], timeout_seconds=2)
|
||||
report = probe.run(rounds=10, interval=0)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
self.assertEqual(report.total, 10)
|
||||
self.assertEqual(report.success, 10)
|
||||
self.assertEqual(report.availability, 1.0)
|
||||
self.assertTrue(report.meets_target())
|
||||
|
||||
def test_single_failure_below_threshold(self):
|
||||
srv = start_server(fail_once=True)
|
||||
try:
|
||||
url = f"http://127.0.0.1:{srv.server_port}"
|
||||
probe = AvailabilityProbe([url], timeout_seconds=2)
|
||||
report = probe.run(rounds=500, interval=0) # 1/500 = 0.2%
|
||||
finally:
|
||||
srv.shutdown()
|
||||
self.assertEqual(len(report.failures), 1)
|
||||
# 1/500 = 0.002 = 99.8% —— 恰好达标(>= target 判定通过)
|
||||
self.assertGreaterEqual(report.availability, report.target)
|
||||
self.assertTrue(report.meets_target())
|
||||
# urllib 对非 200 抛 HTTPError → 记为不可用
|
||||
self.assertFalse(report.failures[0].ok)
|
||||
self.assertIn("503", report.failures[0].detail)
|
||||
|
||||
def test_high_failure_rate_fails_threshold(self):
|
||||
# 构造 50% 失败的端点(fail_mode 每次循环交替:用两个处理器状态不可行,
|
||||
# 改为直接 mock probe_once)
|
||||
probe = AvailabilityProbe(["http://x"], timeout_seconds=1)
|
||||
results = [probe.probe_once.__self__.__class__] # noqa - 占位
|
||||
from unittest import mock
|
||||
ok_result = mock.MagicMock()
|
||||
ok_result.ok = True
|
||||
bad_result = mock.MagicMock()
|
||||
bad_result.ok = False
|
||||
bad_result.url = "http://x"
|
||||
bad_result.detail = "http-503"
|
||||
bad_result.latency_ms = 1.0
|
||||
# 交替 200/503 → 6 次探测 3 成功 → 50% 可用率,远低于 99.8%
|
||||
with mock.patch.object(probe, "probe_once",
|
||||
side_effect=[ok_result, bad_result] * 3):
|
||||
report = probe.run(rounds=6, interval=0)
|
||||
self.assertEqual(report.availability, 0.5)
|
||||
self.assertFalse(report.meets_target())
|
||||
self.assertEqual(len(report.failures), 3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -29,6 +29,19 @@ spec:
|
||||
nodeSelector:
|
||||
ascend.com/npu: "true"
|
||||
{{- end }}
|
||||
{{- if .Values.tolerations }}
|
||||
tolerations:
|
||||
{{- toYaml .Values.tolerations | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.image.serviceAccountName }}
|
||||
serviceAccountName: {{ .Values.image.serviceAccountName }}
|
||||
{{- end }}
|
||||
{{- if .Values.image.pullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- range .Values.image.pullSecrets }}
|
||||
- name: {{ . }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: inference
|
||||
image: "{{ include "iaop.image" . }}"
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{{- if .Values.autoscaling.enabled }}
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
metadata:
|
||||
name: {{ include "iaop.fullname" . }}
|
||||
labels:
|
||||
{{- include "iaop.labels" . | nindent 4 }}
|
||||
spec:
|
||||
scaleTargetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: {{ include "iaop.fullname" . }}
|
||||
minReplicas: {{ .Values.autoscaling.minReplicas }}
|
||||
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
|
||||
metrics:
|
||||
- type: Resource
|
||||
resource:
|
||||
name: cpu
|
||||
target:
|
||||
type: Utilization
|
||||
averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,22 @@
|
||||
# iAOP Helm Chart —— 开发/联调环境 values 覆盖示例(issue #56 多环境参数化)。
|
||||
# 用法:helm install iaop deploy/k8s/helm/iaop -f values.dev.yaml
|
||||
# 说明:仅覆盖与开发环境差异的键;其余继承 values.yaml 默认值。
|
||||
|
||||
# 开发环境:低副本、小资源、关 HPA(本地/联调)
|
||||
replicaCount: 1
|
||||
resources:
|
||||
requests:
|
||||
cpu: "1"
|
||||
memory: 4Gi
|
||||
limits:
|
||||
cpu: "4"
|
||||
memory: 16Gi
|
||||
autoscaling:
|
||||
enabled: false
|
||||
storage:
|
||||
size: 20Gi
|
||||
|
||||
# 域名入口(开发环境使用独立域名)
|
||||
ingress:
|
||||
enabled: true
|
||||
host: dev.iaop.example.com
|
||||
@@ -0,0 +1,35 @@
|
||||
# iAOP Helm Chart —— 生产环境 values 覆盖示例(issue #56 多环境参数化)。
|
||||
# 用法:helm install iaop deploy/k8s/helm/iaop -f values.prod.yaml
|
||||
# 说明:生产环境按 PRD 5.6 配置点固化:资源配额、副本/HPA、灰度、域名。
|
||||
|
||||
# 生产环境:多副本 + HPA、大资源、灰度滚动
|
||||
replicaCount: 3
|
||||
autoscaling:
|
||||
enabled: true
|
||||
minReplicas: 3
|
||||
maxReplicas: 10
|
||||
targetCPUUtilizationPercentage: 70
|
||||
rollingUpdate:
|
||||
maxUnavailable: 0
|
||||
maxSurge: 1
|
||||
resources:
|
||||
requests:
|
||||
cpu: "2"
|
||||
memory: 8Gi
|
||||
limits:
|
||||
cpu: "8"
|
||||
memory: 32Gi
|
||||
storage:
|
||||
enabled: true
|
||||
className: "" # 生产建议指定 SSD StorageClass
|
||||
size: 200Gi
|
||||
|
||||
# 域名入口(生产域名 + 证书)
|
||||
ingress:
|
||||
enabled: true
|
||||
host: iaop.example.com
|
||||
|
||||
# 私有镜像仓库凭据(生产必需)
|
||||
image:
|
||||
pullSecrets:
|
||||
- iaop-registry-secret
|
||||
@@ -10,6 +10,10 @@ image:
|
||||
repository: iaop/inference
|
||||
tag: v1.0.0
|
||||
pullPolicy: IfNotPresent
|
||||
# 私有仓库拉取凭据(imagePullSecrets)
|
||||
pullSecrets: []
|
||||
# 服务账户(缺省 = release 名;自定义请先创建)
|
||||
serviceAccountName: ""
|
||||
|
||||
# ---- 推理后端选择(PRD 5.6 配置点:切换后端仅改此处) ----
|
||||
inference:
|
||||
@@ -28,6 +32,16 @@ rollingUpdate:
|
||||
maxUnavailable: 0
|
||||
maxSurge: 1
|
||||
|
||||
# ---- 水平自动扩缩(HPA;副本参数化扩展,issue #56) ----
|
||||
autoscaling:
|
||||
enabled: false
|
||||
minReplicas: 2
|
||||
maxReplicas: 8
|
||||
targetCPUUtilizationPercentage: 70
|
||||
|
||||
# ---- 节点调度(可选) ----
|
||||
tolerations: [] # 容忍度(如 GPU/NPU 专用节点污点)
|
||||
|
||||
# ---- 服务 ----
|
||||
service:
|
||||
type: ClusterIP
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 氯化车间/海绵钛驾驶舱 · 告警面板配置资产(iAOP-Template-Ti 一期)。
|
||||
#
|
||||
# 对齐 PRD 5.5「⑤ 配置化驾驶舱」+ 5.3 ③ 场景A(异常检测 → 驾驶舱红色告警 +
|
||||
# LLM 生成"原因+处置建议" → 值班长确认):把告警面板的「严重度配色 / 规则源 /
|
||||
# SOP 联动 / 确认与静默 / 分组排序」外置为模板配置(issue #52)。
|
||||
#
|
||||
# 切换到其他行业模板(如树脂)= 换一份本文件,告警面板前端代码零改动
|
||||
# (PRD 5.5 验收口径「切换模板零改码」覆盖到告警面板)。
|
||||
#
|
||||
# $schema 对应 core/cockpit/alarm_config.py 的 ALARM_CONFIG_SCHEMA_ID。
|
||||
$schema: iAOP-cockpit-alarm-panel-v1
|
||||
# severityColors:P0/P1/P2 三级展示配色(覆盖主题默认告警色)。
|
||||
# P0=红色(驾驶舱红色告警,PRD 场景A)、P1=黄色(加强监控)、P2=蓝色(提示)。
|
||||
severityColors:
|
||||
- severity: P0
|
||||
fg: "#ff3b30" # 红色前景(告警文本 / 图标)
|
||||
bg: "rgba(255,59,48,0.12)"
|
||||
icon: alert-octagon
|
||||
border: "#ff3b30"
|
||||
- severity: P1
|
||||
fg: "#f5a623" # 黄色
|
||||
bg: "rgba(245,166,35,0.12)"
|
||||
icon: alert-triangle
|
||||
border: "#f5a623"
|
||||
- severity: P2
|
||||
fg: "#3aa0ff" # 蓝色(提示)
|
||||
bg: "rgba(58,160,255,0.10)"
|
||||
icon: info
|
||||
# rulesSource:告警面板订阅哪份规则资产(阈值/规则外置)。
|
||||
# 指向 issue #72 落地的炉层杂质预警规则模板(templates/ti-cl4/impurity-forecast/
|
||||
# config/alert_rules.template.yaml,在其 feature 分支上推进;此处先按规划路径绑定)。
|
||||
rulesSource:
|
||||
kind: asset
|
||||
ref: ti-cl4/impurity-forecast/config/alert_rules.template.yaml
|
||||
# thresholdsSource:阈值可与规则同源,这里显式独立声明,便于配置台单独维护。
|
||||
thresholdsSource:
|
||||
kind: asset
|
||||
ref: ti-cl4/impurity-forecast/config/alert_rules.template.yaml
|
||||
# SOP 联动:在面板里展开处置 SOP(PRD 场景A:LLM 报警解释 + 值班长确认)。
|
||||
showSop: true
|
||||
# 关键告警强制人工确认(PRD line 333:高利害人工确认,不直接联动执行机构)。
|
||||
requireAck: true
|
||||
ackTimeoutS: 300 # 5 分钟未确认自动升级 severity
|
||||
# 静默下限:低于 P2 的不展示(Ti 一期 P0/P1/P2 全展示)。
|
||||
muteLower: P2
|
||||
# 分组 / 排序 / 最大条数:大屏展示策略外置。
|
||||
groupBy: severity
|
||||
sortBy: severity
|
||||
maxItems: 50
|
||||
@@ -0,0 +1,30 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 氯化车间/海绵钛驾驶舱 · 移动端交接班摘要配置资产(iAOP-Template-Ti 一期)。
|
||||
#
|
||||
# 对齐 PRD 场景C(辅助):交接班 → LLM 汇总本班关键事件/能耗/待办 → 生成交接班
|
||||
# 报告 → 推送下一班(PRD line 84/350-351:交接班报告生成 ≤ 2 分钟、移动端交接班
|
||||
# 摘要可用)。
|
||||
#
|
||||
# 把"移动端交接班摘要"的展示语义(章节/折叠/字号/确认策略/绑定的 LLM 提示词)
|
||||
# 外置为模板配置(issue #53)。切换到其他行业模板(如树脂)= 换一份本文件,
|
||||
# 移动端卡片代码零改动(与 #52 同一验收口径「切换模板零改码」)。
|
||||
#
|
||||
# $schema 对应 core/shift-handover/handover.py 的 HANDOVER_CONFIG_SCHEMA_ID。
|
||||
$schema: iAOP-cockpit-handover-brief-v1
|
||||
# 绑定的提示词模板(core/llm-gateway/config/prompts.template.yaml):
|
||||
# shift_handover v1.0.1(current)正文含「生产概况/异常事项/安全注意事项」三章节。
|
||||
promptTemplate: shift_handover
|
||||
promptVersion: 1.0.1
|
||||
# 摘要包含的章节(移动端卡片渲染哪些区块):
|
||||
# overview 生产概况 / abnormal 异常事项 / safety 安全注意事项 /
|
||||
# energy 能耗 / todos 待办(交下一班)。
|
||||
sections: [overview, abnormal, safety, energy, todos]
|
||||
# 移动端展示策略(外置,配置台可调):
|
||||
maxEvents: 8 # 事件列表最多展示条数(超过折叠 + 溢出计数角标)
|
||||
maxTodos: 5 # 待办列表最多展示条数
|
||||
collapseThreshold: 4 # 超过该条数则折叠为「展开更多」
|
||||
fontSize: md # 移动端字号档位(sm/md/lg)
|
||||
# 高利害人工确认:交接班摘要通常非高利害(scenarios.template.yaml: high_stakes=false),
|
||||
# 但若本班出现 P0 告警 / 安全事件,内核会自动强制 requireConfirm=true(见
|
||||
# render_handover_brief),无需在此显式开启。
|
||||
requireConfirm: false
|
||||
Reference in New Issue
Block a user