Files
group_fqcd_jr/tests/integration/test_intent_config_runtime_mysql.py
T
lzf_0626 6516ccb385 feat: 第二版——接口契约对齐 docs/05,修复静默故障与数据库基线
相对第一版 46fc976 的完整变更。组员迁移对照表见 docs/20。

一、对外契约对齐 docs/05(破坏性,共 4 处,组员需按 docs/20 调整)
1) 配置发布端点改为文档规定的复数资源名:submit→validations、
   approve→reviews(需 body decision)、activate→activations、
   rollback→rollbacks;第一版这 4 个动词式路径 docs/05 从未定义过。
2) 错误码由 8 个笼统码改为 15 个具体语义码(FORBIDDEN→AGENT_PERMISSION_DENIED、
   UNAUTHORIZED→AUTHENTICATION_REQUIRED、CONFLICT→RESOURCE_VERSION_CONFLICT、
   RESOURCE_NOT_FOUND→RUN_NOT_FOUND/SESSION_NOT_FOUND 等),
   输入类错误状态码 400→422。
3) POST /api/v1/agent-runs 与 GET /api/v1/agent-runs/{run_id} 统一为
   {data, meta} 信封(data 内字段名与语义未变)。
4) 错误响应体统一为 {error:{code,message,retryable,field_errors}, meta:{trace_id}},
   不再返回 FastAPI 默认的 {"detail": ...}。

二、数据库基线与约束
新增 39 张表的基线迁移(链根)与联合唯一键纠偏(4 张表、删 8 增 4,幂等收敛);
撤下 config_release 的双人复核 CHECK(应用层已允许自审,审核节点保留,
自审如实写入 reviewer_id);记忆 active key 生成列与唯一键;
activate 开始记录 supersedes_release_id 使版本链可追溯。
docs/00 基线未修改,未重命名或删除任何表与字段。

三、修复会静默出错或无报错的缺陷
- 跑完集成测试后平台会静默失去生效配置:清理只删自己创建的版本,却没有恢复被它
  顶成 superseded 的原生效版本,且审计一并删除因而完全无痕,表现为所有工具被拒
  但没有任何报错。已修清理逻辑并加恢复。
- Worker 单轮异常导致进程退出;记忆抽取调用方的“事务已开始”异常;
  召回缓存丢失 degraded 标记;连接时区未生效导致 created_at/updated_at 差 8 小时;
  .env 与 os.getenv 密钥来源分裂导致“没有可用的已批准模型端点”。
- 记忆信号识别漏判与跨键误命中;SSE 未带 Accept 的协商行为。

四、功能补齐
记忆链路 P1/P2/P3(抽取、受控词表、召回与缓存、生命周期级联及投影事件)、
fin_* 场内交易只读 ORM 层、agent_intent_config 状态流转并在运行期真正生效、
限流(Redis 固定窗口、故障一律放行)、游标校验、trace_id 中间件、
示例业务 Agent fund_query_demo 与一键端到端验证脚本,以及审计/指纹/迁移状态工具。

五、文档与验证
新增 docs/19(业务 Agent 接入实操)、docs/20(第一版迁移指南)与 docs/evidence 证据;
docs/01/02/06/08/09/17 同步实现现状。

验证结果:ruff 通过、mypy 103 文件无错、unit+contract 447 passed、
integration 29 passed、acceptance_check --production 7 PASS、
demo_agent_e2e 9/9 PASS(含失败关闭反证)。
2026-09-10 15:55:54 +08:00

117 lines
5.6 KiB
Python

"""真实 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})