From 58bb6a3406948ee7310ee42517dfe7081856e74c Mon Sep 17 00:00:00 2001 From: anor Date: Thu, 24 Sep 2026 02:22:07 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B0=D0=B4?= =?UTF-8?q?=D1=80=D0=B5=D1=81=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=B9=D0=B4=D0=B5=D1=80=D0=B0=20=E2=80=94=20=D0=BE?= =?UTF-8?q?=D1=82=D0=BA=D0=B0=D0=B7,=20=D1=81=D0=B1=D0=BE=D0=B9=20=D0=B6?= =?UTF-8?q?=D1=83=D1=80=D0=BD=D0=B0=D0=BB=D0=B0=20=D0=BD=D0=B5=20=D0=BE?= =?UTF-8?q?=D1=82=D0=BC=D0=B5=D0=BD=D1=8F=D0=B5=D1=82=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=BF=D1=83=D1=82=D1=8C=20(?= =?UTF-8?q?=D0=BD=D0=B0=D1=85=D0=BE=D0=B4=D0=BA=D0=B8=20=D0=B7=D0=B0=D0=B9?= =?UTF-8?q?=D0=BA=D0=B8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 (1M context) --- qa_fallback.py | 13 +++++++++---- tests/test_qa_fallback.py | 15 +++++++++++++++ tests/test_qa_fallback_transport.py | 10 ++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/qa_fallback.py b/qa_fallback.py index 1458002..2c86490 100644 --- a/qa_fallback.py +++ b/qa_fallback.py @@ -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", headers={"Authorization": f"Bearer {ep.key}"}, 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, (await resp.aread()).decode("utf-8", "replace")) 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 _log.warning("справочный путь: %s отказал до первого текста (%s) — отвечает %s", ep.name, failure, nxt) - import db - await asyncio.to_thread(db.log_action, username, "qa_fallback", "STREAM", "/api/chat", - f"{ep.name}→{nxt}: {failure}"[:200], None, 502) + try: + import db + 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 yield "error", failure return diff --git a/tests/test_qa_fallback.py b/tests/test_qa_fallback.py index bddcf67..3f43fc4 100644 --- a/tests/test_qa_fallback.py +++ b/tests/test_qa_fallback.py @@ -237,3 +237,18 @@ def test_missing_zaika_key_is_honest(env, monkeypatch, caplog): assert kinds(run(qf)) == ["error"] assert calls["glm"] == 0 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 diff --git a/tests/test_qa_fallback_transport.py b/tests/test_qa_fallback_transport.py index f58a5bd..628d51c 100644 --- a/tests/test_qa_fallback_transport.py +++ b/tests/test_qa_fallback_transport.py @@ -180,3 +180,13 @@ def test_stream_claude_reports_who_answered(monkeypatch, tmp_path): assert done["result"].startswith("ответ") assert seen["primary"].label == "deepseek-qa" 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"