相对第一版 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(含失败关闭反证)。
127 lines
4.9 KiB
Python
127 lines
4.9 KiB
Python
"""SSE `Accept` 契约测试(文档 §3.2 请求头表 + §3.5 状态码 + §6.4 主要错误)。
|
||
|
||
权威规则:`Accept` **非必填**,"默认 `application/json`;SSE 为 `text/event-stream`",
|
||
`SSE_NOT_ACCEPTABLE` 是 SSE 接口的主要错误之一(406)。
|
||
|
||
覆盖两条容易写错的分支:
|
||
1. **未携带** `Accept` 必须放行——把"未携带"当成"不接受"会把所有默认客户端挡在门外;
|
||
2. `q=0` 属于显式拒绝,不能被通配符掩盖。
|
||
|
||
校验顺序另在 `stream_agent_run_events` 中做了断言:可见性(RUN_NOT_FOUND)先行,
|
||
否则 406/404 的差异就等于一次运行存在性枚举。
|
||
"""
|
||
|
||
from typing import Any
|
||
|
||
import pytest
|
||
from fastapi.testclient import TestClient
|
||
|
||
from app.api.controllers.agent_runs import accepts_event_stream
|
||
from app.api.dependencies.auth import build_request_context
|
||
from app.core.contracts import RequestContext
|
||
from app.core.errors import RunNotFoundError
|
||
from app.main import create_app
|
||
from app.service.run_query_service import RunSnapshot
|
||
|
||
EVENTS_PATH = "/api/v1/agent-runs/run-1/events"
|
||
|
||
|
||
async def resolve_context() -> RequestContext:
|
||
return RequestContext(user_id="1", trace_id="trace-1", permissions=("agent:run",))
|
||
|
||
|
||
def app_with_query(monkeypatch: pytest.MonkeyPatch, query: Any) -> TestClient:
|
||
application = create_app()
|
||
application.dependency_overrides[build_request_context] = resolve_context
|
||
monkeypatch.setattr("app.api.controllers.agent_runs.RunQueryService", lambda: query)
|
||
return TestClient(application)
|
||
|
||
|
||
class StubQuery:
|
||
"""`get` 返回终态快照、`watch` 立即收流,避免测试连接挂住。"""
|
||
|
||
def __init__(self, status: str = "succeeded") -> None:
|
||
self.status = status
|
||
|
||
async def get(self, run_id: str, _ctx: RequestContext) -> RunSnapshot:
|
||
return RunSnapshot(run_id=run_id, trace_id="trace-1", status=self.status,
|
||
agent_type="customer_service", session_id="s", result=None,
|
||
error_code=None, created_at="2026-01-01T00:00:00Z",
|
||
completed_at="2026-01-01T00:00:01Z")
|
||
|
||
async def watch(self, initial: RunSnapshot, _ctx: RequestContext):
|
||
yield initial
|
||
|
||
|
||
class MissingQuery:
|
||
async def get(self, _run_id: str, _ctx: RequestContext) -> RunSnapshot:
|
||
raise RunNotFoundError("运行不存在或不可见")
|
||
|
||
async def watch(self, initial: RunSnapshot, _ctx: RequestContext):
|
||
yield initial
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"accept",
|
||
[None, "", "*/*", "text/*", "text/event-stream", "text/event-stream;q=0.8",
|
||
"application/json, text/event-stream"],
|
||
)
|
||
def test_acceptable_or_absent_accept_is_allowed(accept: str | None) -> None:
|
||
assert accepts_event_stream(accept) is True
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"accept",
|
||
["application/json", "text/html", "application/json, text/html",
|
||
"*/*;q=0", "text/event-stream;q=0", "text/*;q=0, application/json"],
|
||
)
|
||
def test_explicitly_unacceptable_accept_is_rejected(accept: str) -> None:
|
||
assert accepts_event_stream(accept) is False
|
||
|
||
|
||
@pytest.mark.parametrize("accept", [None, "*/*", "text/event-stream"])
|
||
def test_missing_wildcard_and_exact_accept_are_allowed_by_endpoint(
|
||
monkeypatch: pytest.MonkeyPatch, accept: str | None
|
||
) -> None:
|
||
headers = {} if accept is None else {"Accept": accept}
|
||
with app_with_query(monkeypatch, StubQuery()) as client:
|
||
response = client.get(EVENTS_PATH, headers=headers)
|
||
|
||
assert response.status_code == 200
|
||
assert response.headers["content-type"].startswith("text/event-stream")
|
||
|
||
|
||
def test_json_only_accept_is_rejected_with_documented_code(
|
||
monkeypatch: pytest.MonkeyPatch
|
||
) -> None:
|
||
with app_with_query(monkeypatch, StubQuery()) as client:
|
||
response = client.get(EVENTS_PATH, headers={"Accept": "application/json"})
|
||
|
||
assert response.status_code == 406
|
||
assert response.json()["error"]["code"] == "SSE_NOT_ACCEPTABLE"
|
||
assert response.json()["error"]["retryable"] is False
|
||
assert response.json()["error"]["field_errors"] == []
|
||
|
||
|
||
def test_visibility_is_checked_before_accept(
|
||
monkeypatch: pytest.MonkeyPatch
|
||
) -> None:
|
||
"""不可见运行的非法 Accept 也必须得到 `RUN_NOT_FOUND`,不泄露存在性差异。"""
|
||
cases = [{"Accept": "application/json"}, {}]
|
||
for headers in cases:
|
||
with app_with_query(monkeypatch, MissingQuery()) as client:
|
||
response = client.get(EVENTS_PATH, headers=headers)
|
||
|
||
assert response.status_code == 404
|
||
assert response.json()["error"]["code"] == "RUN_NOT_FOUND"
|
||
|
||
|
||
def test_unacceptable_accept_does_not_start_a_stream(
|
||
monkeypatch: pytest.MonkeyPatch
|
||
) -> None:
|
||
"""拒绝必须发生在响应头发送前:文档 §6.4 要求此时返回统一 JSON 错误。"""
|
||
with app_with_query(monkeypatch, StubQuery()) as client:
|
||
response = client.get(EVENTS_PATH, headers={"Accept": "application/json"})
|
||
|
||
assert response.headers["content-type"].startswith("application/json")
|