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"