Spaces:
Running
Running
SilverElixir commited on
Commit ·
d71a8e1
1
Parent(s): bca15ac
Add opt-in JSONL dev trace module, tests and docs
Browse files- README.md +3 -2
- docs/ENVIRONMENT.md +3 -0
- lumen_devtrace.py +182 -0
- tests/test_lumen_devtrace.py +95 -0
README.md
CHANGED
|
@@ -55,7 +55,7 @@ A Telegram bot styled after Claude's tone and personality (direct, warm, light o
|
|
| 55 |
|
| 56 |
Lumen is a single FastAPI + aiogram service. Telegram delivers updates to a webhook. Each message gets routed through a chain of candidate models, built on the fly from the message's content: attachments, links, and a couple of lightweight heuristics for "does this need current information" and "is this a heavy request." Plain text starts on Groq, search and link reading go to Gemini, OpenRouter covers the rest; the first provider that answers wins, the next one is tried as a fallback if its whole chain fails. Models that already returned 429 today are skipped by the router.
|
| 57 |
|
| 58 |
-
The codebase is a modular monolith. `bot.py` is the entry point and composition root; the rest is split into focused modules: `lumen_admin.py` (FastAPI app, secret gates, admin/diag/export endpoints), `lumen_message_core.py` (message-handling core), `lumen_routes.py` (LLM calls with fallback, `_run_route`), `lumen_streaming.py` (provider-agnostic streaming), `lumen_chat_state.py` (chat state, quotas, locks), `lumen_commands.py` (commands, TTS/draw pipelines, pick buttons), `lumen_tiktok_flow.py` (TikTok send orchestration), `lumen_rich.py` (sending: guests, Rich Messages, chunking), `lumen_media_flow.py` (Telegram attachment downloads), `lumen_transport_calls.py` (sessions, proxy rotation, Telegram calls), `lumen_errors.py` (model error classification), `lumen_limits.py` (rate window, pick queue), `lumen_router_config.py` (model routing), `lumen_formatting.py` (markdown to Telegram HTML, plus Rich Messages for tables/headings/math), `lumen_security.py` (injection and leak defenses), `lumen_message_parse.py` (links, draw/tts triggers, media references), `lumen_media.py` (mime types, file-id parsing), `lumen_images.py`, `lumen_tts.py`, `lumen_tiktok.py`, `lumen_telegram_transport.py`, `lumen_state_storage.py`, `lumen_typing_pace.py`, `lumen_model_speed.py`, and `lumen_lang.py` (bot language: system messages in 25 languages).
|
| 59 |
|
| 60 |
See **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** for a deeper look at routing, streaming, the security layers, and the TikTok downloader.
|
| 61 |
|
|
@@ -94,13 +94,14 @@ The proxy only forwards to an explicit host allowlist (`api.telegram.org`, `www.
|
|
| 94 |
|
| 95 |
## Diagnostics
|
| 96 |
|
| 97 |
-
All
|
| 98 |
|
| 99 |
| Endpoint | Purpose |
|
| 100 |
|---|---|
|
| 101 |
| `GET /diag` | Checks outbound network reachability (Telegram, Gemini, OpenRouter, TikWM, Pollinations, etc.) from inside the container. |
|
| 102 |
| `GET /webhook_url` | Shows the computed webhook URL and a ready-to-open registration link. |
|
| 103 |
| `GET /export_state` | Dumps all chat histories and quota counters as JSON, for manual backup. |
|
|
|
|
| 104 |
|
| 105 |
`/logs` (a Telegram command, owner-only) sends the current `bot.log` with secrets redacted.
|
| 106 |
|
|
|
|
| 55 |
|
| 56 |
Lumen is a single FastAPI + aiogram service. Telegram delivers updates to a webhook. Each message gets routed through a chain of candidate models, built on the fly from the message's content: attachments, links, and a couple of lightweight heuristics for "does this need current information" and "is this a heavy request." Plain text starts on Groq, search and link reading go to Gemini, OpenRouter covers the rest; the first provider that answers wins, the next one is tried as a fallback if its whole chain fails. Models that already returned 429 today are skipped by the router.
|
| 57 |
|
| 58 |
+
The codebase is a modular monolith. `bot.py` is the entry point and composition root; the rest is split into focused modules: `lumen_admin.py` (FastAPI app, secret gates, admin/diag/export endpoints), `lumen_message_core.py` (message-handling core), `lumen_routes.py` (LLM calls with fallback, `_run_route`), `lumen_streaming.py` (provider-agnostic streaming), `lumen_chat_state.py` (chat state, quotas, locks), `lumen_commands.py` (commands, TTS/draw pipelines, pick buttons), `lumen_tiktok_flow.py` (TikTok send orchestration), `lumen_rich.py` (sending: guests, Rich Messages, chunking), `lumen_media_flow.py` (Telegram attachment downloads), `lumen_transport_calls.py` (sessions, proxy rotation, Telegram calls), `lumen_errors.py` (model error classification), `lumen_limits.py` (rate window, pick queue), `lumen_router_config.py` (model routing), `lumen_formatting.py` (markdown to Telegram HTML, plus Rich Messages for tables/headings/math), `lumen_security.py` (injection and leak defenses), `lumen_message_parse.py` (links, draw/tts triggers, media references), `lumen_media.py` (mime types, file-id parsing), `lumen_images.py`, `lumen_tts.py`, `lumen_tiktok.py`, `lumen_telegram_transport.py`, `lumen_state_storage.py`, `lumen_typing_pace.py`, `lumen_model_speed.py`, and `lumen_lang.py` (bot language: system messages in 25 languages). `lumen_devtrace.py` writes an opt-in JSONL trace (requests, answers, passive background) for prompt debugging.
|
| 59 |
|
| 60 |
See **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** for a deeper look at routing, streaming, the security layers, and the TikTok downloader.
|
| 61 |
|
|
|
|
| 94 |
|
| 95 |
## Diagnostics
|
| 96 |
|
| 97 |
+
All endpoints below require `Authorization: Bearer <ADMIN_PANEL_KEY>` (`/admin_keys`, covered in the deploy steps above, uses `BOT_TOKEN` instead):
|
| 98 |
|
| 99 |
| Endpoint | Purpose |
|
| 100 |
|---|---|
|
| 101 |
| `GET /diag` | Checks outbound network reachability (Telegram, Gemini, OpenRouter, TikWM, Pollinations, etc.) from inside the container. |
|
| 102 |
| `GET /webhook_url` | Shows the computed webhook URL and a ready-to-open registration link. |
|
| 103 |
| `GET /export_state` | Dumps all chat histories and quota counters as JSON, for manual backup. |
|
| 104 |
+
| `GET /devtrace?n=200` | Tails the dev trace (requests, answers, passive background) as JSON, for prompt debugging. Needs `DEV_TRACE=1`. |
|
| 105 |
|
| 106 |
`/logs` (a Telegram command, owner-only) sends the current `bot.log` with secrets redacted.
|
| 107 |
|
docs/ENVIRONMENT.md
CHANGED
|
@@ -145,6 +145,9 @@ These ceilings are fixed in code; change them only with a code edit:
|
|
| 145 |
| `BOT_LOG_PATH` | `/app/bot.log` | Log file path. Mainly relevant for tests; leave it alone in production. |
|
| 146 |
| `LOG_LEVEL` | `INFO` | Standard logging level (`DEBUG`/`INFO`/`WARNING`/...). |
|
| 147 |
| `DIAG_TOTAL_BUDGET_SEC` | `25s` | Total budget for the `/diag` network check across all probed hosts, so a hanging host cannot hang the diagnostic. |
|
|
|
|
|
|
|
|
|
|
| 148 |
| `ADMIN_SECRET_SEED` | — | Secret seed for deriving `WEBHOOK_SECRET` and `ADMIN_PANEL_KEY`. **Set it to its own random value, separate from `BOT_TOKEN`.** Without it both keys are derived from `BOT_TOKEN`, so a leaked token also exposes `/export_state` and `/webhook` (the bot logs a warning at startup). Changing the seed (or setting it for the first time) rotates both keys at once: on restart the bot re-registers the Telegram webhook with the new `WEBHOOK_SECRET` by itself, but anything using the old `ADMIN_PANEL_KEY` (browser bookmarks, cron export scripts) gets `401` until updated — fetch the new key via `GET /admin_keys` with Bearer `BOT_TOKEN`. |
|
| 149 |
|
| 150 |
Sentry setup: create a free Python project at [sentry.io](https://sentry.io) (Developer tier: 5,000 events/month as of 06.10.2026), copy the DSN from the project settings, and add it as a Space secret.
|
|
|
|
| 145 |
| `BOT_LOG_PATH` | `/app/bot.log` | Log file path. Mainly relevant for tests; leave it alone in production. |
|
| 146 |
| `LOG_LEVEL` | `INFO` | Standard logging level (`DEBUG`/`INFO`/`WARNING`/...). |
|
| 147 |
| `DIAG_TOTAL_BUDGET_SEC` | `25s` | Total budget for the `/diag` network check across all probed hosts, so a hanging host cannot hang the diagnostic. |
|
| 148 |
+
| `DEV_TRACE` | `0` | Set to `1` to log every request, answer and passive group background as JSONL (`devtrace.jsonl` next to `bot.log`), for prompt debugging. Off by default: the file holds chat texts. |
|
| 149 |
+
| `DEV_TRACE_PATH` | `<BOT_LOG_PATH dir>/devtrace.jsonl` | Where the dev trace file lives. Point it at a temp dir in tests. |
|
| 150 |
+
| `DEV_TRACE_MAX_BYTES` | `5 MB` | File size cap before rotation to a single `.1` backup; garbage values fall back to the default. |
|
| 151 |
| `ADMIN_SECRET_SEED` | — | Secret seed for deriving `WEBHOOK_SECRET` and `ADMIN_PANEL_KEY`. **Set it to its own random value, separate from `BOT_TOKEN`.** Without it both keys are derived from `BOT_TOKEN`, so a leaked token also exposes `/export_state` and `/webhook` (the bot logs a warning at startup). Changing the seed (or setting it for the first time) rotates both keys at once: on restart the bot re-registers the Telegram webhook with the new `WEBHOOK_SECRET` by itself, but anything using the old `ADMIN_PANEL_KEY` (browser bookmarks, cron export scripts) gets `401` until updated — fetch the new key via `GET /admin_keys` with Bearer `BOT_TOKEN`. |
|
| 152 |
|
| 153 |
Sentry setup: create a free Python project at [sentry.io](https://sentry.io) (Developer tier: 5,000 events/month as of 06.10.2026), copy the DSN from the project settings, and add it as a Space secret.
|
lumen_devtrace.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""lumen_devtrace.py — построчный JSONL-след запросов и ответов для разбора багов."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
log = logging.getLogger("bot")
|
| 11 |
+
|
| 12 |
+
_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
|
| 13 |
+
|
| 14 |
+
_DEFAULT_MAX_BYTES = 5 * 1024 * 1024
|
| 15 |
+
TAIL_HARD_CAP = 1000
|
| 16 |
+
_USER_CLIP = 2000
|
| 17 |
+
_REPLY_CLIP = 4000
|
| 18 |
+
_CTX_TAIL_LINES = 3
|
| 19 |
+
_CTX_CLIP = 500
|
| 20 |
+
_ERROR_CLIP = 500
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def enabled() -> bool:
|
| 24 |
+
return os.getenv("DEV_TRACE", "").strip().lower() in _TRUE_VALUES
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def trace_path() -> Path:
|
| 28 |
+
explicit = os.getenv("DEV_TRACE_PATH", "").strip()
|
| 29 |
+
if explicit:
|
| 30 |
+
return Path(explicit)
|
| 31 |
+
# Рядом с bot.log: в тестах BOT_LOG_PATH уже ведёт во временный каталог.
|
| 32 |
+
base = os.path.dirname(os.getenv("BOT_LOG_PATH", "/app/bot.log")) or "/app"
|
| 33 |
+
return Path(base) / "devtrace.jsonl"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def max_bytes() -> int:
|
| 37 |
+
try:
|
| 38 |
+
value = int(os.getenv("DEV_TRACE_MAX_BYTES", str(_DEFAULT_MAX_BYTES)).strip())
|
| 39 |
+
except (TypeError, ValueError):
|
| 40 |
+
return _DEFAULT_MAX_BYTES
|
| 41 |
+
# Мусор и нули в env давали бы ротацию на каждой строке.
|
| 42 |
+
return value if value >= 1024 else _DEFAULT_MAX_BYTES
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _clip(text: str, limit: int) -> str:
|
| 46 |
+
if not isinstance(text, str):
|
| 47 |
+
text = str(text)
|
| 48 |
+
return text if len(text) <= limit else text[:limit]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _current_secrets() -> tuple[str, ...]:
|
| 52 |
+
# Ленивый импорт: bot импортирует этот модуль, топ-уровень закольцует.
|
| 53 |
+
try:
|
| 54 |
+
import bot as _bot
|
| 55 |
+
getter = getattr(_bot, "_current_log_secrets", None)
|
| 56 |
+
if callable(getter):
|
| 57 |
+
return tuple(getter())
|
| 58 |
+
except Exception:
|
| 59 |
+
pass
|
| 60 |
+
return ()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _scrub(text: str) -> str:
|
| 64 |
+
for secret in _current_secrets():
|
| 65 |
+
if secret:
|
| 66 |
+
text = text.replace(secret, "<REDACTED>")
|
| 67 |
+
return text
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _append(kind: str, payload: dict) -> bool:
|
| 71 |
+
if not enabled():
|
| 72 |
+
return False
|
| 73 |
+
try:
|
| 74 |
+
payload["ts"] = datetime.now(timezone.utc).isoformat()
|
| 75 |
+
payload["kind"] = kind
|
| 76 |
+
path = trace_path()
|
| 77 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
if path.exists() and path.stat().st_size >= max_bytes():
|
| 79 |
+
# Один бэкап вместо series: диску на Space есть предел, старьё не копим.
|
| 80 |
+
backup = Path(str(path) + ".1")
|
| 81 |
+
try:
|
| 82 |
+
if backup.exists():
|
| 83 |
+
backup.unlink()
|
| 84 |
+
path.rename(backup)
|
| 85 |
+
except OSError:
|
| 86 |
+
pass
|
| 87 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 88 |
+
f.write(json.dumps(payload, ensure_ascii=False) + "\n")
|
| 89 |
+
return True
|
| 90 |
+
except Exception as exc:
|
| 91 |
+
log.warning("[devtrace] Failed to append trace entry: %s", exc.__class__.__name__)
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _route_names(route: list | None) -> list[str]:
|
| 96 |
+
names = []
|
| 97 |
+
for item in route or []:
|
| 98 |
+
if isinstance(item, (list, tuple)) and len(item) == 2:
|
| 99 |
+
names.append(f"{item[0]}:{item[1]}")
|
| 100 |
+
else:
|
| 101 |
+
names.append(str(item))
|
| 102 |
+
return names
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def record_passive(chat_id: int, text: str, *, is_private: bool = False, mentioned: bool = False) -> bool:
|
| 106 |
+
# Сначала вычистка, потом обрезка: секрет в хвосте иначе срезался бы молча.
|
| 107 |
+
return _append("passive", {
|
| 108 |
+
"chat_id": chat_id,
|
| 109 |
+
"text": _clip(_scrub(text or ""), _USER_CLIP),
|
| 110 |
+
"private": bool(is_private),
|
| 111 |
+
"mentioned": bool(mentioned),
|
| 112 |
+
})
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def record_blocked(chat_id: int, *, reason: str, prompt_len: int = 0) -> bool:
|
| 116 |
+
# Текст не пишем, только длину: тот же запрет, что у injection-варнинга в логе.
|
| 117 |
+
return _append("blocked", {"chat_id": chat_id, "reason": reason, "prompt_len": int(prompt_len)})
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def record_answer(
|
| 121 |
+
chat_id: int,
|
| 122 |
+
*,
|
| 123 |
+
user_text: str,
|
| 124 |
+
route: list | None = None,
|
| 125 |
+
provider: str = "",
|
| 126 |
+
model: str = "",
|
| 127 |
+
latency_ms: int = 0,
|
| 128 |
+
reply: str = "",
|
| 129 |
+
ctx_tail: list | None = None,
|
| 130 |
+
flags: dict | None = None,
|
| 131 |
+
) -> bool:
|
| 132 |
+
tail = [_clip(_scrub(line), _CTX_CLIP) for line in (ctx_tail or []) if isinstance(line, str)]
|
| 133 |
+
return _append("answer", {
|
| 134 |
+
"chat_id": chat_id,
|
| 135 |
+
"user": _clip(_scrub(user_text or ""), _USER_CLIP),
|
| 136 |
+
"route": _route_names(route),
|
| 137 |
+
"provider": provider or "",
|
| 138 |
+
"model": model or "",
|
| 139 |
+
"latency_ms": int(latency_ms),
|
| 140 |
+
"ctx_tail": tail[-_CTX_TAIL_LINES:],
|
| 141 |
+
"flags": dict(flags or {}),
|
| 142 |
+
"reply": _clip(_scrub(reply or ""), _REPLY_CLIP),
|
| 143 |
+
})
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def record_failure(
|
| 147 |
+
chat_id: int, *, user_text: str, route: list | None = None, error: str = "", latency_ms: int = 0,
|
| 148 |
+
) -> bool:
|
| 149 |
+
return _append("failure", {
|
| 150 |
+
"chat_id": chat_id,
|
| 151 |
+
"user": _clip(_scrub(user_text or ""), _USER_CLIP),
|
| 152 |
+
"route": _route_names(route),
|
| 153 |
+
"error": _clip(_scrub(error or ""), _ERROR_CLIP),
|
| 154 |
+
"latency_ms": int(latency_ms),
|
| 155 |
+
})
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def read_tail(n: int = 200) -> list[dict]:
|
| 159 |
+
try:
|
| 160 |
+
count = max(1, min(int(n), TAIL_HARD_CAP))
|
| 161 |
+
except (TypeError, ValueError):
|
| 162 |
+
count = 200
|
| 163 |
+
try:
|
| 164 |
+
path = trace_path()
|
| 165 |
+
if not path.exists():
|
| 166 |
+
return []
|
| 167 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 168 |
+
lines = f.readlines()
|
| 169 |
+
# С конца до N валидных: битая строка в хвосте иначе съедала бы лимит.
|
| 170 |
+
out = []
|
| 171 |
+
for line in reversed(lines):
|
| 172 |
+
if len(out) >= count:
|
| 173 |
+
break
|
| 174 |
+
try:
|
| 175 |
+
item = json.loads(line)
|
| 176 |
+
except ValueError:
|
| 177 |
+
continue
|
| 178 |
+
if isinstance(item, dict):
|
| 179 |
+
out.append(item)
|
| 180 |
+
return out[::-1]
|
| 181 |
+
except OSError:
|
| 182 |
+
return []
|
tests/test_lumen_devtrace.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""test_lumen_devtrace.py — JSONL-след запросов и ответов для разбора багов."""
|
| 2 |
+
import asyncio
|
| 3 |
+
from types import SimpleNamespace
|
| 4 |
+
|
| 5 |
+
import bot
|
| 6 |
+
import lumen_devtrace
|
| 7 |
+
from tests.bot_test_helpers import _FakeAdminRequest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _enable_trace(monkeypatch, tmp_path):
|
| 11 |
+
monkeypatch.setenv("DEV_TRACE", "1")
|
| 12 |
+
monkeypatch.setenv("DEV_TRACE_PATH", str(tmp_path / "trace.jsonl"))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_devtrace_disabled_by_default_writes_nothing(monkeypatch, tmp_path):
|
| 16 |
+
# Сторож: без DEV_TRACE=1 файл не создаётся даже при прямом вызове.
|
| 17 |
+
monkeypatch.delenv("DEV_TRACE", raising=False)
|
| 18 |
+
monkeypatch.setenv("DEV_TRACE_PATH", str(tmp_path / "trace.jsonl"))
|
| 19 |
+
assert lumen_devtrace.record_answer(1, user_text="hi", reply="hello") is False
|
| 20 |
+
assert not (tmp_path / "trace.jsonl").exists()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_devtrace_answer_clips_and_redacts_secret(monkeypatch, tmp_path):
|
| 24 |
+
# Защищает разбор глупостей модели (полный маршрут и ответ в файле) и
|
| 25 |
+
# отсутствие секретов в нём: регрессия — сырой токен в trace-файле.
|
| 26 |
+
_enable_trace(monkeypatch, tmp_path)
|
| 27 |
+
monkeypatch.setattr(bot, "BOT_TOKEN", "devtrace-secret-abc")
|
| 28 |
+
ok = lumen_devtrace.record_answer(
|
| 29 |
+
5, user_text="devtrace-secret-abc " + "x" * 2500, route=[("groq", "m1")],
|
| 30 |
+
provider="groq", model="m1", latency_ms=12, reply="y" * 5000,
|
| 31 |
+
)
|
| 32 |
+
assert ok is True
|
| 33 |
+
raw = (tmp_path / "trace.jsonl").read_text(encoding="utf-8")
|
| 34 |
+
assert "devtrace-secret-abc" not in raw
|
| 35 |
+
assert "<REDACTED>" in raw
|
| 36 |
+
entries = lumen_devtrace.read_tail(10)
|
| 37 |
+
assert len(entries) == 1 and entries[0]["kind"] == "answer"
|
| 38 |
+
assert len(entries[0]["user"]) == 2000
|
| 39 |
+
assert len(entries[0]["reply"]) == 4000
|
| 40 |
+
assert entries[0]["route"] == ["groq:m1"]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_devtrace_read_tail_returns_last_n_and_skips_broken(monkeypatch, tmp_path):
|
| 44 |
+
# Хвост для /devtrace: последние N и пропуск битых строк вместо 500.
|
| 45 |
+
_enable_trace(monkeypatch, tmp_path)
|
| 46 |
+
for i in range(5):
|
| 47 |
+
assert lumen_devtrace.record_passive(7, f"msg {i}") is True
|
| 48 |
+
with open(tmp_path / "trace.jsonl", "a", encoding="utf-8") as f:
|
| 49 |
+
f.write("{broken\n")
|
| 50 |
+
last = lumen_devtrace.read_tail(2)
|
| 51 |
+
assert [e["text"] for e in last] == ["msg 3", "msg 4"]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_devtrace_endpoint_rejects_missing_or_wrong_key(monkeypatch):
|
| 55 |
+
original = bot.ADMIN_PANEL_KEY
|
| 56 |
+
bot.ADMIN_PANEL_KEY = "real-admin-key"
|
| 57 |
+
try:
|
| 58 |
+
result = asyncio.run(bot.devtrace(_FakeAdminRequest(headers={"Authorization": "Bearer wrong"})))
|
| 59 |
+
assert result.status_code == 401
|
| 60 |
+
finally:
|
| 61 |
+
bot.ADMIN_PANEL_KEY = original
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_devtrace_endpoint_returns_entries(monkeypatch, tmp_path):
|
| 65 |
+
# Сторож: валидный ключ отдаёт записанный след, а не пустой список.
|
| 66 |
+
_enable_trace(monkeypatch, tmp_path)
|
| 67 |
+
original = bot.ADMIN_PANEL_KEY
|
| 68 |
+
bot.ADMIN_PANEL_KEY = "real-admin-key"
|
| 69 |
+
try:
|
| 70 |
+
assert lumen_devtrace.record_failure(9, user_text="q", error="boom") is True
|
| 71 |
+
result = asyncio.run(bot.devtrace(_FakeAdminRequest(headers={"Authorization": "Bearer real-admin-key"})))
|
| 72 |
+
assert result["count"] == 1
|
| 73 |
+
assert result["entries"][0]["kind"] == "failure"
|
| 74 |
+
assert result["enabled"] is True
|
| 75 |
+
finally:
|
| 76 |
+
bot.ADMIN_PANEL_KEY = original
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_devtrace_passive_hook_writes_background(monkeypatch, tmp_path):
|
| 80 |
+
# Фон группы попадает в след: иначе разбирать влияние контекста не по чему.
|
| 81 |
+
from aiogram.enums import ChatType
|
| 82 |
+
_enable_trace(monkeypatch, tmp_path)
|
| 83 |
+
monkeypatch.setattr(bot, "_should_only_record_passively", lambda *a, **k: True)
|
| 84 |
+
monkeypatch.setattr(bot, "is_guest_message", lambda m: False)
|
| 85 |
+
monkeypatch.setattr(bot, "message_mentions_bot", lambda m: False)
|
| 86 |
+
msg = SimpleNamespace(
|
| 87 |
+
text="фоновый текст", caption=None,
|
| 88 |
+
chat=SimpleNamespace(id=777002, type=ChatType.GROUP),
|
| 89 |
+
from_user=SimpleNamespace(id=456), reply_to_message=None,
|
| 90 |
+
)
|
| 91 |
+
asyncio.run(bot._handle_message_core(msg))
|
| 92 |
+
entries = lumen_devtrace.read_tail(10)
|
| 93 |
+
assert entries and entries[-1]["kind"] == "passive"
|
| 94 |
+
assert "фоновый" in entries[-1]["text"]
|
| 95 |
+
bot.chat_state.pop(777002, None)
|