434 lines
21 KiB
Python
434 lines
21 KiB
Python
"""Regression contracts for final stability review findings; all I/O stays local."""
|
|
import ast
|
|
import asyncio
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
from types import SimpleNamespace
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
from test_bot_stability import (BOT, Content, Response, Session, actual_gateway,
|
|
adapter, frame, stability)
|
|
|
|
|
|
class FakeClock:
|
|
"""Thread-safe monotonic clock that moves only when the test says so.
|
|
|
|
Budget accounting can then be asserted exactly instead of hoped for: no real
|
|
sleep, thread warm-up or scheduling delay can shorten the window.
|
|
"""
|
|
|
|
def __init__(self, start: float = 1000.0) -> None:
|
|
self.start = start
|
|
self._value = start
|
|
self._lock = threading.Lock()
|
|
|
|
def monotonic(self) -> float:
|
|
with self._lock:
|
|
return self._value
|
|
|
|
def advance(self, seconds: float) -> None:
|
|
with self._lock:
|
|
self._value += seconds
|
|
|
|
|
|
@contextmanager
|
|
def fake_timing(clock: FakeClock):
|
|
"""Drive adapter deadline math *and* event-loop timers from one fake clock.
|
|
|
|
The adapter reads ``bot_stability.time.monotonic``; the controller additionally
|
|
enforces its own deadline with ``loop.time()`` (``asyncio.timeout_at``). Both are
|
|
replaced, so expiry can only happen through ``clock.advance``.
|
|
"""
|
|
loop = asyncio.get_running_loop()
|
|
with mock.patch.object(adapter, "time", SimpleNamespace(monotonic=clock.monotonic)), \
|
|
mock.patch.object(loop, "time", clock.monotonic):
|
|
yield
|
|
|
|
|
|
class StreamEdges(unittest.IsolatedAsyncioTestCase):
|
|
async def test_default_model_is_admitted_not_bypassed(self):
|
|
session = Session([Response()])
|
|
ns, gate = actual_gateway(session)
|
|
self.assertEqual(await ns["gw_chat"]([]), "unchanged output")
|
|
self.assertEqual(session.calls[0][1]["json"]["model"], "grok-4.7")
|
|
self.assertEqual(gate.controller.snapshot()["model_count"], 1)
|
|
|
|
async def test_final_done_without_newline_is_complete(self):
|
|
session = Session([Response([frame("exact"), b"data: [DONE]"])])
|
|
ns, gate = actual_gateway(session)
|
|
async def send(text): pass
|
|
reply = await ns["gw_chat_stream"]([], "m", send)
|
|
self.assertEqual(reply, "exact")
|
|
self.assertNotIsInstance(reply, adapter.PartialReply)
|
|
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1)
|
|
self.assertEqual(gate.controller.snapshot()["models"]["m"]["circuit"], "closed")
|
|
|
|
async def test_delivery_transport_error_is_not_upstream_failure(self):
|
|
for exception in (TimeoutError("Telegram timeout"), ConnectionResetError("Telegram reset")):
|
|
with self.subTest(error=type(exception).__name__):
|
|
session = Session([Response([frame("already paid"), frame(finish="stop")])])
|
|
ns, gate = actual_gateway(session)
|
|
async def send(text): raise exception
|
|
reply = await ns["gw_chat_stream"]([], "m", send)
|
|
self.assertEqual(reply, "already paid")
|
|
self.assertTrue(reply.incomplete)
|
|
state = gate.controller.snapshot()
|
|
self.assertEqual(state["outcomes"]["partial"], 1)
|
|
self.assertEqual(state["outcomes"]["dependency_failure"], 0)
|
|
self.assertEqual(state["models"]["m"]["circuit"], "closed")
|
|
self.assertEqual(len(session.calls), 1)
|
|
|
|
async def test_deadline_keeps_already_delivered_partial_without_model_penalty(self):
|
|
sent = []
|
|
class SlowContent(Content):
|
|
async def iterate(self):
|
|
yield frame("delivered unchanged")
|
|
await asyncio.Event().wait()
|
|
response = Response()
|
|
response.content = SlowContent()
|
|
session = Session([response])
|
|
ns, gate = actual_gateway(session)
|
|
async def send(text): sent.append(text)
|
|
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .03))
|
|
try:
|
|
reply = await ns["gw_chat_stream"]([], "m", send)
|
|
finally:
|
|
adapter.POLICY.reset(token)
|
|
self.assertEqual(reply, "delivered unchanged")
|
|
self.assertTrue(reply.incomplete)
|
|
self.assertEqual(sent[0], "delivered unchanged")
|
|
state = gate.controller.snapshot()
|
|
self.assertEqual(state["active"], 0)
|
|
self.assertEqual(state["outcomes"]["partial"], 1)
|
|
self.assertEqual(state["outcomes"]["success"], 0)
|
|
self.assertEqual(state["models"]["m"]["limit"], 4)
|
|
self.assertEqual(state["models"]["m"]["circuit"], "closed")
|
|
self.assertEqual(len(session.calls), 1)
|
|
|
|
async def test_user_cancel_after_partial_propagates_and_frees_permit(self):
|
|
delivered = asyncio.Event()
|
|
class SlowContent(Content):
|
|
async def iterate(self):
|
|
yield frame("partial")
|
|
await asyncio.Event().wait()
|
|
response = Response()
|
|
response.content = SlowContent()
|
|
session = Session([response])
|
|
ns, gate = actual_gateway(session)
|
|
async def send(text): delivered.set()
|
|
task = asyncio.create_task(ns["gw_chat_stream"]([], "m", send))
|
|
await asyncio.wait_for(delivered.wait(), 2)
|
|
task.cancel()
|
|
with self.assertRaises(asyncio.CancelledError):
|
|
await task
|
|
state = gate.controller.snapshot()
|
|
self.assertEqual(state["active"], 0)
|
|
self.assertEqual(state["queued"], 0)
|
|
self.assertEqual(state["outcomes"]["cancelled"], 1)
|
|
self.assertEqual(state["models"]["m"]["circuit"], "closed")
|
|
self.assertEqual(len(session.calls), 1)
|
|
|
|
async def test_final_render_keeps_marker_after_cleaning_for_both_handlers(self):
|
|
path = BOT / "grok_bot.py"
|
|
if not path.exists(): path = BOT / "iishko_bot.py"
|
|
tree = ast.parse(path.read_text(encoding="utf-8"))
|
|
found = 0
|
|
for fn in ast.walk(tree):
|
|
if not isinstance(fn, ast.AsyncFunctionDef): continue
|
|
flags: list[ast.stmt] = [n for n in fn.body if isinstance(n, ast.Assign)
|
|
and any(isinstance(t, ast.Name) and t.id == "_partial" for t in n.targets)]
|
|
renders: list[ast.stmt] = [n for n in fn.body if isinstance(n, ast.Assign)
|
|
and any(isinstance(t, ast.Name) and t.id == "_ch" for t in n.targets)
|
|
and "_PARTIAL_MARK" in ast.unparse(n)]
|
|
if not flags or not renders: continue
|
|
namespace = {"reply": adapter.PartialReply("raw"), "PartialReply": adapter.PartialReply,
|
|
"_PARTIAL_MARK": " [incomplete]", "_chunks_html": lambda text: [text]}
|
|
exec(compile(ast.Module(body=flags, type_ignores=[]), str(path), "exec"), namespace)
|
|
namespace["_r"] = str(namespace["reply"])
|
|
exec(compile(ast.Module(body=renders, type_ignores=[]), str(path), "exec"), namespace)
|
|
self.assertEqual(namespace["_ch"], ["raw [incomplete]"])
|
|
found += 1
|
|
self.assertEqual(found, 2)
|
|
|
|
|
|
class AdapterEdges(unittest.IsolatedAsyncioTestCase):
|
|
async def test_inline_dispatcher_resolves_owner_and_rank(self):
|
|
from aiogram import Bot, Dispatcher, Router
|
|
from aiogram.types import Update, InlineQuery, User
|
|
class Preferences:
|
|
def get(self, uid): return 60
|
|
calls = []
|
|
gate = adapter.BotStability({"BOT_DB": "unused.db", "tier_of": lambda uid: 4},
|
|
preferences=Preferences())
|
|
router = Router()
|
|
gate.register(router)
|
|
async def handle(query): calls.append(adapter.POLICY.get())
|
|
router.inline_query.register(handle)
|
|
dispatcher = Dispatcher()
|
|
dispatcher.include_router(router)
|
|
bot = Bot("123456:test-only-placeholder")
|
|
try:
|
|
await dispatcher.feed_update(bot, Update(update_id=1, inline_query=InlineQuery(
|
|
id="test", from_user=User(id=7, is_bot=False, first_name="Test"), query="x", offset="")))
|
|
finally:
|
|
await bot.session.close()
|
|
self.assertEqual(calls, [adapter.RequestPolicy(7, 3, 60)])
|
|
self.assertEqual(adapter.POLICY.get(), adapter.RequestPolicy())
|
|
|
|
async def test_rank_cache_is_bounded_and_does_not_cache_access_authority(self):
|
|
calls = []
|
|
class Preferences:
|
|
def get(self, uid): return 180
|
|
gate = adapter.BotStability({"BOT_DB": "unused.db", "tier_of": lambda uid: calls.append(uid) or 3},
|
|
preferences=Preferences())
|
|
self.assertEqual(gate.policy_for(7).priority, 2)
|
|
self.assertEqual(gate.policy_for(7).priority, 2)
|
|
self.assertEqual(calls, [7])
|
|
for uid in range(4100): gate.policy_for(uid)
|
|
self.assertLessEqual(len(gate._rank_cache), 4096)
|
|
|
|
async def test_cap_cancel_or_deadline_refunds_exactly_once_without_dispatch(self):
|
|
for timed_out in (False, True):
|
|
with self.subTest(timed_out=timed_out):
|
|
ready, release = threading.Event(), threading.Event()
|
|
ledger = {"used": 0, "refunds": 0, "dispatch": 0}
|
|
def reserve(uid, model):
|
|
ledger["used"] += 1
|
|
ready.set()
|
|
if not release.wait(2): raise RuntimeError("test did not release worker")
|
|
return True, 1, 10, "old-day-receipt"
|
|
def refund(receipt):
|
|
self.assertEqual(receipt, "old-day-receipt")
|
|
ledger["used"] -= 1
|
|
ledger["refunds"] += 1
|
|
async def gw_chat_stream(messages, model, send, t=360, _deadline=None):
|
|
ledger["dispatch"] += 1
|
|
return "must not send"
|
|
ns = {"BOT_DB": "unused.db", "gw_chat_stream": gw_chat_stream,
|
|
"pm_cap_reserve": reserve, "pm_cap_release": refund}
|
|
gate = adapter.BotStability(ns); gate.install_wrappers()
|
|
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .04 if timed_out else 60))
|
|
try:
|
|
task = asyncio.create_task(ns["gw_chat_stream"]([], "m", None))
|
|
finally:
|
|
adapter.POLICY.reset(token)
|
|
try:
|
|
self.assertTrue(await asyncio.to_thread(ready.wait, 1))
|
|
if not timed_out: task.cancel()
|
|
with self.assertRaises(stability.DeadlineExceeded if timed_out else asyncio.CancelledError):
|
|
await task
|
|
self.assertEqual(ledger["dispatch"], 0)
|
|
finally:
|
|
release.set()
|
|
if gate._cleanup_tasks:
|
|
await asyncio.wait_for(asyncio.gather(*gate._cleanup_tasks), 3)
|
|
self.assertEqual(ledger, {"used": 0, "refunds": 1, "dispatch": 0})
|
|
self.assertEqual(gate.controller.snapshot()["active"], 0)
|
|
self.assertEqual(gate.controller.snapshot()["models"]["m"]["circuit"], "closed")
|
|
|
|
async def test_cancelled_cap_workers_cannot_build_unbounded_backlog(self):
|
|
ready, release = threading.Event(), threading.Event()
|
|
reservations = []
|
|
def reserve(uid, model):
|
|
reservations.append(uid)
|
|
ready.set()
|
|
if not release.wait(2):
|
|
raise RuntimeError("test did not release worker")
|
|
return True, 1, 10, "receipt"
|
|
async def stream(messages, model, send, t=360, _deadline=None):
|
|
self.fail("must not dispatch")
|
|
ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream,
|
|
"pm_cap_reserve": reserve, "pm_cap_release": lambda key: None}
|
|
controller = stability.StabilityController(global_limit=1)
|
|
gate = adapter.BotStability(ns, controller=controller)
|
|
gate.install_wrappers()
|
|
token = adapter.POLICY.set(adapter.RequestPolicy(7))
|
|
try:
|
|
first = asyncio.create_task(ns["gw_chat_stream"]([], "m", None))
|
|
self.assertTrue(await asyncio.to_thread(ready.wait, 1))
|
|
first.cancel()
|
|
with self.assertRaises(asyncio.CancelledError):
|
|
await first
|
|
with self.assertRaises(stability.QueueFull):
|
|
await ns["gw_chat_stream"]([], "m", None)
|
|
self.assertEqual(reservations, [7])
|
|
self.assertEqual(len(gate._cap_pending), 1)
|
|
finally:
|
|
adapter.POLICY.reset(token)
|
|
release.set()
|
|
if gate._cleanup_tasks:
|
|
await asyncio.wait_for(asyncio.gather(*gate._cleanup_tasks), 3)
|
|
self.assertFalse(gate._cap_pending)
|
|
|
|
async def test_remaining_budget_recomputed_after_cap_and_success_is_not_refunded(self):
|
|
# The cap transaction consumes exactly half of the 125 ms budget, on a clock
|
|
# the test owns. A dispatch that kept the pre-cap budget (0.125) or that let
|
|
# real time eat the window cannot produce the asserted numbers.
|
|
budget, cap_cost = 0.125, 0.0625
|
|
clock = FakeClock()
|
|
dispatched, reserved, refunds = [], [], []
|
|
|
|
def reserve(uid, model):
|
|
clock.advance(cap_cost)
|
|
reserved.append((uid, model))
|
|
return True, 1, 10, "receipt"
|
|
|
|
def release(key):
|
|
refunds.append(key)
|
|
return True
|
|
|
|
async def stream(messages, model, send, t=360, _deadline=None):
|
|
dispatched.append((model, t, _deadline))
|
|
return "exact"
|
|
|
|
ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream,
|
|
"pm_cap_reserve": reserve, "pm_cap_release": release}
|
|
gate = adapter.BotStability(
|
|
ns, controller=stability.StabilityController(clock=clock.monotonic))
|
|
gate.install_wrappers()
|
|
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, budget))
|
|
try:
|
|
with fake_timing(clock):
|
|
self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact")
|
|
finally:
|
|
adapter.POLICY.reset(token)
|
|
gate._cap_executor.shutdown(wait=False)
|
|
self.assertEqual(reserved, [(7, "m")])
|
|
self.assertEqual(dispatched, [("m", budget - cap_cost, clock.start + budget)])
|
|
self.assertEqual(refunds, [])
|
|
self.assertFalse(gate._cleanup_tasks)
|
|
self.assertFalse(gate._cap_pending)
|
|
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1)
|
|
|
|
async def test_auxiliary_call_keeps_its_shorter_explicit_timeout(self):
|
|
calls = []
|
|
async def gw_call(path, payload, t=180):
|
|
calls.append(t)
|
|
return "exact"
|
|
ns = {"BOT_DB": "unused.db", "gw_call": gw_call}
|
|
gate = adapter.BotStability(ns)
|
|
gate.install_wrappers()
|
|
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, 360))
|
|
try:
|
|
result = await ns["gw_call"]("/chat/completions", {"model": "m"}, t=.05)
|
|
finally:
|
|
adapter.POLICY.reset(token)
|
|
self.assertEqual(result, "exact")
|
|
self.assertEqual(calls, [.05])
|
|
|
|
async def test_other_task_can_free_the_last_user_slot_for_nested_model(self):
|
|
controller = stability.StabilityController(global_limit=3, user_limit=2)
|
|
ready, release = asyncio.Event(), asyncio.Event()
|
|
async def holder():
|
|
ready.set()
|
|
await release.wait()
|
|
background = asyncio.create_task(controller.run("background", holder, user_id=7))
|
|
await asyncio.wait_for(ready.wait(), 1)
|
|
async def inner():
|
|
return "inner"
|
|
async def outer():
|
|
asyncio.get_running_loop().call_later(.01, release.set)
|
|
return await controller.run("other", inner, user_id=7)
|
|
try:
|
|
self.assertEqual(await controller.run("outer", outer, user_id=7), "inner")
|
|
finally:
|
|
release.set()
|
|
await asyncio.wait_for(background, 1)
|
|
self.assertEqual(controller.snapshot()["active"], 0)
|
|
self.assertEqual(controller.snapshot()["queued"], 0)
|
|
|
|
async def test_same_task_other_model_rejects_self_deadlock_without_bypassing_user_limit(self):
|
|
controller = stability.StabilityController(global_limit=2, user_limit=1)
|
|
called = []
|
|
async def inner(): called.append(True)
|
|
async def outer():
|
|
with self.assertRaises(stability.QueueFull):
|
|
await controller.run("other", inner, user_id=7)
|
|
return "ok"
|
|
self.assertEqual(await controller.run("m", outer, user_id=7), "ok")
|
|
self.assertEqual(called, [])
|
|
self.assertEqual(controller.snapshot()["active"], 0)
|
|
self.assertEqual(controller.snapshot()["queued"], 0)
|
|
|
|
|
|
class PremiumReceiptStore(unittest.TestCase):
|
|
def test_actual_cap_transaction_and_midnight_refund(self):
|
|
path = BOT / "grok_bot.py"
|
|
if not path.exists(): path = BOT / "iishko_bot.py"
|
|
tree = ast.parse(path.read_text(encoding="utf-8"))
|
|
wanted = {"pm_cap_take", "pm_cap_reserve", "pm_cap_release"}
|
|
definitions: list[ast.stmt] = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in wanted]
|
|
self.assertEqual({n.name for n in definitions if isinstance(n, ast.FunctionDef)}, wanted)
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
db = Path(tmp) / "bot.db"
|
|
namespace = {"sqlite3": sqlite3, "BOT_DB": str(db), "_pm_class": lambda model: "premium",
|
|
"PM_DAY_CAPS": {"premium": {1: 2}}, "earned_rank": lambda uid: 1,
|
|
"today_msk": lambda: "old-day"}
|
|
exec(compile(ast.Module(body=definitions, type_ignores=[]), str(path), "exec"), namespace)
|
|
with ThreadPoolExecutor(max_workers=3) as workers:
|
|
receipts = list(workers.map(lambda _: namespace["pm_cap_reserve"](7, "m"), range(3)))
|
|
self.assertEqual(sum(bool(r[0]) for r in receipts), 2)
|
|
namespace["today_msk"] = lambda: "new-day"
|
|
for receipt in receipts:
|
|
if receipt[0]: namespace["pm_cap_release"](receipt[3])
|
|
con = sqlite3.connect(db)
|
|
try:
|
|
self.assertEqual(con.execute("SELECT v FROM kv WHERE k='pmc:7:premium:old-day'").fetchone()[0], "0")
|
|
self.assertEqual(con.execute("SELECT COUNT(*) FROM kv").fetchone()[0], 1)
|
|
finally: con.close()
|
|
self.assertEqual(namespace["pm_cap_take"](7, "m"), (True, 1, 2))
|
|
|
|
def test_cap_reserve_and_refund_survive_brief_real_writer_contention(self):
|
|
path = BOT / "grok_bot.py"
|
|
if not path.exists():
|
|
path = BOT / "iishko_bot.py"
|
|
tree = ast.parse(path.read_text(encoding="utf-8"))
|
|
wanted = {"pm_cap_take", "pm_cap_reserve", "pm_cap_release"}
|
|
definitions = [node for node in tree.body
|
|
if isinstance(node, ast.FunctionDef) and node.name in wanted]
|
|
self.assertEqual({node.name for node in definitions}, wanted)
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
db = Path(tmp) / "bot.db"
|
|
namespace = {"sqlite3": sqlite3, "BOT_DB": str(db),
|
|
"_pm_class": lambda model: "premium",
|
|
"PM_DAY_CAPS": {"premium": {1: 2}},
|
|
"earned_rank": lambda uid: 1, "today_msk": lambda: "same-day"}
|
|
exec(compile(ast.Module(body=definitions, type_ignores=[]), str(path), "exec"), namespace)
|
|
blocker = sqlite3.connect(db)
|
|
try:
|
|
blocker.execute("CREATE TABLE kv(k TEXT PRIMARY KEY, v TEXT)")
|
|
blocker.commit()
|
|
with ThreadPoolExecutor(max_workers=1) as workers:
|
|
for action in ("reserve", "release"):
|
|
with self.subTest(action=action):
|
|
blocker.execute("BEGIN IMMEDIATE")
|
|
started = threading.Event()
|
|
def run():
|
|
started.set()
|
|
if action == "reserve":
|
|
return namespace["pm_cap_reserve"](7, "m")
|
|
return namespace["pm_cap_release"]("pmc:7:premium:same-day")
|
|
pending = workers.submit(run)
|
|
try:
|
|
self.assertTrue(started.wait(1))
|
|
time.sleep(.3)
|
|
self.assertFalse(pending.done())
|
|
finally:
|
|
blocker.rollback()
|
|
result = pending.result(timeout=3)
|
|
if action == "reserve":
|
|
self.assertEqual(result, (True, 1, 2, "pmc:7:premium:same-day"))
|
|
self.assertEqual(blocker.execute("SELECT v FROM kv").fetchone()[0], "0")
|
|
finally:
|
|
blocker.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|