"""Exercise actual bot gateway bodies without importing the bot or accessing live data.""" import ast import asyncio from contextlib import asynccontextmanager import importlib import json import logging from pathlib import Path import random import sys import tempfile import time from types import SimpleNamespace from typing import Any import unittest import aiohttp BOT = Path(__file__).resolve().parents[1] / "bot" sys.path.insert(0, str(BOT)) sys.path.insert(0, str(BOT.parent / "gateway")) public_error = importlib.import_module("gateway_errors").public_error adapter = importlib.import_module("bot_stability") stability = importlib.import_module("request_stability") StabilityController, DeadlineExceeded = stability.StabilityController, stability.DeadlineExceeded class Content: def __init__(self, frames=(), error=None): self.frames, self.error = frames, error async def read(self, size): return b'{"error":{"message":"provider rejected"}}' def __aiter__(self): return self.iterate() async def iterate(self): for frame in self.frames: yield frame if self.error: raise self.error class Response: def __init__(self, frames=(), status=200, error=None, body=None): self.content = Content(frames, error) self.status = status self.body = body or {"choices": [{"message": {"content": "unchanged output"}}]} async def __aenter__(self): return self async def __aexit__(self, *args): return False class Session: def __init__(self, responses): self.responses = list(responses) self.calls = [] def post(self, url, **kwargs): self.calls.append((url, kwargs)) result = self.responses.pop(0) if isinstance(result, BaseException): raise result return result def frame(content=None, *, finish=None, error=False): body = ({"error": {"message": "sensitive provider detail"}} if error else {"choices": [{"delta": {"content": content}, "finish_reason": finish}]}) return ("data: " + json.dumps(body) + "\n\n").encode() def actual_gateway(session, controller=None): """Only the named definitions are executed; all module-level effects are excluded.""" filename = BOT / "grok_bot.py" if not filename.exists(): filename = BOT / "iishko_bot.py" tree = ast.parse(filename.read_text(encoding="utf-8")) wanted = {"gw_chat_stream", "gw_call", "_gw_call_once", "gw_chat", "gw_chat_tools"} definitions: list[ast.stmt] = [ n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in wanted | {"_gw_policy_error", "_sampling"} ] assert wanted.issubset({n.name for n in definitions}) @asynccontextmanager async def session_ctx(): yield session async def response_json(response): return response.body class EmptyChatResponse(RuntimeError): pass class ModelIdentityError(RuntimeError): pass namespace = { "asyncio": asyncio, "aiohttp": aiohttp, "time": time, "random": random, "log": logging.getLogger("gateway-test"), "_STREAM_TOTAL": 360, "_STREAM_SOCK_READ": 120, "_SEND_GAP": 0, "GW_BASE": "http://billing.invalid/v1", "GW_KEY": "test-only-placeholder", "BOT_TOOLS": [], "SAMPLING_REJECTED_MODELS": set(), "_alias": lambda model: model, "_thinking_off": lambda model: {}, "_brand_scrub": lambda text: text, "_PARTIAL_MARK": " [partial]", "_GW_PROV_DEAD": (), "_GW_CHANNEL_DEAD": (), "_GW_USER_QUOTA": (), "_QUOTA429_MARKERS": (), "_POLICY_MARKERS": (), "_POLICY_USERMSG": "rejected", "_pm_class": lambda model: False, "_effort_mt": lambda: 100, "CHAT_FALLBACK": [], "check_response_model": lambda *args: None, "_gw_session_ctx": session_ctx, "_json": response_json, "PartialReply": adapter.PartialReply, "EmptyChatResponse": EmptyChatResponse, "ModelIdentityError": ModelIdentityError, "generation_error": adapter.generation_error, "BOT_DB": "unused.db", "DeadlineExceeded": DeadlineExceeded, "public_error": public_error, } exec(compile(ast.Module(body=definitions, type_ignores=[]), str(filename), "exec"), namespace) gate = adapter.BotStability(namespace, controller=controller) namespace["_STABILITY_GATE"] = gate gate.install_wrappers() return namespace, gate class GatewayContracts(unittest.IsolatedAsyncioTestCase): async def test_success_payload_and_return_are_unchanged(self): text = "Exact output / original 日本語" session = Session([Response([frame(text), frame(finish="stop"), b"data: [DONE]\n\n"])]) ns, gate = actual_gateway(session) sent = [] async def send(text): sent.append(text) result = await ns["gw_chat_stream"]([{"role": "user", "content": "unchanged input"}], "model-x", send) self.assertEqual(result, text) self.assertIn(text, sent) self.assertEqual(len(session.calls), 1) url, request = session.calls[0] self.assertEqual(url, "http://billing.invalid/v1/chat/completions") self.assertEqual(request["json"]["messages"], [{"role": "user", "content": "unchanged input"}]) self.assertEqual(request["json"]["model"], "model-x") self.assertEqual(gate.controller.snapshot()["active"], 0) async def test_partial_transport_failure_is_not_replayed(self): session = Session([Response([frame("partial original")], error=aiohttp.ServerDisconnectedError())]) ns, gate = actual_gateway(session) sent = [] async def send(text): sent.append(text) result = await ns["gw_chat_stream"]([], "model-x", send) self.assertEqual(result, "partial original") self.assertTrue(result.incomplete) self.assertEqual(sent[-1], "partial original [partial]") self.assertEqual(len(session.calls), 1) self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1) self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 0) async def test_sse_error_after_content_is_partial_not_success(self): session = Session([Response([frame("paid output"), frame(error=True)])]) ns, gate = actual_gateway(session) sent = [] async def send(text): sent.append(text) self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "paid output") self.assertEqual(sent[-1], "paid output [partial]") self.assertEqual(len(session.calls), 1) self.assertNotIn("sensitive", str(sent)) self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1) async def test_ambiguous_disconnect_before_content_is_terminal(self): session = Session([Response(error=aiohttp.ServerDisconnectedError())]) ns, gate = actual_gateway(session) async def send(text): self.fail("must not deliver") with self.assertRaises(RuntimeError) as cm: await ns["gw_chat_stream"]([], "model-x", send) self.assertTrue(getattr(cm.exception, "terminal", False)) self.assertTrue(getattr(cm.exception, "ambiguous", False)) self.assertEqual(len(session.calls), 1) self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1) async def test_non_stream_transport_timeout_is_not_replayed(self): session = Session([asyncio.TimeoutError()]) ns, gate = actual_gateway(session) with self.assertRaises(RuntimeError) as cm: await ns["gw_call"]("/chat/completions", {"model": "model-x"}) self.assertTrue(getattr(cm.exception, "terminal", False)) self.assertTrue(getattr(cm.exception, "ambiguous", False)) self.assertEqual(len(session.calls), 1) self.assertEqual(gate.controller.snapshot()["active"], 0) async def test_non_stream_status_error_cannot_trigger_legacy_fallback(self): session = Session([Response(status=503, body={"error": {"message": "unavailable"}})]) ns, gate = actual_gateway(session) with self.assertRaises(RuntimeError) as cm: await ns["gw_chat_tools"]([], "model-x") self.assertTrue(getattr(cm.exception, "terminal", False)) self.assertEqual(len(session.calls), 1) self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1) async def test_pre_content_retry_is_bounded_same_model(self): session = Session([Response(status=429), Response([frame("ok"), frame(finish="stop")])]) ns, gate = actual_gateway(session) # Keep the real retry/sleep algorithm; a short caller deadline is tested separately. async def send(text): pass self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "ok") self.assertEqual(len(session.calls), 2) self.assertEqual([c[1]["json"]["model"] for c in session.calls], ["model-x", "model-x"]) async def test_caller_deadline_is_not_extended(self): session = Session([Response(status=429)]) ns, gate = actual_gateway(session) async def send(text): pass started = time.monotonic() with self.assertRaises(DeadlineExceeded): await ns["gw_chat_stream"]([], "model-x", send, _deadline=started + .03) self.assertLess(time.monotonic() - started, .3) self.assertEqual(len(session.calls), 1) self.assertEqual(gate.controller.snapshot()["active"], 0) async def test_telegram_delivery_error_does_not_penalize_model(self): session = Session([Response([frame("already generated"), frame(finish="stop")])]) ns, gate = actual_gateway(session) async def send(text): raise ValueError("delivery only") self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "already generated") self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 0) self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 0) self.assertEqual(gate.controller.snapshot()["outcomes"]["partial"], 1) self.assertEqual(len(session.calls), 1) async def test_eof_without_finish_is_partial_failure(self): session = Session([Response([frame("unfinished")])]) ns, gate = actual_gateway(session) async def send(text): pass self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "unfinished") self.assertEqual(len(session.calls), 1) self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1) class AdapterContracts(unittest.IsolatedAsyncioTestCase): async def test_nested_calls_share_lease_and_budget(self): controller = StabilityController(global_limit=1, model_limit=1) ns: dict[str, Any] = {"BOT_DB": "unused.db"} async def gw_call(path, payload, t=180): self.assertEqual(controller.snapshot()["active"], 1) self.assertLess(t, .08) return {"unchanged": True} async def gw_chat(messages, model): await asyncio.sleep(.02) return await ns["gw_call"]("/chat/completions", {"model": model}) ns.update(gw_call=gw_call, gw_chat=gw_chat) gate = adapter.BotStability(ns, controller=controller) gate.install_wrappers() token = adapter.POLICY.set(adapter.RequestPolicy(7, 2, .08)) try: self.assertEqual(await ns["gw_chat"]([], "model-x"), {"unchanged": True}) finally: adapter.POLICY.reset(token) self.assertEqual(controller.snapshot()["outcomes"]["success"], 1) self.assertEqual(controller.snapshot()["active"], 0) async def test_rejected_queue_does_not_spend_premium_cap(self): controller = StabilityController(global_limit=1, model_limit=1, queue_limit=1) hold, started = asyncio.Event(), asyncio.Event() async def occupy(): started.set(); await hold.wait() active = asyncio.create_task(controller.run("busy", occupy, user_id=1)) await started.wait() cap_calls = [] async def gw_chat_stream(messages, model, send, t=360, _deadline=None): self.fail("expired queued request must never send") ns = {"BOT_DB": "unused.db", "gw_chat_stream": gw_chat_stream, "pm_cap_take": lambda *args: cap_calls.append(args) or (True, 1, 10)} gate = adapter.BotStability(ns, controller=controller); gate.install_wrappers() token = adapter.POLICY.set(adapter.RequestPolicy(9, 0, .02)) try: with self.assertRaises(DeadlineExceeded): await ns["gw_chat_stream"]([], "busy", None) finally: adapter.POLICY.reset(token); hold.set(); await active self.assertEqual(cap_calls, []) self.assertEqual(controller.snapshot()["active"], 0) async def test_admitted_stream_spends_cap_once(self): calls = [] ns = {"BOT_DB": "unused.db", "pm_cap_take": lambda *args: calls.append(args) or (True, 1, 10)} async def gw_chat_stream(messages, model, send, t=360, _deadline=None): if not messages: return await ns["gw_chat_stream"](["tool round"], model, send, _deadline=_deadline) return "exact" ns["gw_chat_stream"] = gw_chat_stream gate = adapter.BotStability(ns); gate.install_wrappers() token = adapter.POLICY.set(adapter.RequestPolicy(7, 1, 60)) try: self.assertEqual(await ns["gw_chat_stream"]([], "model-x", None), "exact") finally: adapter.POLICY.reset(token) self.assertEqual(calls, [(7, "model-x")]) self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1) async def test_child_task_inherits_policy_not_lease(self): ns: dict[str, Any] = {"BOT_DB": "unused.db"} gate = adapter.BotStability(ns) class Preferences: def get(self, uid): return 360 gate.preferences = Preferences(); ns["tier_of"] = lambda uid: 4 child_result = [] async def handler(event, data): async def child(): child_result.append(adapter.POLICY.get()) await asyncio.create_task(child()) await gate.middleware(handler, SimpleNamespace(from_user=SimpleNamespace(id=7)), {}) self.assertEqual(child_result, [adapter.RequestPolicy(7, 3, 360)]) self.assertEqual(adapter.POLICY.get(), adapter.RequestPolicy()) async def test_non_generation_call_is_not_queued(self): ns: dict[str, Any] = {"BOT_DB": "unused.db"} async def gw_call(path, payload, t=180): return payload ns["gw_call"] = gw_call gate = adapter.BotStability(ns); gate.install_wrappers() payload = {"model": "media-x", "original": True} self.assertIs(await ns["gw_call"]("/images/generations", payload), payload) self.assertEqual(gate.controller.snapshot()["model_count"], 0) async def test_real_router_registration_and_wait_callback(self): from aiogram import Router router = Router() with tempfile.TemporaryDirectory() as tmp: gate = adapter.BotStability({"BOT_DB": str(Path(tmp)/"bot.db"), "tier_of": lambda uid: 3}) gate.register(router) self.assertEqual(len(router.message.handlers), 1) self.assertEqual(len(router.callback_query.handlers), 1) sent = [] class Message: from_user = SimpleNamespace(id=7) chat = SimpleNamespace(type="private") async def answer(self, text, **kwargs): sent.append((text, kwargs)) async def edit_text(self, text, **kwargs): sent.append((text, kwargs)) class Query: from_user = SimpleNamespace(id=7) message = Message() data = "stability_wait:360" async def answer(self, text, **kwargs): pass await router.message.handlers[0].callback(Message()) self.assertIn("180 с", sent[-1][0]) await router.callback_query.handlers[0].callback(Query()) self.assertEqual(gate.preferences.get(7), 360) self.assertIn("360 с", sent[-1][0]) self.assertTrue(all(len(b.callback_data.encode()) < 64 for b in sent[-1][1]["reply_markup"].inline_keyboard[0])) class PreferenceContracts(unittest.TestCase): def test_preferences_persist_without_touching_bot_db(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp)/"preferences.db" prefs = adapter.WaitPreferences(path) self.assertEqual(prefs.get(7), 180) self.assertFalse(path.exists()) prefs.set(7, 60) self.assertEqual(adapter.WaitPreferences(path).get(7), 60) for invalid in (True, 0, 61, 720): with self.assertRaises(ValueError): prefs.set(7, invalid) self.assertEqual(prefs.get(7), 60) def test_error_markers_are_explicit_and_do_not_trust_text(self): for status in (None, 429, 500, 502, 503, 504): self.assertTrue(adapter.generation_error("message", status=status).stability_dependency_failure) for status in (400, 401, 402, 403, 404): self.assertFalse(adapter.generation_error("timeout, unavailable", status=status).stability_dependency_failure) if __name__ == "__main__": unittest.main()