Spaces:
Running
Running
SilverElixir commited on
Commit ·
b3808d6
1
Parent(s): 53310cd
Answer on failed attachment downloads; fix album extras, picks in groups and Gemma routing after the limit
Browse filesA download error escaped the handler and left the user without a reply. Album extras now exclude the main message by identity, a resolved pick is no longer passive background, and plain text keeps Gemma after the Gemini limit.
- lumen_message_core.py +67 -19
- tests/test_bot_state.py +62 -0
lumen_message_core.py
CHANGED
|
@@ -37,6 +37,7 @@ from lumen_media import (
|
|
| 37 |
_msg_media_source,
|
| 38 |
)
|
| 39 |
from lumen_router_config import (
|
|
|
|
| 40 |
_build_route,
|
| 41 |
_looks_like_freshness_query,
|
| 42 |
_looks_like_heavy_query,
|
|
@@ -143,18 +144,9 @@ async def _process_media_group_buffers_locked(messages: list) -> None:
|
|
| 143 |
if any(_direct_attachment_needs_gemini(m) for m in messages) and await _refuse_daily_gemini(main_msg, uid, entry):
|
| 144 |
return
|
| 145 |
extra_media: list[tuple[bytes, str]] = []
|
| 146 |
-
MAX_ALBUM_EXTRA = 9 # первое уходит как основное, до +9 дополнительных (итого 10 — как лимит TikTok-слайдшоу)
|
| 147 |
album_state = bot.get_state(main_msg.chat.id)
|
| 148 |
album_user_id = main_msg.from_user.id if main_msg.from_user else None
|
| 149 |
-
targets
|
| 150 |
-
for m in messages[1:1 + MAX_ALBUM_EXTRA]:
|
| 151 |
-
src = _msg_media_source(m)
|
| 152 |
-
if not src:
|
| 153 |
-
continue
|
| 154 |
-
fid, mime, _ = _media_file_id_and_mime(src)
|
| 155 |
-
if not fid:
|
| 156 |
-
continue
|
| 157 |
-
targets.append((fid, mime, src))
|
| 158 |
# Качаем параллельно, а не по очереди: альбом из 9 фото иначе ждал бы до ~10-20с последовательных скачиваний.
|
| 159 |
fetched_list: list = [None] * len(targets)
|
| 160 |
# Семафор режет in-flight память, суммарный кап — накопленную (аудит D1, 30.09.2026).
|
|
@@ -196,6 +188,29 @@ async def _process_media_group_buffers_locked(messages: list) -> None:
|
|
| 196 |
log.warning("[album] Skipped %d of %d files: over the download size cap.", too_big, len(targets))
|
| 197 |
await bot._handle_message_core(main_msg, extra_media=extra_media or None)
|
| 198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
def _record_passive_group_context(message: Message, state: dict[str, Any], t: str) -> None:
|
| 200 |
"""Фон группы без упоминания: только контекст и медиа в state, без ответа."""
|
| 201 |
import bot
|
|
@@ -297,6 +312,10 @@ def _should_only_record_passively(message: Message, t: str, *, is_private: bool,
|
|
| 297 |
_handle_message_core)."""
|
| 298 |
if is_private or is_guest or mentioned:
|
| 299 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
url = extract_url(t)
|
| 301 |
if url and is_tiktok(url):
|
| 302 |
import bot
|
|
@@ -595,6 +614,12 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
|
|
| 595 |
# Файл больше капа скачивания: честный отказ ниже вместо слепого ответа.
|
| 596 |
med_path, med_name, media_tuple = None, "", None
|
| 597 |
media_too_big_mb = max(1, round(exc.cap_bytes / (1024 * 1024)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 598 |
|
| 599 |
# Голос/аудио: сначала дешёвая транскрибация — дальше текст идёт общим роутингом по
|
| 600 |
# сценарию (тяжесть/свежесть определяются по сказанному). Не вышло — падает в прежний
|
|
@@ -602,7 +627,7 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
|
|
| 602 |
# Один бюджет на транскрибацию и маршрут: иначе войс держал лок сверх бюджета.
|
| 603 |
route_deadline: float | None = None
|
| 604 |
if media_tuple and media_tuple[1].startswith("audio/"):
|
| 605 |
-
route_deadline =
|
| 606 |
transcript = await bot._transcribe_audio(media_tuple[0], media_tuple[1], message.chat.id, deadline=route_deadline)
|
| 607 |
if transcript:
|
| 608 |
clean_prompt = (clean_prompt + "\n" + transcript).strip() if clean_prompt else transcript
|
|
@@ -654,10 +679,17 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
|
|
| 654 |
needs_youtube=needs_youtube, needs_website=needs_website,
|
| 655 |
media_mime=media_mime, is_heavy=is_heavy, needs_freshness=needs_freshness,
|
| 656 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 657 |
log.info(
|
| 658 |
-
'[router] chat=%s heavy=%s freshness=%s youtube=%s website=%s media=%s route=%s',
|
| 659 |
message.chat.id, is_heavy, needs_freshness, needs_youtube, needs_website, media_mime,
|
| 660 |
-
|
| 661 |
)
|
| 662 |
|
| 663 |
# Дневные лимиты на пользователя — до скачивания/маршрута уже поздно, но до
|
|
@@ -669,14 +701,16 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
|
|
| 669 |
return
|
| 670 |
no_search_note = False
|
| 671 |
if bot._user_daily_gemini_exhausted(uid, _late_entry):
|
| 672 |
-
|
| 673 |
-
|
|
|
|
|
|
|
| 674 |
# Ссылки, YouTube, видео/аудио и документы читает только Gemini.
|
| 675 |
await _refuse_daily_gemini(message, uid, _late_entry)
|
| 676 |
return
|
| 677 |
-
route =
|
| 678 |
# Свежесть без Gemini — честная пометка, что ответ без поиска.
|
| 679 |
-
no_search_note = needs_freshness
|
| 680 |
# Дошло до обработки: фон, инъекции и отказы выше уже отсеяны.
|
| 681 |
bot._record_stats_event("messages_received")
|
| 682 |
|
|
@@ -706,6 +740,10 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
|
|
| 706 |
search_budget = web_search_timeout_sec()
|
| 707 |
if route_deadline is not None:
|
| 708 |
search_budget = min(search_budget, max(0.0, route_deadline - time.monotonic()))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 709 |
snippets: list = []
|
| 710 |
if search_budget > 0:
|
| 711 |
try:
|
|
@@ -743,6 +781,12 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
|
|
| 743 |
and not no_search_note
|
| 744 |
and (not needs_freshness or head_has_live_search)
|
| 745 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 746 |
try:
|
| 747 |
provenance: dict = {}
|
| 748 |
ans, reply_already_sent = await bot._run_route(
|
|
@@ -791,8 +835,12 @@ async def _handle_message_core(message: Message, extra_media: list[tuple[bytes,
|
|
| 791 |
ans = bot._t(message.chat.id, "fallback_no_live_search") + "\n\n" + ans
|
| 792 |
if not reply_already_sent:
|
| 793 |
await bot._safe_reply(message, ans)
|
| 794 |
-
#
|
| 795 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 796 |
bot.mark_state_dirty(message.chat.id)
|
| 797 |
lumen_devtrace.record_answer(
|
| 798 |
message.chat.id, user_text=clean_prompt, route=route,
|
|
|
|
| 37 |
_msg_media_source,
|
| 38 |
)
|
| 39 |
from lumen_router_config import (
|
| 40 |
+
_GEMMA_TEXT_CHAIN,
|
| 41 |
_build_route,
|
| 42 |
_looks_like_freshness_query,
|
| 43 |
_looks_like_heavy_query,
|
|
|
|
| 144 |
if any(_direct_attachment_needs_gemini(m) for m in messages) and await _refuse_daily_gemini(main_msg, uid, entry):
|
| 145 |
return
|
| 146 |
extra_media: list[tuple[bytes, str]] = []
|
|
|
|
| 147 |
album_state = bot.get_state(main_msg.chat.id)
|
| 148 |
album_user_id = main_msg.from_user.id if main_msg.from_user else None
|
| 149 |
+
targets = _album_extra_sources(messages, main_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
# Качаем параллельно, а не по очереди: альбом из 9 фото иначе ждал бы до ~10-20с последовательных скачиваний.
|
| 151 |
fetched_list: list = [None] * len(targets)
|
| 152 |
# Семафор режет in-flight память, суммарный кап — накопленную (аудит D1, 30.09.2026).
|
|
|
|
| 188 |
log.warning("[album] Skipped %d of %d files: over the download size cap.", too_big, len(targets))
|
| 189 |
await bot._handle_message_core(main_msg, extra_media=extra_media or None)
|
| 190 |
|
| 191 |
+
|
| 192 |
+
# Основное сообщение уходит отдельно, до +9 дополнительных (итого 10 — как лимит TikTok-слайдшоу).
|
| 193 |
+
_MAX_ALBUM_EXTRA = 9
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _album_extra_sources(messages: list, main_msg: Any) -> list[tuple[str, str, Any]]:
|
| 197 |
+
"""Файлы альбома кроме основного: подпись бывает не на первом фото (аудит 27.10.2026)."""
|
| 198 |
+
sources: list[tuple[str, str, Any]] = []
|
| 199 |
+
for m in messages:
|
| 200 |
+
if m is main_msg:
|
| 201 |
+
continue
|
| 202 |
+
if len(sources) >= _MAX_ALBUM_EXTRA:
|
| 203 |
+
break
|
| 204 |
+
src = _msg_media_source(m)
|
| 205 |
+
if not src:
|
| 206 |
+
continue
|
| 207 |
+
fid, mime, _ = _media_file_id_and_mime(src)
|
| 208 |
+
if not fid:
|
| 209 |
+
continue
|
| 210 |
+
sources.append((fid, mime, src))
|
| 211 |
+
return sources
|
| 212 |
+
|
| 213 |
+
|
| 214 |
def _record_passive_group_context(message: Message, state: dict[str, Any], t: str) -> None:
|
| 215 |
"""Фон группы без упоминания: только контекст и медиа в state, без ответа."""
|
| 216 |
import bot
|
|
|
|
| 312 |
_handle_message_core)."""
|
| 313 |
if is_private or is_guest or mentioned:
|
| 314 |
return False
|
| 315 |
+
if getattr(message, "_pick_resolved", False):
|
| 316 |
+
# Выбор кнопки — уже прямой ответ боту: в группе без этой проверки он
|
| 317 |
+
# уходил в пассивный фон и человек не получал ответа (аудит 27.10.2026).
|
| 318 |
+
return False
|
| 319 |
url = extract_url(t)
|
| 320 |
if url and is_tiktok(url):
|
| 321 |
import bot
|
|
|
|
| 614 |
# Файл больше капа скачивания: честный отказ ниже вместо слепого ответа.
|
| 615 |
med_path, med_name, media_tuple = None, "", None
|
| 616 |
media_too_big_mb = max(1, round(exc.cap_bytes / (1024 * 1024)))
|
| 617 |
+
except Exception as exc:
|
| 618 |
+
# Сеть/прокси не отдали файл: исключение уходило из обработчика,
|
| 619 |
+
# пользователь оставался без ответа (аудит 27.10.2026).
|
| 620 |
+
log.warning("[media] Attachment download failed, replying with a fallback: %s", exc)
|
| 621 |
+
await bot._safe_reply(message, bot._model_error_text("fallback", bot._chat_lang(message.chat.id)))
|
| 622 |
+
return
|
| 623 |
|
| 624 |
# Голос/аудио: сначала дешёвая транскрибация — дальше текст идёт общим роутингом по
|
| 625 |
# сценарию (тяжесть/свежесть определяются по сказанному). Не вышло — падает в прежний
|
|
|
|
| 627 |
# Один бюджет на транскрибацию и маршрут: иначе войс держал лок сверх бюджета.
|
| 628 |
route_deadline: float | None = None
|
| 629 |
if media_tuple and media_tuple[1].startswith("audio/"):
|
| 630 |
+
route_deadline = bot._deadline_within_message(bot.ROUTE_TOTAL_BUDGET_SEC)
|
| 631 |
transcript = await bot._transcribe_audio(media_tuple[0], media_tuple[1], message.chat.id, deadline=route_deadline)
|
| 632 |
if transcript:
|
| 633 |
clean_prompt = (clean_prompt + "\n" + transcript).strip() if clean_prompt else transcript
|
|
|
|
| 679 |
needs_youtube=needs_youtube, needs_website=needs_website,
|
| 680 |
media_mime=media_mime, is_heavy=is_heavy, needs_freshness=needs_freshness,
|
| 681 |
)
|
| 682 |
+
# Блоки и число моделей в них: полный список из 16 строк не читался.
|
| 683 |
+
route_shape: list[list[Any]] = []
|
| 684 |
+
for provider, _model_id in route:
|
| 685 |
+
if route_shape and route_shape[-1][0] == provider:
|
| 686 |
+
route_shape[-1][1] += 1
|
| 687 |
+
else:
|
| 688 |
+
route_shape.append([provider, 1])
|
| 689 |
log.info(
|
| 690 |
+
'[router] chat=%s heavy=%s freshness=%s youtube=%s website=%s media=%s route=%s (%d)',
|
| 691 |
message.chat.id, is_heavy, needs_freshness, needs_youtube, needs_website, media_mime,
|
| 692 |
+
" -> ".join(f"{p}:{n}" for p, n in route_shape), len(route),
|
| 693 |
)
|
| 694 |
|
| 695 |
# Дневные лимиты на пользователя — до скачивания/маршрута уже поздно, но до
|
|
|
|
| 701 |
return
|
| 702 |
no_search_note = False
|
| 703 |
if bot._user_daily_gemini_exhausted(uid, _late_entry):
|
| 704 |
+
# Gemma не тратит дефицитную квоту, поэтому остаётся и после лимита:
|
| 705 |
+
# обычный текст должен работать, как и обещает отказ (аудит 27.10.2026).
|
| 706 |
+
allowed = [(p, m) for p, m in route if p != "gemini" or m in _GEMMA_TEXT_CHAIN]
|
| 707 |
+
if not allowed:
|
| 708 |
# Ссылки, YouTube, видео/аудио и документы читает только Gemini.
|
| 709 |
await _refuse_daily_gemini(message, uid, _late_entry)
|
| 710 |
return
|
| 711 |
+
route = allowed
|
| 712 |
# Свежесть без Gemini — честная пометка, что ответ без поиска.
|
| 713 |
+
no_search_note = needs_freshness and not route_has_live_search(route)
|
| 714 |
# Дошло до обработки: фон, инъекции и отказы выше уже отсеяны.
|
| 715 |
bot._record_stats_event("messages_received")
|
| 716 |
|
|
|
|
| 740 |
search_budget = web_search_timeout_sec()
|
| 741 |
if route_deadline is not None:
|
| 742 |
search_budget = min(search_budget, max(0.0, route_deadline - time.monotonic()))
|
| 743 |
+
else:
|
| 744 |
+
remaining = bot._msg_remaining_sec()
|
| 745 |
+
if remaining is not None:
|
| 746 |
+
search_budget = min(search_budget, remaining)
|
| 747 |
snippets: list = []
|
| 748 |
if search_budget > 0:
|
| 749 |
try:
|
|
|
|
| 781 |
and not no_search_note
|
| 782 |
and (not needs_freshness or head_has_live_search)
|
| 783 |
)
|
| 784 |
+
if route_deadline is None:
|
| 785 |
+
# Один дедлайн на первый проход и пост-хок ретрай: раньше ретрай
|
| 786 |
+
# получал свежие 40с и суммарно выходил за потолок сообщения.
|
| 787 |
+
route_deadline = bot._deadline_within_message(bot.ROUTE_TOTAL_BUDGET_SEC)
|
| 788 |
+
# Маркер обрыва прошлого сообщения не должен влиять на это.
|
| 789 |
+
state.pop("stream_interrupted", None)
|
| 790 |
try:
|
| 791 |
provenance: dict = {}
|
| 792 |
ans, reply_already_sent = await bot._run_route(
|
|
|
|
| 835 |
ans = bot._t(message.chat.id, "fallback_no_live_search") + "\n\n" + ans
|
| 836 |
if not reply_already_sent:
|
| 837 |
await bot._safe_reply(message, ans)
|
| 838 |
+
# Частичный стрим тоже «успешен» для вызывающего, но его пометка
|
| 839 |
+
# «продолжи» должна пережить этот блок (аудит 27.10.2026).
|
| 840 |
+
if state.pop("stream_interrupted", False):
|
| 841 |
+
state["interrupted"] = True
|
| 842 |
+
else:
|
| 843 |
+
state.pop("interrupted", None)
|
| 844 |
bot.mark_state_dirty(message.chat.id)
|
| 845 |
lumen_devtrace.record_answer(
|
| 846 |
message.chat.id, user_text=clean_prompt, route=route,
|
tests/test_bot_state.py
CHANGED
|
@@ -1366,6 +1366,45 @@ def test_continue_rewrites_prompt_and_clears_flag(rate_guard_setup, monkeypatch)
|
|
| 1366 |
bot.chat_state.pop(123, None)
|
| 1367 |
|
| 1368 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1369 |
def test_voice_message_transcribed_into_normal_routing(rate_guard_setup, monkeypatch):
|
| 1370 |
# Войс: транскрибация уходит в общий роутинг как текст, аудио дальше не едет.
|
| 1371 |
message = rate_guard_setup()
|
|
@@ -2055,6 +2094,17 @@ def test_should_only_record_passively(text, is_private, is_guest, mentioned, exp
|
|
| 2055 |
) is expected
|
| 2056 |
|
| 2057 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2058 |
def test_handle_message_core_known_route_outcome_logs_as_warning_not_exception(caplog):
|
| 2059 |
# РЕГРЕССИЯ (аудит логирования): GeminiAllModelsExhaustedError/
|
| 2060 |
# RouteBudgetExceededError — известные, уже обрабатываемые исходы (реальный
|
|
@@ -2615,6 +2665,18 @@ def test_album_logs_skipped_files(monkeypatch, caplog):
|
|
| 2615 |
bot.chat_state.pop(chat_id, None)
|
| 2616 |
|
| 2617 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2618 |
def test_mg_evict_if_full_bounds_buffers():
|
| 2619 |
# Аудит A1-5: флуд distinct mgid растил задачи и память без края.
|
| 2620 |
try:
|
|
|
|
| 1366 |
bot.chat_state.pop(123, None)
|
| 1367 |
|
| 1368 |
|
| 1369 |
+
def test_stream_interrupted_survives_successful_answer(rate_guard_setup, monkeypatch):
|
| 1370 |
+
# Что защищает: пометку «продолжи» после оборванного стрима. Регрессия:
|
| 1371 |
+
# успешный возврат _run_route снимал state["interrupted"], который ставил
|
| 1372 |
+
# стрим, и добивка переставала работать (аудит 27.10.2026).
|
| 1373 |
+
message = rate_guard_setup()
|
| 1374 |
+
state = _continue_state()
|
| 1375 |
+
state.pop("interrupted", None)
|
| 1376 |
+
monkeypatch.setattr(bot, "get_state", lambda cid: state)
|
| 1377 |
+
message.text = "расскажи про фотосинтез"
|
| 1378 |
+
|
| 1379 |
+
async def fake_run_route(*args, **kwargs):
|
| 1380 |
+
state["stream_interrupted"] = True
|
| 1381 |
+
return "Фотосинтез — это", True
|
| 1382 |
+
|
| 1383 |
+
monkeypatch.setattr(bot, "_run_route", fake_run_route)
|
| 1384 |
+
asyncio.run(bot._handle_message_core(message))
|
| 1385 |
+
assert state.get("interrupted") is True
|
| 1386 |
+
assert "stream_interrupted" not in state
|
| 1387 |
+
bot.chat_state.pop(123, None)
|
| 1388 |
+
|
| 1389 |
+
|
| 1390 |
+
def test_attachment_download_failure_replies_with_fallback(rate_guard_setup, monkeypatch):
|
| 1391 |
+
# Что защищает: ответ пользователю, когда файл не скачался. Регрессия:
|
| 1392 |
+
# исключение вылетало из обработчика, и сообщение оставалось без ответа
|
| 1393 |
+
# (аудит 27.10.2026).
|
| 1394 |
+
message = rate_guard_setup()
|
| 1395 |
+
message.text = "что на фото?"
|
| 1396 |
+
message.photo = [SimpleNamespace(file_id="fid", mime_type="image/jpeg")]
|
| 1397 |
+
|
| 1398 |
+
async def failing_resolve(*args, **kwargs):
|
| 1399 |
+
raise RuntimeError("network is down")
|
| 1400 |
+
|
| 1401 |
+
monkeypatch.setattr(bot, "_resolve_incoming_media", failing_resolve)
|
| 1402 |
+
asyncio.run(bot._handle_message_core(message))
|
| 1403 |
+
bot._safe_reply.assert_awaited_once()
|
| 1404 |
+
reply_text = bot._safe_reply.await_args[0][1]
|
| 1405 |
+
assert reply_text == bot._model_error_text("fallback", bot._chat_lang(message.chat.id))
|
| 1406 |
+
|
| 1407 |
+
|
| 1408 |
def test_voice_message_transcribed_into_normal_routing(rate_guard_setup, monkeypatch):
|
| 1409 |
# Войс: транскрибация уходит в общий роутинг как текст, аудио дальше не едет.
|
| 1410 |
message = rate_guard_setup()
|
|
|
|
| 2094 |
) is expected
|
| 2095 |
|
| 2096 |
|
| 2097 |
+
def test_pick_request_in_group_is_not_passive():
|
| 2098 |
+
# Что защищает: выбор кнопки в группе без упоминания бота. Регрессия:
|
| 2099 |
+
# сообщение уходило в пассивный фон, и человек не получал ответа (аудит 27.10.2026).
|
| 2100 |
+
msg = _FakeIncomingMessage(1)
|
| 2101 |
+
msg._pick_resolved = True
|
| 2102 |
+
assert bot._should_only_record_passively(
|
| 2103 |
+
msg, "посоветуй фильм (жанр: Триллер)",
|
| 2104 |
+
is_private=False, is_guest=False, mentioned=False,
|
| 2105 |
+
) is False
|
| 2106 |
+
|
| 2107 |
+
|
| 2108 |
def test_handle_message_core_known_route_outcome_logs_as_warning_not_exception(caplog):
|
| 2109 |
# РЕГРЕССИЯ (аудит логирования): GeminiAllModelsExhaustedError/
|
| 2110 |
# RouteBudgetExceededError — известные, уже обрабатываемые исходы (реальный
|
|
|
|
| 2665 |
bot.chat_state.pop(chat_id, None)
|
| 2666 |
|
| 2667 |
|
| 2668 |
+
def test_album_extras_exclude_main_message_not_position():
|
| 2669 |
+
# Что защищает: состав extra_media альбома. Регрессия: старый код брал
|
| 2670 |
+
# messages[1:10] и при подписи на втором фото терял первый файл, а основное
|
| 2671 |
+
# сообщение отправлял ещё раз как дополнительное (аудит 27.10.2026).
|
| 2672 |
+
import lumen_message_core
|
| 2673 |
+
first = _album_message(999981, caption="опиши", file_id="fid-a")
|
| 2674 |
+
main = _album_message(999982, file_id="fid-b")
|
| 2675 |
+
third = _album_message(999983, file_id="fid-c")
|
| 2676 |
+
extras = lumen_message_core._album_extra_sources([first, main, third], main)
|
| 2677 |
+
assert [fid for fid, _, _ in extras] == ["fid-a", "fid-c"]
|
| 2678 |
+
|
| 2679 |
+
|
| 2680 |
def test_mg_evict_if_full_bounds_buffers():
|
| 2681 |
# Аудит A1-5: флуд distinct mgid растил задачи и память без края.
|
| 2682 |
try:
|