fix: справочный путь уходит на зайку при отказе дипсика, сторож видит пустой счёт, телеграм через впн сервера

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-09-24 02:14:23 +10:00
co-authored by Claude Opus 5.5
parent f7b1aebe07
commit 454108655b
7 changed files with 267 additions and 97 deletions
+10 -2
View File
@@ -13,10 +13,18 @@ import time
_log = logging.getLogger("smeta_web") _log = logging.getLogger("smeta_web")
def tg_proxy() -> str | None:
"""Местный вход впн для Телеграма (TG_PROXY_URL). Напрямую с сервера до api.telegram.org
доходит треть запросов, через впн — все (замер 24.09.2026). Прокси из окружения не берём
(trust_env=False): там адрес для песочницы агента, а не для Телеграма."""
return os.environ.get("TG_PROXY_URL", "").strip() or None
def _post(url: str, data: dict) -> int: def _post(url: str, data: dict) -> int:
"""Выделено для тестов (мокается). Прямой доступ, без прокси — как канарейка.""" """Выделено для тестов (мокается)."""
import httpx import httpx
r = httpx.post(url, data=data, timeout=5, trust_env=False) kw = {"proxy": tg_proxy()} if tg_proxy() else {}
r = httpx.post(url, data=data, timeout=5, trust_env=False, **kw)
return r.status_code return r.status_code
+17 -54
View File
@@ -13,8 +13,6 @@ import re
from pathlib import Path from pathlib import Path
from typing import AsyncGenerator from typing import AsyncGenerator
import httpx
from path_safety import safe_work_dir from path_safety import safe_work_dir
_log = logging.getLogger("smeta_web") _log = logging.getLogger("smeta_web")
@@ -33,6 +31,7 @@ from chat_context import history_messages
# Инжекты новых БД (матрица БИМ / базисные ФСНБ / региональные ФГИС ЦС) + общие # Инжекты новых БД (матрица БИМ / базисные ФСНБ / региональные ФГИС ЦС) + общие
# хелперы разбора вопроса, переехавшие туда из этого модуля. # хелперы разбора вопроса, переехавшие туда из этого модуля.
import qa_fallback
import qa_inject import qa_inject
from qa_inject import _bim_extract_quarter from qa_inject import _bim_extract_quarter
@@ -1040,59 +1039,23 @@ async def stream_claude(
+ [{"role": "user", "content": user_content}] + [{"role": "user", "content": user_content}]
) )
# Stream from GLM API # Дипсик, при его отказе до первого текста — зайка (qa_fallback, инцидент 24.09.2026).
full_response = "" full_response = ""
_qa_usage: dict = {} _qa_usage: dict = {}
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") _provider, _model = "deepseek-qa", ZAI_MODEL
try: primary = qa_fallback.Endpoint("deepseek", "deepseek-qa", ZAI_BASE_URL, ZAI_API_KEY, ZAI_MODEL)
async with httpx.AsyncClient(timeout=120, proxy=proxy) as client: async for kind, payload in qa_fallback.stream_with_fallback(
resp = await client.post( messages, primary=primary, username=username, tab_id=tab_id):
f"{ZAI_BASE_URL}/chat/completions", if kind == "text":
headers={"Authorization": f"Bearer {ZAI_API_KEY}"}, full_response += payload
json={ yield f"event: text\ndata: {json.dumps({'text': payload}, ensure_ascii=False)}\n\n"
"model": ZAI_MODEL, elif kind == "done":
"messages": messages, _qa_usage, _provider, _model = payload["usage"], payload["provider"], payload["model"]
"stream": True, else:
# usage в финальном чанке стрима (OpenAI-совм.) — питает учёт llm_usage (Ф2). # Префикс «Ошибка GLM API» — сигнатура маски error_mask: main подменит его заглушкой.
"stream_options": {"include_usage": True}, error_msg = f"Ошибка GLM API: {payload}"
"temperature": 0.1, yield f"event: text\ndata: {json.dumps({'text': error_msg}, ensure_ascii=False)}\n\n"
"max_tokens": 4096, full_response = error_msg
"thinking": {"type": "disabled"},
},
)
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
data_str = line[6:]
if data_str == "[DONE]":
break
try:
chunk = json.loads(data_str)
if chunk.get("usage"):
# финальный usage-чанк (choices пуст) — переводим в Anthropic-формат Ф2
_qa_usage = {
"input_tokens": chunk["usage"].get("prompt_tokens", 0),
"cache_read_input_tokens":
(chunk["usage"].get("prompt_tokens_details") or {}).get("cached_tokens", 0),
"output_tokens": chunk["usage"].get("completion_tokens", 0),
}
if not chunk.get("choices"):
continue
delta = chunk["choices"][0].get("delta", {})
# GLM-5.1: skip reasoning_content (internal thinking), use only content
text = delta.get("content", "")
if text:
full_response += text
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
except (json.JSONDecodeError, KeyError, IndexError):
continue
except Exception as e:
error_msg = f"Ошибка GLM API: {e}"
yield f"event: text\ndata: {json.dumps({'text': error_msg}, ensure_ascii=False)}\n\n"
full_response = error_msg
# Детерминированная проверка шифров (faithfulness-слой поверх промпт-guard). # Детерминированная проверка шифров (faithfulness-слой поверх промпт-guard).
# Не зависит от послушания LLM; показывает только уверенные HARD-случаи # Не зависит от послушания LLM; показывает только уверенные HARD-случаи
@@ -1119,7 +1082,7 @@ async def stream_claude(
# usage/provider/model — учёт стоимости Ф2 (суффикс '-qa' → path='qa' в llm_usage). # usage/provider/model — учёт стоимости Ф2 (суффикс '-qa' → path='qa' в llm_usage).
yield ("event: done\ndata: " + json.dumps( yield ("event: done\ndata: " + json.dumps(
{"result": full_response, "usage": _qa_usage, {"result": full_response, "usage": _qa_usage,
"provider": "deepseek-qa", "model": ZAI_MODEL}, ensure_ascii=False) + "\n\n") "provider": _provider, "model": _model}, ensure_ascii=False) + "\n\n")
def list_user_files(username: str, tab_id: str = "default") -> list[dict]: def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
+7 -4
View File
@@ -254,11 +254,14 @@ def check_providers() -> Check:
import asyncio import asyncio
import provider_health import provider_health
bad = [] bad, alive = [], []
for name in checkable: for name in checkable:
if not asyncio.run(provider_health.ping_provider(name)): ok, why = asyncio.run(provider_health.probe_provider(name))
bad.append(name) (alive if ok else bad).append(f"{name} — {why}")
detail = ("ключ не отвечает: " + ", ".join(bad)) if bad else "ключи живы: " + ", ".join(checkable) if bad:
detail = "мёртв: " + "; ".join(bad) + (" | жив: " + "; ".join(alive) if alive else "")
else:
detail = "ключи живы: " + "; ".join(alive)
if unknown: if unknown:
detail += "; проба не описана: " + ", ".join(unknown) detail += "; проба не описана: " + ", ".join(unknown)
return Check("providers", not bad, detail) return Check("providers", not bad, detail)
+46 -31
View File
@@ -268,19 +268,44 @@ async def _tick() -> None:
async def ping_provider(name: str) -> bool: async def ping_provider(name: str) -> bool:
"""Проба живости нужного провайдера. Адрес и ключ — свои у каждого: общий пинг стучался """Проба живости нужного провайдера — только вердикт, для монитора размыкателя."""
return (await probe_provider(name))[0]
async def probe_provider(name: str) -> tuple[bool, str]:
"""Проба живости с причиной. Адрес и ключ — свои у каждого: общий пинг стучался
бы к дипсику и подтверждал бы жизнь зайки, пока она лежит.""" бы к дипсику и подтверждал бы жизнь зайки, пока она лежит."""
if name == "glm": if name == "glm":
key = os.environ.get("ZAI_GLM_API_KEY") or _key_from_settings("AGENT_SETTINGS_GLM", "glm") key = os.environ.get("ZAI_GLM_API_KEY") or _key_from_settings("AGENT_SETTINGS_GLM", "glm")
base = os.environ.get("GLM_PING_BASE", "https://api.z.ai/api/anthropic") base = os.environ.get("GLM_PING_BASE", "https://api.z.ai/api/anthropic")
return await _http_ok(f"{base}/v1/messages", key, method="POST") return await _http_probe(f"{base}/v1/messages", key, method="POST")
if name == "deepseek": if name == "deepseek":
key = (os.environ.get("DEEPSEEK_API_KEY") or os.environ.get("ZAI_API_KEY") key = (os.environ.get("DEEPSEEK_API_KEY") or os.environ.get("ZAI_API_KEY")
or _key_from_settings("AGENT_SETTINGS_DEEPSEEK", "deepseek")) or _key_from_settings("AGENT_SETTINGS_DEEPSEEK", "deepseek"))
base = os.environ.get("DEEPSEEK_PING_BASE", "https://api.deepseek.com") base = os.environ.get("DEEPSEEK_PING_BASE", "https://api.deepseek.com")
return await _http_ok(f"{base}/user/balance", key, method="GET") return await _http_probe(f"{base}/user/balance", key, method="GET",
verdict=_deepseek_verdict)
_log.warning("проба для неизвестного провайдера %s не описана", name) _log.warning("проба для неизвестного провайдера %s не описана", name)
return False return False, "проба не описана"
def _deepseek_verdict(r) -> tuple[bool, str]:
"""Ручка остатка отвечает 200 и при пустом счёте (24.09.2026: is_available false,
остаток -0.05 USD) — жив лишь тот, у кого is_available true. Непонятный ответ = мёртв."""
if r.status_code != 200:
return False, f"HTTP {r.status_code}"
try:
body = r.json()
except Exception: # noqa: BLE001
return False, "ответ ручки остатка не разобран"
if not isinstance(body, dict) or "is_available" not in body:
return False, "в ответе ручки нет is_available"
infos = [i for i in (body.get("balance_infos") or []) if isinstance(i, dict)]
info = next((i for i in infos if i.get("currency") == "USD"), infos[0] if infos else None)
left = f"{info.get('total_balance')} {info.get('currency')}" if info else "неизвестен"
if body["is_available"] is True:
return True, f"остаток {left}"
return False, f"нет денег на счёте (остаток {left})"
def _key_from_settings(env_name: str, provider: str = "") -> str: def _key_from_settings(env_name: str, provider: str = "") -> str:
@@ -312,12 +337,17 @@ def _key_from_settings(env_name: str, provider: str = "") -> str:
async def _http_ok(url: str, key: str, *, method: str = "GET") -> bool: async def _http_ok(url: str, key: str, *, method: str = "GET") -> bool:
"""Один дешёвый запрос: 200 = провайдер отвечает. Нет ключа, не-200 или сетевой сбой → return (await _http_probe(url, key, method=method))[0]
False (не подтвердили → держим цепь разомкнутой)."""
async def _http_probe(url: str, key: str, *, method: str = "GET",
verdict=None) -> tuple[bool, str]:
"""Один дешёвый запрос: 200 = провайдер отвечает (или решает verdict). Нет ключа,
не-200 или сетевой сбой → не подтверждён (держим цепь разомкнутой)."""
import httpx import httpx
if not key: if not key:
return False return False, "ключ не задан"
# Пустая переменная прокси — частое дело в контейнерах; пустая строка вместо адреса # Пустая переменная прокси — частое дело в контейнерах; пустая строка вместо адреса
# роняет запрос, и провайдер ложно числится мёртвым. # роняет запрос, и провайдер ложно числится мёртвым.
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or None proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or None
@@ -331,30 +361,15 @@ async def _http_ok(url: str, key: str, *, method: str = "GET") -> bool:
"max_tokens": 1, "messages": [{"role": "user", "content": "."}]}) "max_tokens": 1, "messages": [{"role": "user", "content": "."}]})
else: else:
r = await client.get(url, headers={"Authorization": f"Bearer {key}"}) r = await client.get(url, headers={"Authorization": f"Bearer {key}"})
return r.status_code == 200 except Exception as e: # noqa: BLE001 — сетевые сбои = «не подтверждён»
except Exception: # noqa: BLE001 — сетевые сбои = «не подтверждён» return False, f"сеть: {type(e).__name__}"
return False if verdict is not None:
return verdict(r)
return (True, "отвечает") if r.status_code == 200 else (False, f"HTTP {r.status_code}")
async def _ping_deepseek() -> bool: async def _ping_deepseek() -> bool:
"""Дешёвый пинг DeepSeek с хоста: GET /user/balance (0 токенов, любой ответ """Пинг DeepSeek с хоста: GET /user/balance (0 токенов) — «сеть + ключ + деньги». НЕ
200 = жив) — проверяет «сеть + ключ + аккаунт». НЕ проверяет контейнерный проверяет контейнерный anthropic-путь (settings/tinyproxy) — потому ping OK ведёт только
anthropic-путь (settings/tinyproxy) — потому ping OK ведёт только в в HALF_OPEN, а CLOSED требует реального commit пробы (false-close guard)."""
HALF_OPEN, а CLOSED требует реального commit пробы (false-close guard). return (await probe_provider("deepseek"))[0]
Нет ключа / не-200 / исключение → False (не можем подтвердить → держим OPEN).
Хост имеет прямой outbound к api.deepseek.com (изоляция --internal+tinyproxy —
только для docker-контейнера агента, не для FastAPI-процесса)."""
import httpx
key = (os.environ.get("DEEPSEEK_API_KEY") or os.environ.get("ZAI_API_KEY")
or _key_from_settings("AGENT_SETTINGS_DEEPSEEK", "deepseek"))
if not key:
return False
base = os.environ.get("DEEPSEEK_PING_BASE", "https://api.deepseek.com")
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
try:
async with httpx.AsyncClient(timeout=10, proxy=proxy) as client:
r = await client.get(f"{base}/user/balance",
headers={"Authorization": f"Bearer {key}"})
return r.status_code == 200
except Exception: # noqa: BLE001 — сетевые сбои = «не подтверждён»
return False
+169
View File
@@ -0,0 +1,169 @@
"""Справочный путь: основной провайдер и запасной.
Дипсик (OpenAI-совместимый /chat/completions) отказал ДО первого отданного текста — 402, 401,
429, 5xx, сеть — и тот же запрос уходит зайке по подписке (OpenAI-совместимый вход Coding
Plan). Уже отданный текст не переигрываем: два ответа склеились бы в один.
Инцидент 24.09.2026: у дипсика кончились деньги, а у справочного пути запасного не было —
человек получал только маску «сервис недоступен».
"""
import asyncio
import json
import logging
import os
import re
from dataclasses import dataclass
from typing import AsyncGenerator
import httpx
import provider_health
import zaika_quota
_log = logging.getLogger("smeta_web")
# Вход подписки Coding Plan: у потокового входа z.ai «нет баланса», работает только этот.
ZAIKA_BASE_URL = os.environ.get("QA_FALLBACK_BASE_URL", "https://api.z.ai/api/coding/paas/v4")
@dataclass(frozen=True)
class Endpoint:
name: str # имя для размыкателя: "deepseek" | "glm"
label: str # подпись в учёте: суффикс -qa уводит строку на путь qa
base_url: str
key: str
model: str
class ProviderRefused(Exception):
"""Провайдер ответил не-2xx. В тексте код и начало тела — без адреса и ключа, чтобы
причина годилась и в журнал, и в маску."""
def __init__(self, status: int, body: str = ""):
self.status, self.body = status, body
snippet = re.sub(r"\s+", " ", body or "").strip()[:160]
super().__init__(f"HTTP {status}" + (f" — {snippet}" if snippet else ""))
def describe(e: BaseException) -> str:
if isinstance(e, ProviderRefused):
return str(e)
# Текст сетевых ошибок httpx бывает с адресом — берём только имя класса.
return type(e).__name__
def zaika_endpoint() -> Endpoint:
import agent_provider
key = (os.environ.get("ZAI_GLM_API_KEY")
or provider_health._key_from_settings("AGENT_SETTINGS_GLM", "glm"))
return Endpoint("glm", "glm-qa", ZAIKA_BASE_URL, key,
agent_provider._profile_by_name("glm").model)
def request_body(model: str, messages: list) -> dict:
return {
"model": model,
"messages": messages,
"stream": True,
# usage в финальном чанке стрима (OpenAI-совм.) — питает учёт llm_usage (Ф2).
"stream_options": {"include_usage": True},
"temperature": 0.1,
"max_tokens": 4096,
"thinking": {"type": "disabled"},
}
async def stream_chat(ep: Endpoint, messages: list) -> AsyncGenerator[tuple[str, object], None]:
"""Куски ответа: ("text", str) и ("usage", dict в формате Anthropic). Не-2xx →
ProviderRefused, сеть → исключение httpx."""
# Пустая переменная прокси — не адрес: пустая строка роняет запрос.
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or None
async with httpx.AsyncClient(timeout=120, proxy=proxy) as client:
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:
raise ProviderRefused(resp.status_code,
(await resp.aread()).decode("utf-8", "replace"))
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
data_str = line[6:]
if data_str == "[DONE]":
break
try:
chunk = json.loads(data_str)
if chunk.get("usage"):
u = chunk["usage"]
yield "usage", {
"input_tokens": u.get("prompt_tokens", 0),
"cache_read_input_tokens":
(u.get("prompt_tokens_details") or {}).get("cached_tokens", 0),
"output_tokens": u.get("completion_tokens", 0),
}
if not chunk.get("choices"):
continue
# reasoning_content — внутренние рассуждения модели, человеку не показываем
text = chunk["choices"][0].get("delta", {}).get("content", "")
if text:
yield "text", text
except (json.JSONDecodeError, KeyError, IndexError):
continue
async def stream_with_fallback(messages: list, *, primary: Endpoint, username: str,
tab_id: str) -> AsyncGenerator[tuple[str, object], None]:
"""События: ("text", str) | ("done", {"usage", "provider", "model"}) | ("error", причина)."""
chain = [primary, zaika_endpoint()]
for idx, ep in enumerate(chain):
if ep.name == "glm":
snap = await asyncio.to_thread(zaika_quota.snapshot)
if snap.get("source") == "refusal":
_log.warning("справочный путь: зайку не зову — окно подписки исчерпано")
continue
if not ep.key:
_log.warning("справочный путь: у %s нет ключа — пропускаю", ep.name)
continue
allowed, is_probe = provider_health.attempt_gate(ep.name)
if not allowed:
_log.info("справочный путь: %s закрыт размыкателем — пропускаю", ep.name)
continue
committed, usage, failure = False, {}, ""
try:
async for kind, payload in stream_chat(ep, messages):
if kind == "usage":
usage = payload
elif payload:
committed = True
yield "text", payload
# Отмена клиентом (CancelledError/GeneratorExit) сюда не попадает: вердикта нет.
except Exception as e: # noqa: BLE001
failure = f"{ep.name}: {describe(e)}"
finally:
if is_probe:
provider_health.release_probe(ep.name)
if not failure and not committed:
failure = f"{ep.name}: пустой ответ"
if not failure:
provider_health.record_success(ep.name)
yield "done", {"usage": usage, "provider": ep.label, "model": ep.model}
return
if committed:
_log.warning("справочный путь: %s оборвался после начала ответа (%s)", ep.name, failure)
yield "error", failure
return
quota = ep.name == "glm" and await asyncio.to_thread(zaika_quota.note_refusal, "glm", failure)
if not quota:
provider_health.record_failure(ep.name)
if idx < len(chain) - 1:
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)
continue
yield "error", failure
return
yield "error", "ни один провайдер справочного пути не доступен"
+4 -2
View File
@@ -17,7 +17,7 @@ t.me/<бот>?start=<метка>, жмёт «Старт», и Telegram прин
сообщения с нами). Отдельный ключ снимает этот вопрос целиком, а его утечка не позволяет сообщения с нами). Отдельный ключ снимает этот вопрос целиком, а его утечка не позволяет
подделывать тревоги оператору. подделывать тревоги оператору.
Сеть — httpx напрямую, без прокси (trust_env=False), как в alerts.py; опрос Сеть — httpx без прокси из окружения (trust_env=False), через TG_PROXY_URL, как в alerts.py; опрос
обновлений живёт отдельно, в `telegram_poll.py`. обновлений живёт отдельно, в `telegram_poll.py`.
""" """
@@ -76,9 +76,11 @@ def _api(method: str, data: dict) -> dict:
чем Telegram по нашей же просьбе держит длинный опрос, — иначе рвался бы каждый тихий чем Telegram по нашей же просьбе держит длинный опрос, — иначе рвался бы каждый тихий
заход.""" заход."""
import httpx import httpx
from alerts import tg_proxy
чтение = _READ_TIMEOUT + int(data.get("timeout") or 0) чтение = _READ_TIMEOUT + int(data.get("timeout") or 0)
kw = {"proxy": tg_proxy()} if tg_proxy() else {}
r = httpx.post(f"https://api.telegram.org/bot{_token()}/{method}", json=data, r = httpx.post(f"https://api.telegram.org/bot{_token()}/{method}", json=data,
timeout=httpx.Timeout(чтение, connect=_CONNECT_TIMEOUT), trust_env=False) timeout=httpx.Timeout(чтение, connect=_CONNECT_TIMEOUT), trust_env=False, **kw)
return r.json() return r.json()
+14 -4
View File
@@ -167,8 +167,9 @@ def test_success_closes_the_streak(env):
assert ph.snapshot()["deepseek"]["streak"] == 0 assert ph.snapshot()["deepseek"]["streak"] == 0
def test_probe_slot_is_released_on_failure(env, monkeypatch): def test_probe_slot_is_released_when_the_person_leaves(env, monkeypatch):
"""Порча: убрать release_probe → проба зайки залипнет, и она не вернётся до TTL.""" """Человек закрыл вкладку посреди ответа пробной попытки — вердикта нет, но слот пробы
обязан освободиться. Порча: убрать release_probe → зайка залипнет до TTL (21 минута)."""
qf, ph, db, calls, script = env qf, ph, db, calls, script = env
now = [1000.0] now = [1000.0]
monkeypatch.setattr(ph, "_now", lambda: now[0]) monkeypatch.setattr(ph, "_now", lambda: now[0])
@@ -176,9 +177,18 @@ def test_probe_slot_is_released_on_failure(env, monkeypatch):
ph.record_failure("glm") ph.record_failure("glm")
now[0] += 61 now[0] += 61
script["deepseek"] = [("text", refused(402))] script["deepseek"] = [("text", refused(402))]
script["glm"] = [("text", httpx.ConnectError("x"))] script["glm"] = [("text", "начало"), ("text", "продолжение")]
run(qf)
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"]["half_open_inflight"] is False
assert ph.snapshot()["glm"]["status"] == ph.HALF_OPEN
def test_quota_mark_skips_zaika(env): def test_quota_mark_skips_zaika(env):