"""Downstream-outcome accounting for the provider relay. An upstream 200 is not success by itself: the identity, payload, and validation layers can still turn it into a downstream 5xx. These tests pin the contract -- account the status the caller actually received, credit one route once, never replay after streaming started, and never penalize client cancellation or a client-side refusal. """ import asyncio from contextlib import closing import json from pathlib import Path import sqlite3 import sys import tempfile import unittest import aiohttp from aiohttp import web ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'gateway' if (ROOT / 'gateway').is_dir() else ROOT)) from gateway_provider_relay import relay_selected from gateway_providers import ProviderRegistry MODEL = 'exact-model' def configuration(): return {'pinning_enabled': True, 'providers': [ {'id': 'primary', 'name': 'Primary', 'channel_ids': [1], 'max_inflight': 1, 'models': {MODEL: {'effort_levels': None}}}, {'id': 'reserve', 'name': 'Reserve', 'channel_ids': [2], 'reserve': True, 'models': {MODEL: {'effort_levels': None}}}]} class _Content: def __init__(self, chunks=()): self._chunks = chunks async def iter_chunked(self, size): for chunk in self._chunks: yield chunk class _Reply: def __init__(self, status, *, headers=None, chunks=()): self.status = status self.headers = dict(headers or {}) self.content = _Content(chunks) class _Exchange: def __init__(self, reply): self.reply = reply async def __aenter__(self): return self.reply async def __aexit__(self, *exc_info): return False class Upstream: def __init__(self, replies): self.replies = list(replies) self.authorizations = [] def request(self, method, target, **kwargs): self.authorizations.append(kwargs['headers'].get('Authorization')) return _Exchange(self.replies.pop(0)) class Request(dict): def __init__(self, headers=None): super().__init__() self.method = 'POST' self.headers = dict(headers or {}) self.transport = None class RelayOutcomeAccountingTests(unittest.IsolatedAsyncioTestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.db = str(Path(self.tmp.name) / 'newapi.db') with closing(sqlite3.connect(self.db)) as con, con: con.executescript( 'CREATE TABLE users(id INTEGER PRIMARY KEY,role INTEGER,status INTEGER,deleted_at INTEGER);' 'CREATE TABLE tokens(key TEXT,user_id INTEGER,"group" TEXT,status INTEGER,deleted_at INTEGER);' 'CREATE TABLE channels(id INTEGER PRIMARY KEY,status INTEGER,model_mapping TEXT);' 'CREATE TABLE abilities(channel_id INTEGER,model TEXT,enabled INTEGER,"group" TEXT);') con.execute('INSERT INTO users VALUES(1,100,1,NULL)') con.execute('INSERT INTO tokens VALUES("testkey",1,"default",1,NULL)') con.executemany('INSERT INTO channels VALUES(?,1,"{}")', [(1,), (2,)]) con.executemany('INSERT INTO abilities VALUES(?,"exact-model",1,"default")', [(1,), (2,)]) self.registry = ProviderRegistry(configuration(), clock=lambda: 1000.0) self.body = json.dumps({'model': MODEL}).encode() async def relay(self, upstream, success, failure=None): async def default_failure(status, raw, outgoing): return web.Response(status=status, body=raw, content_type='application/json') return await relay_selected(Request(), upstream, 'http://upstream/v1/messages', headers={}, body=self.body, registry=self.registry, newapi_db=self.db, raw_key='testkey', model=MODEL, success=success, failure=failure or default_failure) def failures(self, channel): return self.registry._circuits.get((channel, MODEL), {}).get('failures', 0) def assert_idle(self): self.assertEqual(sum(self.registry._active.values()), 0) async def test_downstream_503_from_upstream_200_counts_one_failure_and_no_retry(self): upstream = Upstream([_Reply(200)]) async def success(response): return web.Response(status=503, body=b'{"error":{"code":"model_identity_mismatch"}}') result = await self.relay(upstream, success) self.assertEqual(result.status, 503) self.assertEqual(upstream.authorizations, ['Bearer sk-testkey-1']) self.assertEqual(self.failures(1), 1) self.assert_idle() async def test_healthy_downstream_200_is_recorded_as_success(self): upstream = Upstream([_Reply(200)]) async def success(response): return web.Response(status=200, body=b'ok') result = await self.relay(upstream, success) self.assertEqual(result.status, 200) self.assertEqual(self.registry._circuits, {}) self.assertEqual(len(upstream.authorizations), 1) self.assert_idle() async def test_statusless_handler_falls_back_to_the_upstream_status(self): upstream = Upstream([_Reply(200)]) async def success(response): return None self.assertIsNone(await self.relay(upstream, success)) self.assertEqual(self.registry._circuits, {}) self.assert_idle() async def test_throttled_rejection_falls_back_once_and_both_routes_are_accounted(self): body = b'{"error":{"code":"upstream_throttled"}}' headers = {'Content-Type': 'application/json', 'Retry-After': '20'} upstream = Upstream([_Reply(429, headers=headers, chunks=[body]), _Reply(429, headers=headers, chunks=[body])]) async def success(response): self.fail('a rejected attempt must never be treated as success') result = await self.relay(upstream, success) self.assertEqual(result.status, 429) self.assertEqual(upstream.authorizations, ['Bearer sk-testkey-1', 'Bearer sk-testkey-2']) self.assertEqual((self.failures(1), self.failures(2)), (1, 1)) self.assert_idle() async def test_client_cancellation_is_not_penalized_and_releases_the_lease(self): upstream = Upstream([_Reply(200)]) async def success(response): raise asyncio.CancelledError() with self.assertRaises(asyncio.CancelledError): await self.relay(upstream, success) self.assertEqual(self.registry._circuits, {}) self.assertEqual(len(upstream.authorizations), 1) self.assert_idle() async def test_ambiguous_stream_error_is_not_replayed(self): upstream = Upstream([_Reply(200)]) async def success(response): raise aiohttp.ClientPayloadError('stream interrupted') with self.assertRaises(aiohttp.ClientPayloadError): await self.relay(upstream, success) self.assertEqual(len(upstream.authorizations), 1) self.assertEqual(self.failures(1), 1) self.assert_idle() async def test_client_side_refusal_does_not_open_a_provider_circuit(self): upstream = Upstream([_Reply(200)]) async def success(response): return web.Response(status=400, body=b'{"error":{"code":"invalid_request"}}') result = await self.relay(upstream, success) self.assertEqual(result.status, 400) self.assertEqual(self.registry._circuits, {}) self.assert_idle() if __name__ == '__main__': unittest.main()