Make legacy payment delivery retryable and keep gateway paths responsive
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

This commit is contained in:
Vlad Gothbreach
2026-10-31 11:23:33 +03:00
parent 97d125122c
commit 3765b00b52
13 changed files with 2854 additions and 303 deletions
+71 -12
View File
@@ -2,17 +2,55 @@
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()])
@@ -229,23 +267,44 @@ class AdapterEdges(unittest.IsolatedAsyncioTestCase):
self.assertFalse(gate._cap_pending)
async def test_remaining_budget_recomputed_after_cap_and_success_is_not_refunded(self):
calls = []
# 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):
time.sleep(.02)
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):
calls.append(t)
self.assertLess(t, .07)
self.assertGreater(t, 0)
dispatched.append((model, t, _deadline))
return "exact"
ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream, "pm_cap_reserve": reserve,
"pm_cap_release": lambda key: self.fail("dispatched request must retain its unit")}
gate = adapter.BotStability(ns); gate.install_wrappers()
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .08))
try: self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact")
finally: adapter.POLICY.reset(token)
self.assertEqual(len(calls), 1)
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 = []