fix(agent): retry knowledge queries on transport failures (#7507)

Widen the knowledge query budget to 23 seconds with up to three 7.5-second attempts. Reconnect for bounded retries on transport failures while preserving HTTP and protocol errors. Cover slow search/read responses, retry recovery, cancellation and exhaustion, and document the contract.

Closes #7502
This commit is contained in:
jxxghp
2026-11-21 08:27:52 +08:00
committed by GitHub
parent d58867c7b9
commit d785c98f1a
4 changed files with 173 additions and 25 deletions

View File

@@ -1,7 +1,8 @@
"""
中心知识协议的只读 HTTPS 适配器,不缓存、不重放、不回显中心错误正文。
中心知识协议的只读 HTTPS 适配器,不缓存、有限重试传输故障、不回显中心错误正文。
"""
import asyncio
from collections.abc import Mapping
from typing import Any, Literal, Optional, Protocol, Union
@@ -10,7 +11,6 @@ from pydantic import ValidationError
from app.adapters.network.http import AsyncHttpRequestError, AsyncRequestUtils
from app.runtime.settings import get_runtime_setting
from app.schemas.knowledge import (
QUERY_SECONDS,
AgentKnowledgeConfig,
KnowledgeFailure,
KnowledgeOutcome,
@@ -20,6 +20,9 @@ from app.schemas.knowledge import (
)
MAX_RESPONSE_BYTES = 96 * 1024
# 单轮覆盖中心约 7 秒的正常慢响应,三轮仍受服务层 23 秒总预算约束。
QUERY_ATTEMPT_SECONDS = 7.5
QUERY_MAX_RETRIES = 2
_HTTP_FAILURES: dict[int, KnowledgeFailure] = {
401: "unauthorized", 403: "forbidden", 410: "reference_expired", 413: "invalid_request",
415: "invalid_request", 422: "invalid_request", 429: "rate_limited", 503: "unavailable",
@@ -39,11 +42,42 @@ class KnowledgeClient:
"""
self._transport = transport
async def _post(self, url: str, payload: dict[str, Any]) -> Optional["KnowledgeHttpResponse"]:
"""
对固定只读接口执行有界传输重试,每次生产请求都建立新连接。
:param url: 当前知识中心固定协议地址
:param payload: 已校验且不含用户凭据的协议请求
:return: 收到的 HTTP 响应;请求失败或无响应时为 None
"""
for attempt in range(QUERY_MAX_RETRIES + 1):
transport = self._transport or AsyncRequestUtils(
proxies=get_runtime_setting("PROXY"), http2=False, timeout=QUERY_ATTEMPT_SECONDS,
verify=True, follow_redirects=False, trust_env=False, max_keepalive_connections=0,
)
try:
async with asyncio.timeout(QUERY_ATTEMPT_SECONDS):
response = await transport.post_res(
url, json=payload, allow_redirects=False, raise_exception=True,
headers={"Accept": "application/json", "Content-Type": "application/json",
"Accept-Encoding": "identity"},
)
except (AsyncHttpRequestError, OSError):
# asyncio.timeout 的 TimeoutError 同属 OSError;取消当前尝试后才重试。
if attempt < QUERY_MAX_RETRIES:
continue
return None
except ValueError:
return None
if response is not None:
return response
return None
async def query(
self, config: AgentKnowledgeConfig, request: Union[KnowledgeSearch, KnowledgeRead],
) -> KnowledgeOutcome:
"""
固定路径、校验证书并关闭跳转;不携带 Cookie 或用户身份令牌。
固定路径、校验证书并关闭跳转;传输失败时有界重试,不携带 Cookie 或用户身份令牌。
:param config: 当前 Server 源和本地工具开关
:param request: 宿主验证的检索或补读请求,不接受任意路径
@@ -55,19 +89,9 @@ class KnowledgeClient:
origin = config.origin.rstrip("/")
if not origin:
return KnowledgeOutcome("unavailable")
transport = self._transport or AsyncRequestUtils(
proxies=get_runtime_setting("PROXY"), http2=False, timeout=QUERY_SECONDS, verify=True,
follow_redirects=False, trust_env=False,
response = await self._post(
f"{origin}/knowledge/v1/{path}", request.model_dump(mode="json"),
)
try:
response = await transport.post_res(
f"{origin}/knowledge/v1/{path}", json=request.model_dump(mode="json"),
allow_redirects=False, raise_exception=True,
headers={"Accept": "application/json", "Content-Type": "application/json",
"Accept-Encoding": "identity"},
)
except (AsyncHttpRequestError, OSError, ValueError):
return KnowledgeOutcome("unavailable")
if response is None:
return KnowledgeOutcome("unavailable")
try:

View File

@@ -16,7 +16,8 @@ KnowledgeFailure = Literal[
"disabled", "configuration_changed", "unauthorized", "forbidden", "reference_expired",
"rate_limited", "unavailable", "invalid_request", "invalid_response", "timeout",
]
QUERY_SECONDS = 3.0
# 覆盖 7.5 秒单次预算的首轮请求与两次重试,并为调度留出余量。
QUERY_SECONDS = 23.0
EvidenceIdentifier = Annotated[str, Field(pattern=r"^ke_[A-Za-z0-9_-]{43}$")]

View File

@@ -711,8 +711,9 @@ Agent 使用既有 `MP_SERVER_HOST` 连接 MoviePilot Server,不需要填写
发布后的知识只读,后台来源凭据不会随检索响应返回。
Agent 使用固定 `/knowledge/v1/agent/search` 与 `/knowledge/v1/agent/read` 路径,校验 TLS、关闭重定向、
不自动重放 POST,也不发送站点 Cookie、登录 Cookie、API Key 或用户 UID。单次查询总预算 3 秒、
搜索最多 3 条且每条最多 1600 字符、补读最多 1 条 4000 字符;总正文预算 6000 字符。96 KiB 响应检查
也不发送站点 Cookie、登录 Cookie、API Key 或用户 UID。两条协议路径均为固定只读 POST:传输失败时单次预算为 7.5 秒,
最多重试 2 次,总预算 23 秒;每轮重试都建立新连接,不重试 HTTP 错误或协议无效响应。搜索最多 3 条且每条最多 1600 字符、
补读最多 1 条 4000 字符;总正文预算 6000 字符。96 KiB 响应检查
发生在宿主 HTTP 层缓冲之后,不代表传输前的硬内存上限。请求途中开关或 Server 地址变化会丢弃迟到结果。
Agent 仅在回答 MoviePilot 使用、配置、开发、故障或 PT 站点规则时检索;问候、闲聊和普通常识不触发。

View File

@@ -10,7 +10,12 @@ import httpx2
import pytest
from pydantic import ValidationError
from app.adapters.external.knowledge import MAX_RESPONSE_BYTES, KnowledgeClient
from app.adapters.external.knowledge import (
MAX_RESPONSE_BYTES,
QUERY_ATTEMPT_SECONDS,
QUERY_MAX_RETRIES,
KnowledgeClient,
)
from app.adapters.network.http import AsyncRequestUtils
from app.application.knowledge import KnowledgeService
from app.runtime.config import Settings
@@ -62,7 +67,7 @@ def _requester(client):
:param client: 由测试管理的合成传输客户端
:return: 不跟随跳转、验证 TLS 且禁用环境代理继承的宿主请求器
"""
return AsyncRequestUtils(client=client, http2=False, timeout=3, verify=True,
return AsyncRequestUtils(client=client, http2=False, timeout=QUERY_ATTEMPT_SECONDS, verify=True,
follow_redirects=False, trust_env=False)
@@ -244,10 +249,10 @@ async def test_invalid_encoding_type_or_buffered_size_is_rejected(response):
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["connect", "timeout"])
async def test_transport_failures_are_sanitized_and_not_retried(kind):
@pytest.mark.parametrize("kind", ["connect", "timeout", "os", "empty", "invalid"])
async def test_transport_failures_are_sanitized_and_retried_within_a_bound(kind):
"""
传输异常不回显可能含凭据的异常文本,POST 失败也不自动重放。
只读请求在传输异常后有限重试,最终失败不回显可能含凭据的异常文本。
"""
calls = []
@@ -259,13 +264,130 @@ async def test_transport_failures_are_sanitized_and_not_retried(kind):
:return: 始终抛出合成网络错误
"""
calls.append(request)
if kind == "os":
raise OSError(SENTINEL)
if kind == "invalid":
raise ValueError(SENTINEL)
error = httpx2.ReadTimeout if kind == "timeout" else httpx2.ConnectError
raise error(SENTINEL, request=request)
async with httpx2.AsyncClient(transport=httpx2.MockTransport(handle)) as http:
result = await KnowledgeClient(_requester(http)).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则"))
transport = _requester(http)
if kind == "empty":
transport = MagicMock(post_res=AsyncMock(return_value=None))
result = await KnowledgeClient(transport).query(AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则"))
assert result == KnowledgeOutcome("unavailable")
assert len(calls) == 1 and SENTINEL not in repr(result)
expected_calls = 1 if kind == "invalid" else QUERY_MAX_RETRIES + 1
assert (transport.post_res.await_count if kind == "empty" else len(calls)) == expected_calls
assert SENTINEL not in repr(result)
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ["search", "read"])
async def test_transient_transport_failure_retries_and_success_uses_fresh_connection(monkeypatch, operation):
"""
短暂连接故障后重试成功,并关闭连接复用以便新请求重新解析 DNS。
"""
calls = []
options = []
def handle(request):
"""
通过真实宿主请求器回放一次连接故障和后续的正常中心响应。
:param request: 宿主构造的固定路径只读请求
:return: 重试后返回的有效中心响应
"""
calls.append(request)
if len(calls) == 1:
raise httpx2.ConnectError(SENTINEL, request=request)
return httpx2.Response(200, json=_reply())
def create_transport(**kwargs):
"""
捕获生产请求器选项并返回离线合成传输。
:param kwargs: 请求器生产配置
:return: 用于合成响应的传输
"""
options.append(kwargs)
return AsyncRequestUtils(client=http, **kwargs)
monkeypatch.setattr("app.adapters.external.knowledge.AsyncRequestUtils", create_transport)
payload = KnowledgeSearch(query="规则") if operation == "search" else KnowledgeRead(evidence_id=REFERENCE)
async with httpx2.AsyncClient(transport=httpx2.MockTransport(handle)) as http:
result = await KnowledgeClient().query(AgentKnowledgeConfig(**_config()), payload)
assert not http.is_closed
assert result.status == "matched"
assert len(calls) == 2
assert all(str(request.url) == f"{ORIGIN}/knowledge/v1/agent/{operation}" for request in calls)
assert calls[0].content == calls[1].content
assert len(options) == 2
assert all(option["timeout"] == QUERY_ATTEMPT_SECONDS for option in options)
assert all(option["max_keepalive_connections"] == 0 for option in options)
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ["search", "read"])
async def test_service_accepts_slow_response_within_total_budget(operation):
"""
5.5 秒的有效中心响应在适配器和服务总预算内都能正常返回。
"""
observed = []
async def handle(request):
"""
通过真实宿主 HTTP 请求器回放 5.5 秒后返回的中心响应。
:param request: 宿主构造的固定路径只读请求
:return: 合成的有效中心响应
"""
observed.append(request)
await asyncio.sleep(5.5)
return httpx2.Response(200, json=_reply())
async with httpx2.AsyncClient(transport=httpx2.MockTransport(handle)) as http:
port = KnowledgeClient(_requester(http))
service = KnowledgeService(lambda: AgentKnowledgeConfig(**_config()), port, lambda: "3.2.9")
result = await service.search("慢响应测试") if operation == "search" else await service.read(REFERENCE)
assert result.status == "matched"
assert len(observed) == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("recover", [True, False])
async def test_attempt_deadline_cancels_stalled_request_before_retry(monkeypatch, recover):
"""
单次请求卡住时先取消并释放该次等待,再有限重试或返回不可用。
"""
observed = []
cancelled = []
async def handle(request):
"""
用可取消等待模拟卡住的连接,并按用例选择让第二次请求恢复。
:param request: 当前合成请求
:return: 恢复后的有效中心响应
"""
observed.append(request)
assert len(cancelled) == len(observed) - 1
if recover and len(observed) == 2:
return httpx2.Response(200, json=_reply())
try:
await asyncio.Event().wait()
finally:
cancelled.append(request)
monkeypatch.setattr("app.adapters.external.knowledge.QUERY_ATTEMPT_SECONDS", 0.01)
async with httpx2.AsyncClient(transport=httpx2.MockTransport(handle)) as http:
result = await asyncio.wait_for(KnowledgeClient(_requester(http)).query(
AgentKnowledgeConfig(**_config()), KnowledgeSearch(query="规则"),
), timeout=1)
assert result.status == ("matched" if recover else "unavailable")
assert len(observed) == (2 if recover else QUERY_MAX_RETRIES + 1)
assert len(cancelled) == (1 if recover else QUERY_MAX_RETRIES + 1)
@pytest.mark.asyncio