"""A blocked token lookup must not stall unrelated relay work on the event loop.""" import ast import asyncio import importlib.util import itertools import json import logging from pathlib import Path import sys import threading from types import SimpleNamespace import unittest from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'gateway')) SPEC = importlib.util.spec_from_file_location('responsive_error_relay', ROOT / 'gateway/transparent_api.py') if SPEC is None or SPEC.loader is None: raise RuntimeError('Cannot load the relay under test') RELAY = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(RELAY) SKIN = ROOT / 'gateway' / 'grok-web-skin.py' SKIN_ERROR_FUNCS = ('_error_payload', '_finish_error', 'error_response', 'async_error_response') _LOGGERS = itertools.count() def _skin_error_ns(): """Extract the real skin error-response functions (hyphenated module, import side effects).""" from aiohttp import web from multidict import CIMultiDict import secrets from gateway_errors import public_error, public_json_dumps tree = ast.parse(SKIN.read_text(encoding='utf-8')) found = {n.name: n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in SKIN_ERROR_FUNCS} missing = [name for name in SKIN_ERROR_FUNCS if name not in found] if missing: raise AssertionError('skin error-response region changed shape; missing %s' % missing) log = logging.getLogger('skin-error-%d' % next(_LOGGERS)) log.setLevel(logging.CRITICAL) log.propagate = False ns = {'asyncio': asyncio, 'secrets': secrets, 'web': web, 'CIMultiDict': CIMultiDict, 'public_error': public_error, 'public_json_dumps': public_json_dumps, 'LOG': log} for name in SKIN_ERROR_FUNCS: exec(compile(ast.Module(body=[found[name]], type_ignores=[]), str(SKIN), 'exec'), ns) return ns class ErrorResponsivenessTests(unittest.IsolatedAsyncioTestCase): async def exercise(self, *, embedded=False): loop = asyncio.get_running_loop() started = asyncio.Event() release = threading.Event() owner = threading.get_ident() called = [] pending = None def mapper(status, raw, path, **context): called.append((status, raw, path, context, threading.get_ident())) loop.call_soon_threadsafe(started.set) if not release.wait(2): raise AssertionError('lookup blocked the relay event loop') return 401, {'error': {'code': 'invalid_api_key', 'retryable': False}} class Content: async def iter_chunked(self, size): yield body body = json.dumps({'error': {'status': 401, 'message': 'invalid token'}}).encode() upstream = SimpleNamespace(status=200 if embedded else 401, headers={'Content-Type': 'application/json'}, content=Content()) request = SimpleNamespace(path='/v1/chat/completions', headers={}) try: with patch.object(RELAY, 'public_error', side_effect=mapper): pending = asyncio.create_task(RELAY.relay_api( request, upstream, json_to_sse=embedded, user_balance=7)) await asyncio.wait_for(started.wait(), 2) # This coroutine runs while the mapper is still blocked in its worker. self.assertFalse(pending.done()) self.assertNotEqual(called[0][-1], owner) release.set() response = await asyncio.wait_for(pending, 2) finally: release.set() if pending is not None and not pending.done(): await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2) self.assertEqual(response.status, 401) payload = json.loads(response.body) self.assertEqual(payload['error']['code'], 'invalid_api_key') self.assertFalse(payload['error']['retryable']) self.assertEqual(len(called), 1) self.assertEqual(called[0][0], 401) self.assertEqual(called[0][1], body) self.assertEqual(called[0][2], request.path) self.assertEqual(called[0][3]['user_balance'], 7) self.assertTrue(called[0][3]['from_upstream']) return payload async def test_http_401_token_lookup_does_not_stall_other_coroutines(self): payload = await self.exercise() self.assertTrue(payload['error']['gateway_request_id']) async def test_embedded_401_uses_the_same_nonblocking_lookup(self): await self.exercise(embedded=True) async def test_other_statuses_keep_the_no_worker_fast_path(self): result = (503, {'error': {'code': 'upstream_unavailable'}}) with patch.object(RELAY, 'public_error', return_value=result) as mapper: with patch.object(RELAY.asyncio, 'to_thread', side_effect=AssertionError('unexpected worker')): actual = await RELAY._upstream_error(503, b'{}', '/v1/chat/completions', user_balance=5) self.assertIs(actual, result) mapper.assert_called_once_with(503, b'{}', '/v1/chat/completions', user_balance=5) class SkinErrorResponseTests(unittest.IsolatedAsyncioTestCase): """The skin shares the relay's rule: only a 401 pays for a worker hop.""" async def test_non_401_stays_inline_and_matches_the_sync_wire_form(self): ns = _skin_error_ns() owner = threading.get_ident() threads = [] real_payload = ns['_error_payload'] def recording(*args, **kwargs): out = real_payload(*args, **kwargs) threads.append(threading.get_ident()) return out ns['_error_payload'] = recording with patch.object(asyncio, 'to_thread', side_effect=AssertionError('unexpected worker hop')): response = await ns['async_error_response'](503, b'{}', '/v1/chat/completions') self.assertEqual(threads, [owner]) self.assertEqual(response.status, 503) payload = json.loads(response.body) self.assertTrue(payload['error']['gateway_request_id']) self.assertEqual(payload['error']['request_id'], payload['error']['gateway_request_id']) self.assertEqual(response.headers['Cache-Control'], 'no-store') self.assertEqual(response.headers['X-Request-ID'], payload['error']['gateway_request_id']) # identical classification to the synchronous form, with a fresh request id sync = json.loads(ns['error_response'](503, b'{}', '/v1/chat/completions').body) self.assertEqual(payload['error']['code'], sync['error']['code']) self.assertNotEqual(payload['error']['gateway_request_id'], sync['error']['gateway_request_id']) async def test_401_token_lookup_leaves_the_skin_event_loop(self): ns = _skin_error_ns() loop = asyncio.get_running_loop() owner = threading.get_ident() started = asyncio.Event() release = threading.Event() threads = [] contexts = [] def mapper(status, raw, path, **context): threads.append(threading.get_ident()) contexts.append(context) loop.call_soon_threadsafe(started.set) if not release.wait(2): raise AssertionError('blocked lookup stalled the test') return status, {'error': {'code': 'invalid_api_key', 'retryable': False}} ns['public_error'] = mapper ticks = 0 async def ticker(): nonlocal ticks while ticks < 5: ticks += 1 await asyncio.sleep(0) pending = None try: pending = asyncio.create_task(ns['async_error_response']( 401, b'{}', '/v1/chat/completions', api_key='sk-under-test')) await asyncio.wait_for(started.wait(), 2) # unrelated coroutines keep running while the DB lookup is blocked self.assertFalse(pending.done()) await asyncio.wait_for(ticker(), 2) release.set() response = await asyncio.wait_for(pending, 2) finally: release.set() if pending is not None and not pending.done(): await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2) self.assertNotEqual(threads, [owner]) self.assertEqual(ticks, 5) self.assertEqual(contexts[0]['api_key'], 'sk-under-test') self.assertEqual(response.status, 401) payload = json.loads(response.body) self.assertEqual(payload['error']['code'], 'invalid_api_key') self.assertTrue(payload['error']['gateway_request_id']) self.assertEqual(response.headers['Cache-Control'], 'no-store') if __name__ == '__main__': unittest.main()