"""Bot-only admission integration. No provider credentials, billing or content rewriting.""" from __future__ import annotations import asyncio from collections import OrderedDict from concurrent.futures import ThreadPoolExecutor from contextlib import closing from contextvars import ContextVar import contextvars from dataclasses import dataclass from functools import partial, wraps import inspect import logging from pathlib import Path import sqlite3 import threading import time from request_stability import DeadlineExceeded, QueueFull, StabilityController log = logging.getLogger("bot-stability") WAIT_MODES = (60, 180, 360) @dataclass(frozen=True) class RequestPolicy: user_id: int = 0 priority: int = 0 wait_seconds: int = 180 POLICY = ContextVar("iishko_stability_policy", default=RequestPolicy()) _DEADLINE = ContextVar("iishko_stability_deadline", default=None) class GenerationError(RuntimeError): terminal = True stability_code: str | None = None def __init__(self, message, *, status=None, retry_safe=False, ambiguous=False): super().__init__(message) self.status = self.upstream_status = status self.retry_safe = retry_safe self.ambiguous = ambiguous self.dependency_failure = status is None or status in (429, 500, 502, 503, 504) self.stability_dependency_failure = self.dependency_failure class PartialReply(str): """Raw content is unchanged; callers keep the incomplete marker when rendering.""" incomplete = True stability_partial = True def generation_error(message, *, status=None, retry_safe=False, ambiguous=False): """Typed transport evidence; never infer safety from provider text.""" return GenerationError(message, status=status, retry_safe=retry_safe, ambiguous=ambiguous) class WaitPreferences: """A separate short-transaction preference store; never writes billing/bot DBs.""" def __init__(self, path): self.path = Path(path) self.cache = OrderedDict() self._lock = threading.RLock() def get(self, uid): with self._lock: return self._get(uid) def _get(self, uid): now = time.monotonic() cached = self.cache.get(uid) if cached and now - cached[1] < 30: self.cache.move_to_end(uid) return cached[0] value = 180 if self.path.exists(): uri = self.path.resolve().as_uri() + "?mode=ro" with closing(sqlite3.connect(uri, uri=True, timeout=0.15)) as con: row = con.execute("SELECT seconds FROM wait_preferences WHERE uid=?", (int(uid),)).fetchone() if row and row[0] in WAIT_MODES: value = row[0] self._remember(uid, value) return value def _remember(self, uid, seconds): self.cache[uid] = (seconds, time.monotonic()) self.cache.move_to_end(uid) while len(self.cache) > 4096: self.cache.popitem(last=False) def set(self, uid, seconds): with self._lock: return self._set(uid, seconds) def _set(self, uid, seconds): if isinstance(seconds, bool) or seconds not in WAIT_MODES: raise ValueError("unsupported wait mode") with closing(sqlite3.connect(str(self.path), timeout=0.15)) as con: with con: con.execute("CREATE TABLE IF NOT EXISTS wait_preferences(uid INTEGER PRIMARY KEY, seconds INTEGER NOT NULL)") con.execute("INSERT INTO wait_preferences(uid,seconds) VALUES(?,?) " "ON CONFLICT(uid) DO UPDATE SET seconds=excluded.seconds", (int(uid), seconds)) actual = con.execute("SELECT seconds FROM wait_preferences WHERE uid=?", (int(uid),)).fetchone()[0] if actual != seconds: raise RuntimeError("wait preference not persisted") self._remember(uid, seconds) class BotStability: def __init__(self, namespace, controller=None, preferences=None): self.ns = namespace self.controller = controller or StabilityController() self.preferences = preferences or WaitPreferences(Path(namespace["BOT_DB"]).with_name("request-stability.db")) self.installed = False self._rank_cache = OrderedDict() self._rank_lock = threading.Lock() self._cleanup_tasks = set() self._cap_pending = set() # Cap transactions may wait out a short writer lock; the shared default # executor also serves per-event middleware and must not be starved here. self._cap_executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="iishko-cap") async def _cap_operation(self, fn, *args): context = contextvars.copy_context() return await asyncio.get_running_loop().run_in_executor( self._cap_executor, partial(context.run, fn, *args)) def policy_for(self, uid): # Priority changes scheduling only. Existing handlers remain the access authority. now = time.monotonic() with self._rank_lock: cached = self._rank_cache.get(uid) if cached and now - cached[1] < 30: self._rank_cache.move_to_end(uid) rank = cached[0] else: rank = None if rank is None: rank = int(self.ns["tier_of"](uid)) with self._rank_lock: self._rank_cache[uid] = (rank, time.monotonic()) self._rank_cache.move_to_end(uid) while len(self._rank_cache) > 4096: self._rank_cache.popitem(last=False) return RequestPolicy(int(uid), max(0, min(3, rank - 1)), self.preferences.get(uid)) async def middleware(self, handler, event, data): policy = RequestPolicy() user = getattr(event, "from_user", None) if user is not None: try: policy = await asyncio.to_thread(self.policy_for, user.id) except Exception as exc: log.warning("request preference/rank unavailable (%s); using lowest priority", type(exc).__name__) policy = RequestPolicy(int(user.id)) token = POLICY.set(policy) try: return await handler(event, data) finally: POLICY.reset(token) def _cleanup(self, coro): task = asyncio.create_task(coro) self._cleanup_tasks.add(task) def done(finished): self._cleanup_tasks.discard(finished) try: finished.result() except BaseException as exc: log.error("premium cap cleanup failed (%s)", type(exc).__name__) task.add_done_callback(done) async def _refund_cap(self, pending): try: receipt = await pending if receipt[0] and receipt[3] is not None: await self._cap_operation(self.ns["pm_cap_release"], receipt[3]) finally: self._cap_pending.discard(pending) async def _take_cap(self, uid, model): reserve, release = self.ns.get("pm_cap_reserve"), self.ns.get("pm_cap_release") if callable(reserve) and callable(release): if len(self._cap_pending) >= self.controller.global_limit: raise QueueFull() pending = asyncio.create_task(self._cap_operation(reserve, uid, model)) self._cap_pending.add(pending) try: receipt = await asyncio.shield(pending) except BaseException: # Cancelling to_thread cannot cancel its transaction. Refund only # that attempt when the worker eventually returns its receipt. self._cleanup(self._refund_cap(pending)) raise self._cap_pending.discard(pending) return receipt take = self.ns.get("pm_cap_take") if callable(take): return (*await asyncio.to_thread(take, uid, model), None) return True, 0, 0, None def wrap(self, fn, kind): signature = inspect.signature(fn) @wraps(fn) async def guarded(*args, **kwargs): bound = signature.bind(*args, **kwargs) bound.apply_defaults() if kind == "call" and bound.arguments.get("path") not in ("/chat/completions", "/responses"): return await fn(*args, **kwargs) payload = bound.arguments.get("payload") or {} model = bound.arguments.get("model") or payload.get("model") if not isinstance(model, str) or not model: raise generation_error("Для запроса не выбрана модель.", status=400) cap_model = model if callable(self.ns.get("_alias")): model = self.ns["_alias"](model) policy = POLICY.get() task = asyncio.current_task() inherited = _DEADLINE.get() nested = inherited is not None and inherited[0] is task deadline = inherited[1] if nested else time.monotonic() + policy.wait_seconds supplied_deadline = bound.arguments.get("_deadline") if supplied_deadline is not None: deadline = min(deadline, supplied_deadline) token = _DEADLINE.set((task, deadline)) async def invoke(): remaining = deadline - time.monotonic() if remaining <= 0: raise DeadlineExceeded() receipt = None dispatched = False try: # The legacy caller used to spend this cap before waiting. # Rejected/expired queue entries must not consume model caps. if kind == "stream" and not nested and policy.user_id: receipt = await self._take_cap(policy.user_id, cap_model) ok, used, limit = receipt[:3] if not ok: exc = GenerationError(f"Дневной лимит модели исчерпан ({used}/{limit}). " "Обновится в 00:00 МСК. Выбор модели: /model", status=400) exc.stability_code = "model_daily_limit" raise exc remaining = deadline - time.monotonic() if remaining <= 0: raise DeadlineExceeded() if "t" in signature.parameters: bound.arguments["t"] = (min(bound.arguments["t"], remaining) if kind == "call" else remaining) if "_deadline" in signature.parameters: bound.arguments["_deadline"] = deadline dispatched = True return await fn(*bound.args, **bound.kwargs) except Exception as exc: # Prevent legacy callers from initiating another paid fallback. try: setattr(exc, "terminal", True) except (AttributeError, TypeError): pass raise finally: if receipt and receipt[0] and receipt[3] is not None and not dispatched: async def refund(): await self._cap_operation(self.ns["pm_cap_release"], receipt[3]) self._cleanup(refund()) try: remaining = deadline - time.monotonic() if remaining <= 0: raise DeadlineExceeded() return await self.controller.run(model, invoke, user_id=policy.user_id, priority=policy.priority, timeout=remaining) finally: _DEADLINE.reset(token) return guarded def install_wrappers(self): if self.installed: return for name, kind in (("gw_chat_stream", "stream"), ("gw_call", "call"), ("gw_chat", "chat"), ("gw_chat_tools", "tools")): if callable(self.ns.get(name)): self.ns[name] = self.wrap(self.ns[name], kind) self.installed = True async def telemetry_worker(self): while True: try: snapshot = self.controller.snapshot() log.info("request_stability active=%d queued=%d models=%d limits=%s outcomes=%s rejects=%s", snapshot["active"], snapshot["queued"], snapshot["model_count"], snapshot["limits"], snapshot["outcomes"], snapshot["rejects"]) except Exception as exc: log.error("request stability telemetry failed (%s)", type(exc).__name__) await asyncio.sleep(60) def text(self, policy): snapshot = self.controller.snapshot() return ("Стабильность запросов\n\n" f"Общий бюджет ожидания: {policy.wait_seconds} с (очередь + генерация + инструменты).\n" f"Приоритет ранга: {policy.priority + 1}/4. Ожидающие запросы постепенно получают приоритет.\n" f"В работе: {snapshot.get('active', 0)} · в очереди: {snapshot.get('queued', 0)}.\n" "Не больше 1 одновременного запроса на пользователя. " "Перегрузка одной модели не блокирует остальные.\n" "После начала ответа запрос не запускается заново. " "Выбор ожидания не меняет модель, ранг, цену и лимит запросов.") def register(self, router): from aiogram import F from aiogram.filters import Command from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup def keyboard(seconds): return InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text=f"{s} с" + (" ✓" if s == seconds else ""), callback_data=f"stability_wait:{s}") for s in WAIT_MODES]]) async def command(message): if not message.from_user: return try: policy = await asyncio.to_thread(self.policy_for, message.from_user.id) except Exception: await message.answer("Настройки временно недоступны. Попробуй позже.", parse_mode=None) return await message.answer(self.text(policy), reply_markup=keyboard(policy.wait_seconds), parse_mode=None) async def callback(query): if not query.from_user or not query.message: return # Do not let another group member change someone else's preference panel. chat = query.message.chat if chat.type != "private": await query.answer("Настрой ожидание в личном чате: /stability", show_alert=True) return try: seconds = int(query.data.split(":", 1)[1]) if seconds not in WAIT_MODES: raise ValueError("invalid wait") await asyncio.to_thread(self.preferences.set, query.from_user.id, seconds) except (ValueError, sqlite3.Error, RuntimeError, OSError): await query.answer("Не удалось сохранить ожидание. Попробуй позже.", show_alert=True) return await query.answer(f"Общий бюджет: {seconds} с") policy = await asyncio.to_thread(self.policy_for, query.from_user.id) await query.message.edit_text(self.text(policy), reply_markup=keyboard(seconds), parse_mode=None) router.message.middleware(self.middleware) router.callback_query.middleware(self.middleware) router.inline_query.middleware(self.middleware) router.message.register(command, Command(commands=["stability", "wait"])) router.callback_query.register(callback, F.data.startswith("stability_wait:")) def install(namespace, router): existing = namespace.get("_STABILITY_GATE") if existing is not None: return existing gate = BotStability(namespace) gate.install_wrappers() gate.register(router) namespace["_STABILITY_GATE"] = gate return gate