Files
group_fqcd_jr/tests/integration/test_intent_config_runtime_mysql.py
T
lzf_0626 468ae0bd47 fix(admin): 激活意图不再归档同 Agent 的其他意图(风控 4 意图曾只剩 1 条生效)
两个相关的缺陷,都属于**静默失效**型。

1. `admin_service._transition_intent_config`(真正的 bug)

   激活一个意图时按 `agent_type` 过滤旧 active 版本并归档,但唯一键是生成列
   `active_key = concat(agent_type, ':', intent_code)` —— 同一 `agent_type` 下
   **不同意图码本就允许并存**。于是激活 `general` 会把
   `risk_overview` / `risk_search` / `risk_evidence` 一并归档:风控运行期只剩 1 条
   active 意图,问"查看当前风险概览"被分到 `general`(confidence 0.5),
   而**没有任何报错**。该函数自己的 docstring 写的正是正确行为,实现与它不符。

2. `tools/publish_risk_agent_config.py`(使脚本无法自愈)

   按 `intent_code` 单键建 dict 收集现有意图,而列表**按 id 倒序**返回且同一意图码
   有多个版本,于是**旧版本覆盖新版本**;取到 v1 后再"版本 +1"算出的正是已被占用的
   v2,创建必然 409 IDEMPOTENCY_CONFLICT。现象是 4 条意图全部"创建失败"而库里
   其实都有,`tools/seed_demo_data.py` 第 7 步因此必然失败。

修复后实测:

- 库里 4 个风控意图全部 active;
- 问"查看当前风险概览" → `intent=risk_overview`、`confidence=1.0000`
  (修复前为 `general` / 0.5);
- `tools/seed_demo_data.py` 10/10 步完成、退出码 0(修复前第 7 步退出码 1)。

回归测试:`test_activating_one_intent_does_not_archive_sibling_intents`。
已确认把修复回退后该用例**确实失败**(`['beta'] != ['alpha', 'beta']`),
不是永远通过的空测试 —— 原有用例盖不住这个缺陷,因为它建的第二个意图始终停在 draft、
从未激活过。

门禁:ruff 通过;mypy 250 文件 0 错;unit+contract 1381 passed / 0 failed;
integration 104 passed;e2e 冒烟 40/40。
2026-09-13 22:08:04 +08:00

