Files
xieyi-weixin-/test_review_policy.py
T
2026-09-30 19:30:58 +08:00

379 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""审核闸:裁判判高风险在任何裁判模式下都转人工;关键词比对做全角/大小写/空白/标点归一化。
只用内存数据。review_policy 不读配置、不联网;wechat_bot 的几个方法按 AST 从源码
单独编译,不导入整个模块(导入会初始化运行目录,源码运行时会改写源码目录)。
"""
import ast
import functools
import hashlib
import json
import os
import shutil
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from types import ModuleType
from unittest import mock
import review_policy as policy
HIGH_RISK = "模型裁判评估为高风险"
FIRST_CONTACT_PLACEHOLDER = "(首次会话的新消息已由聊天截图确认)"
# 2026-09-30 线上的「用药调整」关键词;另两条是后台默认规则。
PRODUCTION_RULES = [
{"id": "diagnosis", "label": "诊断",
"keywords": ["确诊", "诊断", "是不是得了", "是不是患了", "是什么病"], "enabled": True},
{"id": "medication", "label": "用药调整",
"keywords": ["加量", "减量", "停药", "换药", "能不能吃", "剂量", "血糖"], "enabled": True},
{"id": "complaint", "label": "投诉退款",
"keywords": ["投诉", "退款", "退货", "举报", "曝光", "消协"], "enabled": True},
]
USAGE_RULE = {"id": "usage", "label": "用法用量", "keywords": ["服用", "饭后", "温服"], "enabled": True}
# 2026-09-30 事故原话:客户问服法,机器人自动答了错误剂量。
INCIDENT_CUSTOMER = "这个中药怎么服用?请告知[抱拳]"
INCIDENT_REPLY = "常规是早晚饭后半小时温服,一次一袋就可以…"
def rule(*keywords, label="规则", enabled=True):
return {"label": label, "keywords": list(keywords), "enabled": enabled}
def reason(customer, reply="", rules=(), state=None):
return policy.selective_review_reason(state or {}, customer, reply, rules=list(rules))
class JudgeVerdictTest(unittest.TestCase):
def test_high_verdict_holds_in_every_judge_mode(self):
for mode in ("shadow", "score_only", "arbitrate", "SHADOW", "", "nonsense", None):
with self.subTest(mode=mode):
state = {"judge_risk": "high"}
if mode is not None:
state["judge_mode"] = mode
self.assertEqual(policy.judge_review_reason(state), HIGH_RISK)
self.assertEqual(reason("问题", "回复", state=state), HIGH_RISK)
def test_legacy_current_mode_argument_cannot_release_high_verdict(self):
state = {"judge_risk": " HIGH ", "judge_mode": "shadow"}
for current in ("shadow", "score_only", "", None):
with self.subTest(current=current):
self.assertEqual(policy.judge_review_reason(state, current_mode=current), HIGH_RISK)
self.assertEqual(policy.selective_review_reason(
state, "问题", "回复", rules=[], current_mode=current), HIGH_RISK)
def test_non_high_verdicts_do_not_hold(self):
for risk in ("low", "medium", "unknown", "", None):
for mode in ("shadow", "score_only", "arbitrate", ""):
with self.subTest(risk=risk, mode=mode):
state = {"judge_risk": risk, "judge_mode": mode}
self.assertEqual(policy.judge_review_reason(state), "")
self.assertEqual(reason("问题", "回复", state=state), "")
self.assertEqual(policy.judge_review_reason(None), "")
def test_high_verdict_takes_precedence_over_keyword_rules(self):
state = {"judge_risk": "high", "judge_mode": "shadow"}
self.assertEqual(reason("能不能吃", "", [rule("能不能吃")], state), HIGH_RISK)
class KeywordMatchingTest(unittest.TestCase):
def test_whitespace_and_punctuation_are_ignored(self):
for text in ("能不 能吃", "能不能吃?", "能不能吃?", "能\u3000不能吃", "能不,能吃", "能不能\n吃",
"能不\u200b能吃", "“能不能吃”", "【能不能吃】"):
with self.subTest(text=text):
self.assertEqual(reason(text, "", [rule("能不能吃", label="用药调整")]), "命中审核规则:用药调整")
# 关键词自己带空白或标点也照样生效
self.assertTrue(reason("这个药能不能吃", "", [rule(" 能不能吃? ")]))
self.assertTrue(reason("请问能否加量", "", [rule("加 量")]))
def test_full_width_and_case_are_folded(self):
self.assertTrue(reason("要不要做CT", "", [rule("ct")]))
self.assertTrue(reason("要不要做ct", "", [rule("CT")]))
self.assertTrue(reason("", "请复查 HbA1c", [rule("hba1c")]))
self.assertTrue(reason("Covid", "", [rule("COVID")]))
self.assertTrue(reason("123", "", [rule("123")]))
def test_keyword_hits_either_customer_or_reply(self):
self.assertTrue(reason("这个药能不能吃", "请稍等", [rule("能不能吃")]))
self.assertTrue(reason("请稍等", "建议停药观察", [rule("停药")]))
self.assertEqual(reason("请稍等", "好的", [rule("停药")]), "")
def test_keyword_cannot_span_customer_and_reply(self):
self.assertEqual(reason("我想问能不", "能吃的话告诉您", [rule("能不能吃")]), "")
def test_joined_keyword_is_split(self):
for word in ("服用,用法", "服用,用法", "服用、用法", "服用;用法", "服用;用法"):
for text in ("怎么服用", "用法是什么"):
with self.subTest(word=word, text=text):
self.assertTrue(reason(text, "", [rule(word)]))
self.assertEqual(reason("怎么保存", "", [rule("服用,用法")]), "")
def test_disabled_rule_is_ignored(self):
rules = [rule("能不能吃", enabled=False)]
self.assertEqual(reason("能不能吃", "", rules), "")
self.assertEqual(reason("", "能不能吃", rules), "")
# enabled 缺省视为开启
self.assertTrue(reason("能不能吃", "", [{"label": "默认开启", "keywords": ["能不能吃"]}]))
def test_empty_keywords_are_ignored(self):
rules = [rule("", " ", "?", ",", "...", None, label="空词")]
for text in ("能不能吃?", "你好,在吗", "...", ""):
with self.subTest(text=text):
self.assertEqual(reason(text, "好的。", rules), "")
def test_malformed_rules_are_ignored(self):
rules = [None, "诊断", {"label": "坏", "keywords": "诊断"}, {"label": "空", "keywords": None}]
self.assertEqual(reason("诊断", "诊断", rules), "")
self.assertEqual(policy.selective_review_reason({}, "诊断", "诊断", rules=None), "")
def test_reason_text_format_is_unchanged(self):
self.assertEqual(reason("诊断", "", [rule("诊断", label=" 诊断 ")]), "命中审核规则:诊断")
self.assertEqual(reason("诊断", "", [rule("诊断", label="")]), "命中审核规则:未命名规则")
# 多条同时命中时按规则顺序取第一条
self.assertEqual(reason("诊断后能不能吃", "", PRODUCTION_RULES), "命中审核规则:诊断")
class MedicationUsageIncidentTest(unittest.TestCase):
def test_incident_misses_production_rules(self):
state = {"judge_risk": "unknown", "judge_mode": "shadow"}
self.assertEqual(reason(INCIDENT_CUSTOMER, INCIDENT_REPLY, PRODUCTION_RULES, state), "")
def test_usage_rule_holds_incident_from_either_side(self):
rules = PRODUCTION_RULES + [USAGE_RULE]
for customer, reply in ((INCIDENT_CUSTOMER, INCIDENT_REPLY), (INCIDENT_CUSTOMER, ""), ("", INCIDENT_REPLY)):
with self.subTest(customer=customer, reply=reply):
self.assertEqual(reason(customer, reply, rules), "命中审核规则:用法用量")
def test_incident_with_high_verdict_holds_under_shadow(self):
state = {"judge_risk": "high", "judge_mode": "shadow"}
self.assertEqual(reason(INCIDENT_CUSTOMER, INCIDENT_REPLY, PRODUCTION_RULES, state), HIGH_RISK)
class RecheckGuardTest(unittest.TestCase):
def test_protected_work_is_never_rechecked(self):
base = {"awaiting_review": True, "stage": "manual_review"}
self.assertTrue(policy.can_recheck_review(base))
for fields in ({"send_state": "sending"}, {"stage": "receipt_check"}, {"manual_required": True},
{"foreign_draft_text": "人工草稿"}, {"foreign_draft_at": 0}, {"cancel_requested": True}):
with self.subTest(fields=fields):
self.assertFalse(policy.can_recheck_review(dict(base, **fields)))
WECHAT_BOT_PATH = Path(__file__).resolve().parent / "wechat_bot.py"
@functools.lru_cache(maxsize=None)
def _wechat_bot_tree():
return ast.parse(WECHAT_BOT_PATH.read_text(encoding="utf-8-sig"), filename=str(WECHAT_BOT_PATH))
@functools.lru_cache(maxsize=None)
def _isolated_bot_namespace():
"""只编译审核文字相关的模块级函数和 WeChatBot 方法,不执行 wechat_bot 模块本身。"""
path = WECHAT_BOT_PATH
tree = _wechat_bot_tree()
constants = {"_AVATAR_FP_BYTES", "_NAME_FP_BYTES", "_SESSION_FP_BYTES", "_LEGACY_SESSION_FP_BYTES",
"SEND_MODE_AUTO", "SEND_MODE_REVIEW"}
assigns = [node for node in tree.body if isinstance(node, ast.Assign)
and any(isinstance(target, ast.Name) and target.id in constants for target in node.targets)]
helper_names = {"review_match_text"}
helpers = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in helper_names]
missing_helpers = helper_names - {node.name for node in helpers}
if missing_helpers:
raise AssertionError("wechat_bot 缺少模块级函数:" + repr(missing_helpers))
original = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "WeChatBot")
names = {"_review_mode_enabled", "_reply_needs_review", "_drop_stale_review_flags", "_stage_exchange",
"_reset_pending_batch_unlocked", "_persist_pending_replies_unlocked", "_load_pending_replies",
"_knowledge_trace_metadata", "_voice_task_timestamp"}
methods = [node for node in original.body if isinstance(node, ast.FunctionDef) and node.name in names]
missing = names - {node.name for node in methods}
if missing:
raise AssertionError("wechat_bot 缺少方法:" + repr(missing))
cls = ast.ClassDef(name="WeChatBot", bases=[], keywords=[], body=methods, decorator_list=[])
module = ast.Module(body=[ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0),
*assigns, *helpers, cls], type_ignores=[])
namespace = {"hashlib": hashlib, "json": json, "os": os, "time": time}
exec(compile(ast.fix_missing_locations(module), str(path), "exec"), namespace)
return namespace
class ReviewMatchTextTest(unittest.TestCase):
"""发送闸和审核复查共用的客户侧比对文字。"""
@classmethod
def setUpClass(cls):
cls.match_text = staticmethod(_isolated_bot_namespace()["review_match_text"])
def test_first_contact_placeholder_is_joined_with_customer_words(self):
state = {"staged_user_text": FIRST_CONTACT_PLACEHOLDER, "staged_review_text": INCIDENT_CUSTOMER,
"last_lines": ["不该用到的聊天行"]}
self.assertEqual(self.match_text(state), FIRST_CONTACT_PLACEHOLDER + "\n" + INCIDENT_CUSTOMER)
# 占位文字本身命中不了规则,拼上客户原话才拦得住事故那一句
rules = PRODUCTION_RULES + [USAGE_RULE]
self.assertEqual(reason(FIRST_CONTACT_PLACEHOLDER, "好的", rules), "")
self.assertEqual(reason(self.match_text(state), "好的", rules), "命中审核规则:用法用量")
def test_last_lines_stand_in_for_missing_staged_text(self):
self.assertEqual(self.match_text({"last_lines": ["第一行", 2]}), "第一行\n2")
self.assertEqual(self.match_text({"staged_user_text": "", "last_lines": ["聊天行"],
"staged_review_text": "原话"}), "聊天行\n原话")
self.assertEqual(self.match_text({"staged_review_text": "只有原话"}), "\n只有原话")
def test_without_review_text_only_staged_text_is_used(self):
for extra in ({}, {"staged_review_text": ""}, {"staged_review_text": None}):
with self.subTest(extra=extra):
self.assertEqual(self.match_text(dict({"staged_user_text": "可信的客户原话"}, **extra)),
"可信的客户原话")
def test_empty_or_missing_state_gives_empty_text(self):
for state in (None, {}, "", [], {"staged_user_text": None, "last_lines": None}):
with self.subTest(state=state):
self.assertEqual(self.match_text(state), "")
def test_send_gate_and_recheck_use_the_helper(self):
tree = _wechat_bot_tree()
bot = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "WeChatBot")
def uses_helper(node):
return isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "review_match_text"
# 发送闸:_reply_review_decision 的客户文字参数必须直接来自 review_match_text
gate_calls = [node for node in ast.walk(bot) if isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute) and node.func.attr == "_reply_review_decision"]
self.assertTrue(gate_calls)
for call in gate_calls:
with self.subTest(line=call.lineno):
self.assertTrue(len(call.args) >= 2 and uses_helper(call.args[1]),
"发送闸没有用 review_match_text 取客户文字")
# 取的必须是同一个待发任务,不能是 None 或别的状态
helper_args = call.args[1].args
self.assertTrue(isinstance(call.args[0], ast.Name) and len(helper_args) == 1
and isinstance(helper_args[0], ast.Name) and helper_args[0].id == call.args[0].id,
"review_match_text 没有拿到发送闸自己的待发任务")
# 复查:_drop_stale_review_flags 用同一个函数取证据(行为另由 VisualReviewHoldTest 覆盖)
recheck = next(node for node in bot.body
if isinstance(node, ast.FunctionDef) and node.name == "_drop_stale_review_flags")
self.assertTrue(any(uses_helper(node) for node in ast.walk(recheck)))
def test_first_contact_branch_stages_the_real_words_for_review(self):
# 首次会话归档用占位文字;规则比对要的原话由这一支单独暂存,丢了它 BUG 2 就回来了。
tree = _wechat_bot_tree()
bot = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "WeChatBot")
placeholder = "(首次会话的新消息已由聊天截图确认)"
branches = [node for node in ast.walk(bot) if isinstance(node, ast.If) and any(
isinstance(stmt, ast.Assign) and isinstance(stmt.value, ast.Constant) and stmt.value.value == placeholder
for stmt in node.body)]
self.assertEqual(len(branches), 1, "找不到首次会话的占位分支")
assigned = [stmt.value for stmt in branches[0].body if isinstance(stmt, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == "review_text" for t in stmt.targets)]
self.assertTrue(assigned and isinstance(assigned[-1], ast.Call)
and isinstance(assigned[-1].func, ast.Name) and assigned[-1].func.id == "latest_customer_turn",
"首次会话分支没有把客户原话放进 review_text")
method = next(node for node in bot.body if isinstance(node, ast.FunctionDef)
and any(sub is branches[0] for sub in ast.walk(node)))
stage_calls = [node for node in ast.walk(method) if isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute) and node.func.attr == "_stage_exchange"]
self.assertTrue(stage_calls)
for call in stage_calls:
with self.subTest(line=call.lineno):
passed = [kw.value for kw in call.keywords if kw.arg == "review_text"]
self.assertTrue(passed and isinstance(passed[0], ast.Name) and passed[0].id == "review_text",
"_stage_exchange 没有收到 review_text")
class VisualReviewHoldTest(unittest.TestCase):
"""视觉链路的发送闸/复查:影子模式高风险不再被复查放行,首次会话原话参与规则比对。"""
@classmethod
def setUpClass(cls):
cls.bot_class = _isolated_bot_namespace()["WeChatBot"]
def setUp(self):
self.config = ModuleType("ai_config")
self.config.AI_REVIEW_RULES = []
patcher = mock.patch.dict(sys.modules, {"ai_config": self.config})
patcher.start()
self.addCleanup(patcher.stop)
self.fp = b"r" * 40
self.key = self.fp.hex()
self.state = {"stage": "manual_review", "awaiting_review": True, "review_origin": "rule",
"staged_user_text": "问题", "staged_reply_text": "回复", "reply_text": "回复"}
bot = self.bot = self.bot_class()
bot.send_mode = "auto"
bot._pending_lock = threading.RLock()
bot._pending_reply_sessions = {self.key: self.state}
bot._pending_reply_state = lambda fp: bot._pending_reply_sessions.get(bytes(fp).hex())
bot._persist_pending_replies = mock.Mock(return_value=True)
bot._forget_uncertain_tracking = mock.Mock()
def drop(self):
with mock.patch("builtins.print"):
self.bot._drop_stale_review_flags()
def test_shadow_high_risk_hold_stays_held(self):
for mode in ("shadow", "score_only", ""):
with self.subTest(mode=mode):
self.state.update(awaiting_review=True, stage="manual_review", review_reason=HIGH_RISK,
judge_risk="high", judge_mode=mode)
self.assertEqual(self.bot._reply_needs_review(self.state, "问题", "回复"), (True, HIGH_RISK))
self.drop()
self.assertTrue(self.state["awaiting_review"])
self.assertEqual(self.state["stage"], "manual_review")
self.assertFalse(self.state.get("review_approved"))
def test_obsolete_keyword_hold_is_still_released(self):
self.config.AI_REVIEW_RULES = [rule("问题", label="已关闭", enabled=False)]
self.state.update(review_reason="命中审核规则:已关闭", judge_risk="low", judge_mode="shadow")
self.drop()
self.assertFalse(self.state.get("awaiting_review"))
self.assertEqual(self.state["stage"], "queued")
self.assertFalse(self.state.get("review_approved"))
def test_first_contact_customer_words_keep_rule_hold(self):
self.config.AI_REVIEW_RULES = PRODUCTION_RULES + [USAGE_RULE]
reply = "您好,这边帮您确认一下"
self.bot._stage_exchange(self.fp, FIRST_CONTACT_PLACEHOLDER, reply, review_text=INCIDENT_CUSTOMER)
self.assertEqual(self.state["staged_user_text"], FIRST_CONTACT_PLACEHOLDER)
self.assertEqual(self.state["staged_review_text"], INCIDENT_CUSTOMER)
self.assertEqual(self.bot._pending_exchanges[self.key], (FIRST_CONTACT_PLACEHOLDER, reply))
# 只看占位文字永远命中不了规则——这正是要修的问题
self.assertEqual(self.bot._reply_needs_review(self.state, FIRST_CONTACT_PLACEHOLDER, reply), (False, ""))
self.state.update(review_reason="命中审核规则:用法用量", staged_reply_text=reply, reply_text=reply)
self.drop()
self.assertTrue(self.state["awaiting_review"])
self.assertEqual(self.state["review_reason"], "命中审核规则:用法用量")
def test_review_text_does_not_outlive_its_batch(self):
self.bot._stage_exchange(self.fp, FIRST_CONTACT_PLACEHOLDER, "回复", review_text=INCIDENT_CUSTOMER)
self.bot._stage_exchange(self.fp, "可信的客户原话", "回复")
self.assertNotIn("staged_review_text", self.state)
self.bot._stage_exchange(self.fp, FIRST_CONTACT_PLACEHOLDER, "回复", review_text=INCIDENT_CUSTOMER)
self.bot._reset_pending_batch_unlocked(self.fp)
self.assertNotIn("staged_review_text", self.state)
def test_review_text_survives_restart(self):
root = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, root, True)
self.bot._pending_reply_path = os.path.join(root, "pending_replies.json")
self.bot._manual_handoff_key = lambda fp: ""
self.state.update(review_reason="命中审核规则:用法用量", staged_user_text=FIRST_CONTACT_PLACEHOLDER,
staged_review_text=INCIDENT_CUSTOMER, confirmed_unread=True, updated_at=time.time())
self.assertTrue(self.bot._persist_pending_replies_unlocked())
with mock.patch("builtins.print"):
restored = self.bot._load_pending_replies()[self.key]
self.assertEqual(restored["staged_review_text"], INCIDENT_CUSTOMER)
self.assertEqual(restored["staged_user_text"], FIRST_CONTACT_PLACEHOLDER)
self.config.AI_REVIEW_RULES = [USAGE_RULE]
self.bot._pending_reply_sessions = {self.key: restored}
self.drop()
self.assertTrue(restored["awaiting_review"])
if __name__ == "__main__":
unittest.main()