fix(review): 首席架構師 Code Review 修補 — I1 get_incident_type 邏輯修正 + 測試補全
Some checks failed
CD Pipeline / build-and-deploy (push) Failing after 8m13s

Code Review 發現 2 個 Critical + 2 個 Important 問題:

Critical:
- rule.id 語意為「規則識別符」,與 incident_type 命名空間不同,不可混用
  移除 rule_id fallback 路徑,YAML 匹配無 incident_type 時 fall through 靜態 dict
- get_incident_type() 關鍵路徑無測試覆蓋
  新增 test_get_incident_type.py:11 測試、4 類別(靜態/YAML優先/YAML錯誤/custom)全過

Important:
- ALERTNAME_TO_TYPE deferred import 移至模組頂層(無 circular 風險)
- alert_types.py TODO 過期 → 更新為 I1 整合後正確說明

技術債記錄:NetworkPolicy ArgoCD egress ClusterIP 10.43.16.201/32 需 ArgoCD 重裝後更新

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
OG T
2026-04-11 21:33:04 +08:00
parent b2dfcf9b0d
commit d77b2add73
4 changed files with 224 additions and 11 deletions

View File

@@ -6,8 +6,9 @@ alertname → incident_type 靜態對應表
來源: BUG-008 修復 2026-04-119筆 → 56筆涵蓋 alerts-unified.yml 全部 alertname
遷移: M3 2026-04-11 — 從 webhooks.py 內聯 dict 抽至此模組
TODO (I1): 下 Sprint 整合 ADR-064 Rule Engine改用 YAML 規則動態推斷;
此靜態 dict 為可接受中間狀態
整合狀態 (I1, 2026-04-11): ADR-064 Rule Engine 已整合,見 alert_rule_engine.get_incident_type()。
此靜態 dict 為 Layer 2 fallbackYAML incident_typeLayer 1→ 此 dict → "custom"Layer 3
擴展方式:在 alert_rules.yaml 中新增 incident_type 欄位;此 dict 僅需補無 YAML 規則的 alertname。
"""
# alertname → incident_type 對應56 筆)

View File

@@ -31,6 +31,8 @@ import httpx
import structlog
import yaml
from src.constants.alert_types import ALERTNAME_TO_TYPE
logger = structlog.get_logger(__name__)
RULES_FILE = Path(__file__).parent.parent.parent / "alert_rules.yaml"
@@ -267,14 +269,13 @@ def get_incident_type(alertname: str) -> str:
從 YAML 規則動態推斷 incident_type取代 webhooks.py 靜態 dict。
優先順序:
1. alert_rules.yaml 中 match.alertname 完全匹配 → 使用 rule.incident_type
1. alert_rules.yaml 中 match.alertname 完全匹配 ruleincident_type 欄位 → 使用之
2. ALERTNAME_TO_TYPE 靜態 dict fallbackconstants/alert_types.py
3. "custom"(兜底)
rule.incident_type 可選欄位;若 YAML 規則未設則跳過進 fallback。
注意YAML rule.id 語意為「規則識別符」,不等於 incident_type
兩者命名空間不同不可混用。YAML 未設 incident_type 時一律走 fallback。
"""
from src.constants.alert_types import ALERTNAME_TO_TYPE
try:
rules = _load_rules()
for rule in rules:
@@ -282,14 +283,10 @@ def get_incident_type(alertname: str) -> str:
continue
alertnames = rule.get("match", {}).get("alertname", [])
if alertname in alertnames:
# YAML incident_type 欄位優先用
# 只有 YAML 明確設定 incident_type 才採用,否則 fall through 到靜態 dict
incident_type = rule.get("incident_type")
if incident_type:
return incident_type
# 無 incident_type 欄位 → 用 rule id 作為 incident_type語意一致
rule_id = rule.get("id", "")
if rule_id:
return rule_id
break
except Exception:
pass