176 lines
8.7 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.
"""真实 MySQL:意图配置激活后必须被运行期分类链路读到。
覆盖两件事(都不改库结构,只写数据):
1. 状态机可用:`draft --reviews--> approved --activations--> active`,激活写
`reviewer_id/reviewed_at/effective_at`,并把同 `agent_type:intent_code` 的旧 active
版本归档(生成列唯一键 `uk_intent_config_active_one` 不允许两个 active);
2. 运行期真的读它:`load_active_intent_configs`(分类链路的装载器)按 `agent_type`
返回 active 行,draft 行不返回,归档后不再返回。
"""
import uuid
from datetime import UTC, datetime
from decimal import Decimal
import pytest
from sqlalchemy import text
from app.core.contracts import RequestContext
from app.infrastructure.db import SessionFactory
from app.repository.platform_repository import PlatformRepository
from app.service.admin_service import AdminService
from app.service.runtime_config_service import load_active_intent_configs
pytestmark = pytest.mark.integration
INTENT = "fund_quote"
def now() -> datetime:
return datetime.now(UTC).replace(tzinfo=None)
async def test_activation_state_machine_feeds_runtime_intent_config() -> None:
agent_type = f"it_intent_{uuid.uuid4().hex[:12]}"
actor = uuid.uuid4().int % 10**12 + 10**15
async with SessionFactory() as session, session.begin():
await session.execute(text("""
INSERT INTO sys_user
(id,user_no,username,password_hash,user_type,professional_investor_status,
fund_account_status,status,created_at,updated_at)
VALUES (:id,:name,:name,'test-only','员工','未申请','未开户','正常',
UTC_TIMESTAMP(),UTC_TIMESTAMP())
"""), {"id": actor, "name": f"it-intent-{actor}"})
try:
context = RequestContext(user_id=str(actor), trace_id="it-intent", roles=("admin",))
service = AdminService()
async with SessionFactory() as session:
repo = PlatformRepository(session)
draft = await repo.create("agent_intent_config", {
"agent_type": agent_type, "intent_code": INTENT, "intent_name": "旧版本意图",
"description": "旧描述", "examples": ["旧示例"],
"confidence_threshold": Decimal("0.9000"), "version": 1, "created_by": actor,
})
# 另建一个只停留在 draft 的意图,用来证明运行期不读非 active 行。
await repo.create("agent_intent_config", {
"agent_type": agent_type, "intent_code": "draft_only", "intent_name": "草稿意图",
"description": "草稿描述", "examples": [], "version": 1, "created_by": actor,
})
approved = await service._transition(
repo, "agent-intent-configs", draft, "reviews", {"decision": "approved"}, context
)
assert approved["status"] == "approved"
assert int(approved["reviewer_id"]) == actor
activated = await service._transition(
repo, "agent-intent-configs", approved, "activations", {}, context
)
assert activated["status"] == "active"
assert activated["effective_at"] is not None
await session.commit()
# 运行期装载器走独立会话:只有已提交的 active 行可见,draft 行不可见。
entries = await load_active_intent_configs(agent_type)
assert [entry.intent_code for entry in entries] == [INTENT]
assert entries[0].description == "旧描述"
assert entries[0].confidence_threshold == 0.9
# 新版本激活:旧 active 版本被归档,装载器只看到新版本。
async with SessionFactory() as session:
repo = PlatformRepository(session)
newer = await repo.create("agent_intent_config", {
"agent_type": agent_type, "intent_code": INTENT, "intent_name": "新版本意图",
"description": "新描述", "examples": ["新示例"],
"confidence_threshold": Decimal("0.6000"), "version": 2, "created_by": actor,
})
approved_new = await service._transition(
repo, "agent-intent-configs", newer, "reviews", {"decision": "approved"}, context
)
await service._transition(
repo, "agent-intent-configs", approved_new, "activations", {}, context
)
archived = await repo.get("agent_intent_config", draft["id"])
assert archived is not None and archived["status"] == "archived"
await session.commit()
entries = await load_active_intent_configs(agent_type)
assert [(entry.description, entry.confidence_threshold) for entry in entries] == [
("新描述", 0.6)
]
# 归档生效版本后,运行期不再读到它(归档是明确的失效动作)。
async with SessionFactory() as session:
repo = PlatformRepository(session)
current = await repo.get("agent_intent_config", newer["id"])
assert current is not None
await service._transition(
repo, "agent-intent-configs", current, "archivals", {}, context
)
await session.commit()
assert await load_active_intent_configs(agent_type) == ()
finally:
async with SessionFactory() as session, session.begin():
await session.execute(
text("DELETE FROM agent_intent_config WHERE agent_type=:agent"),
{"agent": agent_type},
)
await session.execute(text("DELETE FROM sys_user WHERE id=:id"), {"id": actor})
async def test_activating_one_intent_does_not_archive_sibling_intents() -> None:
"""激活一个意图**不得**归档同 Agent 的其他意图。
唯一键是生成列 `active_key = concat(agent_type, ':', intent_code)`,
即同一 `agent_type` 下**不同意图码本就允许并存**(风控的 4 个意图就是并存的)。
这里曾经按 `agent_type` 过滤旧 active 版本去归档,于是激活 `general` 会把
`risk_overview` / `risk_search` / `risk_evidence` 一并归档:风控运行期只剩 1 条
active 意图,问"查看当前风险概览"被分到 `general`,**且没有任何报错**。
上一个用例恰好盖不住这个缺陷 —— 它建的第二个意图始终停留在 draft、从未激活过。
"""
agent_type = f"it_intent_multi_{uuid.uuid4().hex[:12]}"
actor = uuid.uuid4().int % 10**12 + 10**15
async with SessionFactory() as session, session.begin():
await session.execute(text("""
INSERT INTO sys_user
(id,user_no,username,password_hash,user_type,professional_investor_status,
fund_account_status,status,created_at,updated_at)
VALUES (:id,:name,:name,'test-only','员工','未申请','未开户','正常',
UTC_TIMESTAMP(),UTC_TIMESTAMP())
"""), {"id": actor, "name": f"it-intent-multi-{actor}"})
try:
context = RequestContext(
user_id=str(actor), trace_id="it-intent-multi", roles=("admin",)
)
service = AdminService()
# 两个**不同意图码**依次走完 draft -> approved -> active
for code in ("alpha", "beta"):
async with SessionFactory() as session:
repo = PlatformRepository(session)
created = await repo.create("agent_intent_config", {
"agent_type": agent_type, "intent_code": code,
"intent_name": f"{code} 意图", "description": f"{code} 描述",
"examples": [f"{code} 示例"],
"confidence_threshold": Decimal("0.6500"), "version": 1,
"created_by": actor,
})
approved = await service._transition(
repo, "agent-intent-configs", created, "reviews",
{"decision": "approved"}, context
)
await service._transition(
repo, "agent-intent-configs", approved, "activations", {}, context
)
await session.commit()
# 关键断言:激活 beta 之后 alpha **仍然 active**,两个都要能被运行期读到
entries = await load_active_intent_configs(agent_type)
assert sorted(entry.intent_code for entry in entries) == ["alpha", "beta"]
finally:
async with SessionFactory() as session, session.begin():
await session.execute(
text("DELETE FROM agent_intent_config WHERE agent_type=:agent"),
{"agent": agent_type},
)
await session.execute(text("DELETE FROM sys_user WHERE id=:id"), {"id": actor})