fix never-sent notifications for periods >= 3h, lower shared-token gap to 3s, handle both Lichess 429s

- periodic: stale-backlog suppression compared the window length with an absolute 2h,
  so every pair with period 180/360/720/1440 min was suppressed on every check
  (prod: 20 pairs of 16 users, 62 suppressions in 10 days). Now stale means the window
  exceeds the configured period by more than 2h (PeriodicMonitor._is_stale_backlog).
- SharedTokenGate min_gap 6s -> 3s. Measured with a separate test account: the JSON
  "Please only run N request(s) at a time" 429 is a concurrency limit (2 streams per
  IP / per token, slot freed at stream end) that a sequential client cannot trip, so
  the old 6s "cooldown" rationale was wrong; the HTML "Too many requests" 429 is an
  edge burst limiter (~0.45-0.9 req/s sustained) that 2-3s spacing avoids.
- lichess_client: on 429 log the body prefix (so the two limiters are distinguishable)
  and pause the gate 60s for the burst limiter only; re-raise exactly as before.
- /lastYear_or_1000games uses interactive priority (was waiting behind the backlog)
- /test_admin_notify only works from the admin chat
- stats service honours LOG_LEVEL and silences httpx INFO (bulk of its 808 MB log)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-20 21:55:30 +00:00
parent 7178b80854
commit 028fd4d3e8
7 changed files with 131 additions and 35 deletions

View file

