Files
smeta-web/tests/test_qa_fallback.py
T

255 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Справочный путь: дипсик отказал до первого текста → отвечает зайка.
Инцидент 24.09.2026: у дипсика кончились деньги (402), запасного у справочного пути не было,
и человек получал только маску «сервис недоступен». Сеть не нужна: транспорт подменён.
"""
import asyncio
import importlib
import logging
import os
import sys
import httpx
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
DS_KEY = "kluch-dipsika"
ZAIKA_KEY = "kluch-zaiki"
@pytest.fixture()
def env(tmp_path, monkeypatch):
for k in ("CB_FAIL_THRESHOLD", "CB_FAIL_WINDOW_S", "CB_COOLDOWN_S", "CB_PROBE_TTL_S"):
monkeypatch.delenv(k, raising=False)
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("SESSION_SECRET", "test-secret")
monkeypatch.chdir(ROOT)
import db
import provider_health as ph
import zaika_quota
importlib.reload(db)
db.init_db()
ph.reset()
import qa_fallback
importlib.reload(qa_fallback)
monkeypatch.setattr(zaika_quota, "_exhausted_until", 0.0)
monkeypatch.setattr(zaika_quota, "_cache", {"tried_at": 0.0, "ok_at": 0.0, "parsed": None})
def no_network():
raise RuntimeError("сети в проверках нет")
monkeypatch.setattr(zaika_quota, "fetch", no_network)
zaika = qa_fallback.Endpoint("glm", "glm-qa", "https://api.z.ai/api/coding/paas/v4",
ZAIKA_KEY, "glm-5.3")
monkeypatch.setattr(qa_fallback, "zaika_endpoint", lambda: zaika)
calls = {"deepseek": 0, "glm": 0}
script = {"deepseek": [("text", "ответ дипсика")], "glm": [("text", "ответ зайки")]}
async def fake_stream(ep, messages):
calls[ep.name] += 1
for kind, payload in script[ep.name]:
if isinstance(payload, BaseException):
raise payload
yield kind, payload
yield "usage", {"input_tokens": 7, "cache_read_input_tokens": 0, "output_tokens": 3,
"from": ep.name}
monkeypatch.setattr(qa_fallback, "stream_chat", fake_stream)
yield qa_fallback, ph, db, calls, script
ph.reset()
def primary(qf):
return qf.Endpoint("deepseek", "deepseek-qa", "https://api.deepseek.com/v1", DS_KEY,
"deepseek-flash")
def run(qf):
async def go():
return [e async for e in qf.stream_with_fallback(
[{"role": "user", "content": "вопрос"}], primary=primary(qf),
username="u@x", tab_id="t")]
return asyncio.run(go())
def refused(status, body=""):
import qa_fallback
return qa_fallback.ProviderRefused(status, body)
def kinds(events):
return [k for k, _ in events]
def test_402_before_text_goes_to_zaika(env):
"""Порча: не переходить к запасному → вместо ответа будет событие error."""
qf, ph, db, calls, script = env
script["deepseek"] = [("text", refused(402, '{"error":{"message":"Insufficient Balance"}}'))]
events = run(qf)
assert kinds(events) == ["text", "done"], events
assert events[0][1] == "ответ зайки"
def test_done_names_the_real_provider(env):
"""В учёт уходит тот, кто ответил. Порча: литерал deepseek-qa в done → красный."""
qf, ph, db, calls, script = env
script["deepseek"] = [("text", refused(402))]
done = dict(run(qf))["done"]
assert done["provider"] == "glm-qa"
assert done["model"] == "glm-5.3"
assert done["usage"]["from"] == "glm"
def test_primary_answer_is_labelled_as_deepseek(env):
qf, ph, db, calls, script = env
done = dict(run(qf))["done"]
assert done["provider"] == "deepseek-qa" and done["model"] == "deepseek-flash"
assert calls["glm"] == 0
@pytest.mark.parametrize("err", [
"401", "429", "503", "connect", "timeout"])
def test_any_failure_before_text_falls_back(env, err):
"""Порча: переключаться только на 402 → остальные отказы красные."""
qf, ph, db, calls, script = env
boom = {"401": refused(401), "429": refused(429), "503": refused(503),
"connect": httpx.ConnectError("x"), "timeout": httpx.ReadTimeout("x")}[err]
script["deepseek"] = [("text", boom)]
assert kinds(run(qf)) == ["text", "done"]
def test_no_switch_after_first_text(env):
"""Отданный текст не переигрываем — иначе два ответа склеятся.
Порча: переходить к зайке и после первого текста → её вызовут."""
qf, ph, db, calls, script = env
script["deepseek"] = [("text", "начало"), ("text", httpx.ReadError("обрыв"))]
events = run(qf)
assert kinds(events) == ["text", "error"], events
assert calls["glm"] == 0
def test_both_dead_gives_one_error_without_addresses_or_keys(env):
"""Порча: вставить в причину адрес или ключ → утечёт человеку в обход маски."""
import error_mask
qf, ph, db, calls, script = env
script["deepseek"] = [("text", refused(402, "Insufficient Balance"))]
script["glm"] = [("text", httpx.ConnectError("нет связи"))]
events = run(qf)
assert kinds(events) == ["error"], events
reason = events[0][1]
assert error_mask.looks_like_provider_error("Ошибка GLM API: " + reason)
for secret in ("api.deepseek.com", "api.z.ai", DS_KEY, ZAIKA_KEY):
assert secret not in reason
def test_dead_deepseek_opens_the_breaker_and_is_skipped(env):
"""Порча: не звать record_failure/attempt_gate → дипсика будут дёргать вечно."""
qf, ph, db, calls, script = env
script["deepseek"] = [("text", refused(402))]
for _ in range(3):
run(qf)
assert ph.snapshot()["deepseek"]["status"] == ph.OPEN
calls["deepseek"] = 0
assert kinds(run(qf)) == ["text", "done"]
assert calls["deepseek"] == 0
def test_success_closes_the_streak(env):
"""Порча: не звать record_success → счётчик сбоев копится и открывает цепь зря."""
qf, ph, db, calls, script = env
ph.record_failure("deepseek")
ph.record_failure("deepseek")
run(qf)
assert ph.snapshot()["deepseek"]["streak"] == 0
def test_probe_slot_is_released_when_the_person_leaves(env, monkeypatch):
"""Человек закрыл вкладку посреди ответа пробной попытки — вердикта нет, но слот пробы
обязан освободиться. Порча: убрать release_probe → зайка залипнет до TTL (21 минута)."""
qf, ph, db, calls, script = env
now = [1000.0]
monkeypatch.setattr(ph, "_now", lambda: now[0])
for _ in range(3):
ph.record_failure("glm")
now[0] += 61
script["deepseek"] = [("text", refused(402))]
script["glm"] = [("text", "начало"), ("text", "продолжение")]
async def go():
agen = qf.stream_with_fallback([{"role": "user", "content": "в"}], primary=primary(qf),
username="u@x", tab_id="t")
first = await agen.__anext__()
await agen.aclose()
return first
assert asyncio.run(go()) == ("text", "начало")
assert ph.snapshot()["glm"]["half_open_inflight"] is False
assert ph.snapshot()["glm"]["status"] == ph.HALF_OPEN
def test_quota_mark_skips_zaika(env):
"""Окно подписки исчерпано до сброса — зайку не зовём, вызов заведомо упадёт.
Порча: не смотреть отметку → зайку вызовут."""
import zaika_quota
qf, ph, db, calls, script = env
zaika_quota.mark_exhausted(zaika_quota.clock() + 300)
script["deepseek"] = [("text", refused(402))]
assert kinds(run(qf)) == ["error"]
assert calls["glm"] == 0
def test_zaika_quota_refusal_is_not_a_breaker_failure(env, monkeypatch):
"""Квотный отказ зайки — не поломка. Порча: всегда звать record_failure → счётчик 1."""
import zaika_quota
qf, ph, db, calls, script = env
monkeypatch.setattr(zaika_quota, "refresh", lambda: {
"known": True, "percent_used": 100, "reset_at": zaika_quota.clock() + 600})
script["deepseek"] = [("text", refused(402))]
script["glm"] = [("text", refused(429, '{"error":{"type":"rate_limit_error"}}'))]
run(qf)
assert ph.snapshot()["glm"]["streak"] == 0
assert zaika_quota.snapshot()["source"] == "refusal"
def test_operator_sees_the_switch(env, caplog):
"""Порча: не писать в журнал действий → переключение никто не увидит."""
qf, ph, db, calls, script = env
script["deepseek"] = [("text", refused(402, "Insufficient Balance"))]
with caplog.at_level(logging.WARNING, logger="smeta_web"):
run(qf)
assert "отказал до первого текста" in caplog.text
rows = db.get_audit_log(action="qa_fallback")
assert len(rows) == 1, rows
assert rows[0]["detail"].startswith("deepseek→glm: deepseek: HTTP 402")
def test_missing_zaika_key_is_honest(env, monkeypatch, caplog):
"""Порча: звать зайку с пустым ключом → лишний вызов вместо честного отказа."""
qf, ph, db, calls, script = env
monkeypatch.setattr(qf, "zaika_endpoint", lambda: qf.Endpoint(
"glm", "glm-qa", "https://api.z.ai/api/coding/paas/v4", "", "glm-5.3"))
script["deepseek"] = [("text", refused(402))]
with caplog.at_level(logging.WARNING, logger="smeta_web"):
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