fix: переадресация провайдера — отказ, сбой журнала не отменяет запасной путь (находки зайки)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
+9
-4
@@ -83,7 +83,8 @@ async def stream_chat(ep: Endpoint, messages: list) -> AsyncGenerator[tuple[str,
|
|||||||
async with client.stream("POST", f"{ep.base_url}/chat/completions",
|
async with client.stream("POST", f"{ep.base_url}/chat/completions",
|
||||||
headers={"Authorization": f"Bearer {ep.key}"},
|
headers={"Authorization": f"Bearer {ep.key}"},
|
||||||
json=request_body(ep.model, messages)) as resp:
|
json=request_body(ep.model, messages)) as resp:
|
||||||
if resp.status_code >= 400:
|
# httpx не идёт за переадресацией: 3xx — тоже отказ, а не пустой ответ.
|
||||||
|
if not 200 <= resp.status_code < 300:
|
||||||
raise ProviderRefused(resp.status_code,
|
raise ProviderRefused(resp.status_code,
|
||||||
(await resp.aread()).decode("utf-8", "replace"))
|
(await resp.aread()).decode("utf-8", "replace"))
|
||||||
async for line in resp.aiter_lines():
|
async for line in resp.aiter_lines():
|
||||||
@@ -160,9 +161,13 @@ async def stream_with_fallback(messages: list, *, primary: Endpoint, username: s
|
|||||||
nxt = chain[idx + 1].name
|
nxt = chain[idx + 1].name
|
||||||
_log.warning("справочный путь: %s отказал до первого текста (%s) — отвечает %s",
|
_log.warning("справочный путь: %s отказал до первого текста (%s) — отвечает %s",
|
||||||
ep.name, failure, nxt)
|
ep.name, failure, nxt)
|
||||||
import db
|
try:
|
||||||
await asyncio.to_thread(db.log_action, username, "qa_fallback", "STREAM", "/api/chat",
|
import db
|
||||||
f"{ep.name}→{nxt}: {failure}"[:200], None, 502)
|
await asyncio.to_thread(db.log_action, username, "qa_fallback", "STREAM",
|
||||||
|
"/api/chat", f"{ep.name}→{nxt}: {failure}"[:200], None, 502)
|
||||||
|
except Exception: # noqa: BLE001 — сбой журнала не отменяет спасение ответа
|
||||||
|
_log.warning("справочный путь: переключение не записано в журнал действий",
|
||||||
|
exc_info=True)
|
||||||
continue
|
continue
|
||||||
yield "error", failure
|
yield "error", failure
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -237,3 +237,18 @@ def test_missing_zaika_key_is_honest(env, monkeypatch, caplog):
|
|||||||
assert kinds(run(qf)) == ["error"]
|
assert kinds(run(qf)) == ["error"]
|
||||||
assert calls["glm"] == 0
|
assert calls["glm"] == 0
|
||||||
assert "нет ключа" in caplog.text
|
assert "нет ключа" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_broken_audit_log_does_not_cancel_the_rescue(env, monkeypatch, caplog):
|
||||||
|
"""Находка зайки: журнал действий упал (база занята) — зайка всё равно должна ответить.
|
||||||
|
Порча: писать в журнал без защиты → исключение вылетит наружу, человек без ответа."""
|
||||||
|
qf, ph, db, calls, script = env
|
||||||
|
|
||||||
|
def locked(*a, **k):
|
||||||
|
raise RuntimeError("database is locked")
|
||||||
|
|
||||||
|
monkeypatch.setattr(db, "log_action", locked)
|
||||||
|
script["deepseek"] = [("text", refused(402))]
|
||||||
|
with caplog.at_level(logging.WARNING, logger="smeta_web"):
|
||||||
|
assert kinds(run(qf)) == ["text", "done"]
|
||||||
|
assert "журнал" in caplog.text
|
||||||
|
|||||||
@@ -180,3 +180,13 @@ def test_stream_claude_reports_who_answered(monkeypatch, tmp_path):
|
|||||||
assert done["result"].startswith("ответ")
|
assert done["result"].startswith("ответ")
|
||||||
assert seen["primary"].label == "deepseek-qa"
|
assert seen["primary"].label == "deepseek-qa"
|
||||||
assert seen["primary"].base_url == cbg.ZAI_BASE_URL
|
assert seen["primary"].base_url == cbg.ZAI_BASE_URL
|
||||||
|
|
||||||
|
|
||||||
|
def test_redirect_is_a_refusal_not_an_answer(monkeypatch):
|
||||||
|
"""Находка зайки: httpx не идёт за переадресацией, и 3xx читался как пустой ответ без кода.
|
||||||
|
Порча: проверять только >= 400 → проверка упадёт."""
|
||||||
|
import qa_fallback
|
||||||
|
monkeypatch.setattr(httpx, "AsyncClient", fake_client({}, status=307, lines=[]))
|
||||||
|
with pytest.raises(qa_fallback.ProviderRefused) as e:
|
||||||
|
collect(qa_fallback.stream_chat(ep(), []))
|
||||||
|
assert str(e.value) == "HTTP 307"
|
||||||
|
|||||||
Reference in New Issue
Block a user