@ -50,8 +50,11 @@ class LichessBot:
self.application = None # Will be set when application is created
async def test_admin_notify(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Manual test to verify admin notifications delivery path."""
"""Manual test to verify admin notifications delivery path. Admin-only: anyone else gets no reply."""
user = update.effective_user
admin_chat_id = self.db.get_admin_chat_id()
if admin_chat_id is None or update.effective_chat is None or update.effective_chat.id != admin_chat_id:
return
try:
await self.notifier.notify_new_player("test_player_notify", user.id, user.username if user else None)
await update.message.reply_text("✅ Admin notification test triggered.")
@ -924,7 +927,9 @@ class LichessBot:
pass
# Get data for this player
data = await self.lichess_api.get_games_period(username, since_ms, now_ms, rated_only=True)
# User-initiated command: jump ahead of the periodic backlog in the
# shared-token queue instead of waiting it out as "background".
data = await self.lichess_api.get_games_period(username, since_ms, now_ms, rated_only=True, priority="interactive")
# Delete processing message
if processing_msg:

View file

@ -22,7 +22,7 @@ LICHESS_STATS_API_BASE_URL = "http://localhost:8002" # Host port for stats API
# Слои пейсинга запросов (чтобы не плодить лишние):
# - Настоящий лимитер общего Lichess-токена — SharedTokenGate в
# LichessWebServices/rate_limiter.py (6 с между запросами, приоритет interactive >
# LichessWebServices/rate_limiter.py (3 с между запросами, приоритет interactive >
# background). Он один на весь stats-сервис и общий для всех его клиентов.
# - Бот запросы к НАШЕМУ ЖЕ локальному stats-сервису (LICHESS_STATS_API_BASE_URL)
# не притормаживает: любая задержка здесь только добавляла бы латентность перед

View file

@ -73,6 +73,21 @@ class PeriodicMonitor:
# подряд идущих ошибок (~2 часа при капнутом бэкоффе в 300с на попытку)
ADMIN_NOTIFY_ERROR_THRESHOLD = 25
# How much longer than its configured period a (collapsed) check window may be
# before it is treated as a stale backlog and its notification is suppressed.
STALE_BACKLOG_THRESHOLD = timedelta(hours=2)
@classmethod
def _is_stale_backlog(cls, window: timedelta, period_minutes: int) -> bool:
"""
True when a check window exceeds the pair's configured period by more than
STALE_BACKLOG_THRESHOLD. Measured relative to period_minutes, not as an
absolute length: a normal on-schedule window for period_minutes >= 180
is itself longer than 2h and must still produce a notification (an
absolute 2h cut-off silently dropped every notification for such pairs).
"""
return window > timedelta(minutes=period_minutes) + cls.STALE_BACKLOG_THRESHOLD
@staticmethod
def _checkpoint_jitter_seconds(user_id: int, gamer_id: int, period_minutes: int) -> float:
"""
@ -191,12 +206,15 @@ class PeriodicMonitor:
# "recent activity" anymore — dumping a multi-week, game-by-game report
# on the user reads as spam, not a periodic update. Catch the checkpoint
# up silently in that case instead of sending the full notification.
STALE_BACKLOG_THRESHOLD = timedelta(hours=2)
is_stale_backlog = (period_end_approx - since_time) > STALE_BACKLOG_THRESHOLD
# "Way more" is measured against the pair's own configured period
# (see _is_stale_backlog): an on-schedule 3h/6h/12h/24h window is
# normal for those pairs, not a stale backlog.
is_stale_backlog = self._is_stale_backlog(period_end_approx - since_time, period_minutes)
if is_stale_backlog:
logger.warning(
f"⏭️ {username}: collapsed window ({since_time} to {period_end_approx}) "
f"exceeds {STALE_BACKLOG_THRESHOLD}; catching up checkpoint silently, "
f"exceeds the configured period ({period_minutes} min) by more than "
f"{self.STALE_BACKLOG_THRESHOLD}; catching up checkpoint silently, "
f"no notification will be sent for this stale backlog"
)

View file

@ -59,6 +59,31 @@ class LichessClient:
if not self.app_token:
logger.warning("LICHESS_APP_TOKEN не задан — анонимные запросы к games/user и user/activity будут получать 404 от Lichess")
def _handle_429(self, username: str, response: httpx.Response) -> None:
"""
Разбирает 429 от lichess.org, чтобы в логах было видно, КАКОЙ из двух
лимитеров сработал (см. docstring SharedTokenGate в rate_limiter.py):
- JSON "Please only run N request(s) at a time" — ConcurrencyLimit lila:
слоты заняты другим процессом с тем же токеном/IP; пауза между нашими
запросами ничего не даст, гейт не трогаем;
- HTML "Too many requests" (или неизвестное тело) — edge burst limiter:
по правилу Lichess после любого 429 ждём полную минуту всем общим
токеном — gate.pause(60).
Вызывается ТОЛЬКО после release() гейта (из except вне try/finally),
иначе pause() + удержание гейта = дедлок. Исключение не глотает —
вызывающий код пробрасывает его как и раньше.
"""
body = (response.text or "").strip().replace("\n", " ")[:120]
logger.warning(f"429 from lichess.org for {username}: body={body!r}")
if "Please only run" in body:
logger.warning(
f"429 for {username} is the concurrency limiter (slots held by another "
f"process using the same token/IP); request spacing won't help, not pausing the gate"
)
return
logger.warning(f"429 for {username} is the burst limiter (or unknown): pausing all shared-token calls for 60s")
self.shared_token_gate.pause(60)
async def get_user_activity(self, username: str) -> Optional[List[Dict[str, Any]]]:
"""
Получает активность пользователя за последние 7 активных дней.
@ -84,9 +109,9 @@ class LichessClient:
headers = {'Authorization': f'Bearer {self.app_token}'} if self.app_token else {}
# LICHESS_APP_TOKEN общий с get_games_of_period, и Lichess не
# пускает 2+ запроса подряд без ощутимой паузы между ними — держим
# shared_token_gate на весь запрос-ответ. get_user_activity вызывается
# LICHESS_APP_TOKEN общий с get_games_of_period: держим shared_token_gate
# на весь запрос-ответ (не больше одного запроса в полёте + пауза между
# запросами, см. SharedTokenGate). get_user_activity вызывается
# только из интерактивных команд (/today и т.п.), периодические проверки
# его не используют — приоритет всегда "interactive", параметризовать не нужно.
await self.shared_token_gate.acquire(priority="interactive")
@ -108,6 +133,9 @@ class LichessClient:
logger.warning(f"⚠️ Пользователь {username} не найден (404)")
return None
else:
if e.response.status_code == 429:
# Гейт уже отпущен (finally выше) — pause() здесь безопасен
self._handle_429(username, e.response)
# Другие HTTP ошибки - логируем и пробрасываем
logger.error(f"❌ HTTP ошибка при получении активности пользователя {username}: status={e.response.status_code}, error={e}")
raise
@ -168,10 +196,11 @@ class LichessClient:
logger.info(f"Запрос игр для {username} с {since_ms} по {until_ms} (priority={priority})")
# Держим shared_token_gate на весь запрос-ответ и с паузой после —
# LICHESS_APP_TOKEN общий с get_user_activity, и Lichess не пускает
# 2+ запроса подряд без ощутимой паузы между ними (даже строго
# последовательные с интервалом ~100-300мс ловили 429 "Please only
# run 1 request(s) at a time" под реальной нагрузкой на проде).
# LICHESS_APP_TOKEN общий с get_user_activity. Один запрос в полёте
# нужен из-за ConcurrencyLimit (2 потока на токен/IP), пауза между
# запросами — из-за edge burst limiter (см. docstring SharedTokenGate;
# 429 "Please only run N request(s) at a time" на проде были про
# параллельные потоки, а не про интервал).
# priority="interactive" (например, довесочный accuracy-fetch в /today)
# обгоняет фоновые периодические проверки в этой же очереди.
await self.shared_token_gate.acquire(priority=priority)
@ -207,6 +236,9 @@ class LichessClient:
logger.warning(f"Пользователь {username} не найден")
return None
else:
if e.response.status_code == 429:
# Гейт уже отпущен (finally выше) — pause() здесь безопасен
self._handle_429(username, e.response)
# Другие HTTP ошибки - логируем и пробрасываем
logger.error(f"HTTP ошибка при получении игр пользователя {username}: {e}")
raise

View file

@ -16,6 +16,7 @@ from fastapi import FastAPI, HTTPException, Path, Query, Header
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging
import os
from datetime import datetime
from stats_service import StatsService
from models import ActivityResponse, ErrorResponse, HealthResponse, GamesOfPeriodResponse, PuzzleOfPeriodResponse
@ -23,9 +24,14 @@ from models import ActivityResponse, ErrorResponse, HealthResponse, GamesOfPerio
# =============================================================================
# НАСТРОЙКА ЛОГИРОВАНИЯ
# =============================================================================
# Настройка базового логирования для всего приложения
# Уровень INFO позволяет видеть все важные события и ошибки
logging.basicConfig(level=logging.INFO)
# Настройка базового логирования для всего приложения.
# Уровень берём из LOG_LEVEL (DEBUG/INFO/WARNING), как в config.py бота; по
# умолчанию INFO — видны все важные события и ошибки.
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
logging.basicConfig(level=getattr(logging, LOG_LEVEL, logging.INFO))
# httpx логирует URL каждого запроса к lichess.org на INFO — секретов там нет, но
# это основная масса лога сервиса. Access-лог uvicorn не трогаем.
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# =============================================================================

View file

@ -56,16 +56,24 @@ class SharedTokenGate:
"""
Serializes AND paces games/user + user/activity calls sharing LICHESS_APP_TOKEN.
wait_if_needed() alone isn't enough here: it only paces request STARTS and
releases its lock before the request runs, so two requests can still
overlap in flight. A bare mutex isn't enough either: Lichess keeps
rejecting this token with "Please only run 1 request(s) at a time" even
when calls are strictly sequential with only ~100-300ms between one
finishing and the next starting — confirmed live on prod, where nearly
every request was getting 429'd despite never truly overlapping. Whatever
Lichess is enforcing here needs a real cooldown between calls, not just
non-overlap, so this gate tracks the last release time and forces a
minimum gap before the next request is allowed to start.
There are two different 429s on GET /api/games/user/{u} (measured 2026-10
with a separate test account; Lichess sends no Retry-After / X-RateLimit
headers for either):
(a) lila ConcurrencyLimit, JSON body {"error":"Please only run N request(s)
at a time"}: 2 concurrent streams per IP and 2 per OAuth token. The slot
is released when the stream ends, so a strictly sequential client can
never trip it, and an inter-request gap does NOT help. Seeing it means
the slots are held by some OTHER process using the same token/IP.
Serialization (busy flag + queues below) is all this gate can do for it.
(b) edge burst limiter, HTML body "Too many requests. Read
https://http.lichess.org/429": a token bucket of roughly burst 5-6 then
~0.45-0.9 req/s sustained. Gap 0.3s -> 429 at the 9th request, 1.0s ->
at the 15th, 2.0s and 3.0s -> none. This is what min_gap protects
against: the gate tracks the last release time and forces a minimum gap
before the next request may start. Official rule after ANY 429: wait a
full minute — see pause().
Two-tier priority: background periodic checks queue behind interactive
on-demand requests (/today etc.), so a user command doesn't have to wait
@ -74,9 +82,10 @@ class SharedTokenGate:
`async with`) because the priority has to be picked at call time.
"""
def __init__(self, min_gap: float = 6.0):
def __init__(self, min_gap: float = 3.0):
self._min_gap = min_gap
self._last_release_time: Optional[float] = None
self._paused_until: float = 0.0
self._busy = False
self._interactive_waiters: "deque[asyncio.Future]" = deque()
self._background_waiters: "deque[asyncio.Future]" = deque()
@ -98,6 +107,29 @@ class SharedTokenGate:
logger.debug(f"Shared token gate: waiting {wait_time:.3f}s before next games/user or user/activity call")
await asyncio.sleep(wait_time)
# Global pause after a 429 (see pause()). Checked in a loop: pause() may be
# called again while we sleep. Applies to every priority — the limiter is
# per token/IP, an interactive request would just burn the minute too.
while True:
remaining = self._paused_until - time.time()
if remaining <= 0:
break
logger.info(f"Shared token gate: paused after 429, holding next call for {remaining:.1f}s")
await asyncio.sleep(remaining)
def pause(self, seconds: float):
"""
Hold every subsequent acquire() (any priority) until `seconds` from now.
Lichess' rule after any 429 is to wait a full minute; this is how the
client honours it for the whole shared token. Never blocks release(),
so it is safe to call from the error path of a request that still holds
(or has just released) the gate. Later/longer pauses extend, shorter
ones never cut an active pause short.
"""
until = time.time() + seconds
if until > self._paused_until:
self._paused_until = until
def release(self):
self._last_release_time = time.time()
if self._interactive_waiters:
@ -110,13 +142,16 @@ class SharedTokenGate:
if not nxt.done():
nxt.set_result(None)
# min_gap=6.0: no documented number from Lichess for this endpoint's real
# limit: the games/user docs only mention a streaming throttle (games/sec
# within one response), not an inter-request cooldown. 6s was chosen after
# 429s persisted at looser spacing under real prod load; revisit if 429s
# either persist (raise further) or checkpoint lag grows unacceptably
# (Lichess documents its own real limit somewhere and this can be lowered).
_shared_token_gate = SharedTokenGate(min_gap=6.0)
# min_gap=3.0: Lichess documents no number for this endpoint's inter-request
# limit (the games/user docs only mention a streaming throttle, games/sec within
# one response). Measured (see SharedTokenGate docstring): the edge burst limiter
# tolerates a sustained 1 req/2s and 1 req/3s indefinitely, while 1 req/1s trips
# it at the 15th request. 3s keeps a margin over the measured 2s and is safely
# under the ~0.45 req/s sustained refill. The earlier 6s was chosen when the
# "Please only run N request(s) at a time" 429 was blamed on spacing; that one is
# the concurrency limiter and is unaffected by the gap. Revisit if the HTML
# "Too many requests" 429 shows up in prod at this spacing.
_shared_token_gate = SharedTokenGate(min_gap=3.0)
def get_shared_token_gate() -> SharedTokenGate:
"""Gate serializing+pacing lichess.org calls made with the shared LICHESS_APP_TOKEN. Use acquire()/release()."""

View file

@ -115,7 +115,7 @@ Telegram бот для управления отслеживанием игро
- Каждый пользователь имеет свой набор игроков
- Версионность бота (отображается в команде /support)
- **Многоязычная поддержка**: Русский и английский языки с автоматическим определением и ручным выбором через `/set_lang`
- **Пейсинг запросов к Lichess**: единая очередь общего токена в stats-сервисе (`LichessWebServices/rate_limiter.py`, SharedTokenGate: 6 с между запросами, интерактивные команды приоритетнее периодических проверок); бот сам запросы к сервису не притормаживает, только ограничивает число одновременных периодических запросов (`PERIODIC_MAX_CONCURRENT_REQUESTS`)
- **Пейсинг запросов к Lichess**: единая очередь общего токена в stats-сервисе (`LichessWebServices/rate_limiter.py`, SharedTokenGate: 3 с между запросами, интерактивные команды приоритетнее периодических проверок); бот сам запросы к сервису не притормаживает, только ограничивает число одновременных периодических запросов (`PERIODIC_MAX_CONCURRENT_REQUESTS`)
**Команды:**
- `/start` - начало работы с ботом и добавление первого игрока