Files
iishko-public/tests/test_model_metadata_transport.py
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

255 lines
11 KiB
Python

"""Transport regressions: GET /v1/models metadata on the transparent (is_api) path.
The production skin proxies every ``/v1/`` call through the transparent branch, so the
catalogue hook must run there too. Each case drives the skin's real helper plus the real
``relay_api`` over a real aiohttp upstream and a real HTTP client: one upstream request,
enriched 200 JSON, byte-exact fallbacks, no replay on errors and no corrupted gzip.
"""
import ast
import asyncio
import gzip
import json
import logging
import os
import sys
import aiohttp
import pytest
from aiohttp import web
from multidict import CIMultiDict
from yarl import URL
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
CANON_SKIN = os.path.join(ROOT, "gateway", "grok-web-skin.py")
CANDIDATE_SKIN = os.environ.get("IISHKO_CANDIDATE_SKIN")
SPECS = os.path.join(ROOT, "bot", "model_specs.json")
sys.path.insert(0, os.path.join(ROOT, "gateway"))
import model_metadata
from gateway_errors import HOP_HEADERS
from transparent_api import relay_api
SKINS = [CANON_SKIN] + ([CANDIDATE_SKIN] if CANDIDATE_SKIN else [])
SKINS = [path for path in SKINS if os.path.exists(path)]
SKIN_IDS = ["canonical", "candidate"][:len(SKINS)]
HELPERS = ("_attach_model_metadata", "_models_catalogue_response", "response_headers")
CATALOGUE = {"object": "list", "data": [
{"id": "grok-4.6", "object": "model", "owned_by": "x-ai"},
{"id": "totally-unknown-model", "object": "model", "owned_by": "vendor-x"},
{"id": "glm-5.3", "object": "model", "owned_by": "z-ai", "tags": ["chat"]},
]}
def _parsed(path):
with open(path, encoding="utf-8") as handle:
source = handle.read()
return source, ast.parse(source)
def _skin(path):
"""Exec the real helpers of a skin plus the transparent-path dispatch shim."""
_source, tree = _parsed(path)
funcs = {node.name: node for node in tree.body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
ns = {
"asyncio": asyncio, "json": json, "os": os, "aiohttp": aiohttp, "web": web,
"URL": URL, "CIMultiDict": CIMultiDict, "HOP_HEADERS": HOP_HEADERS,
"LOG": logging.getLogger("models-transport"), "model_metadata": model_metadata,
"relay_api": relay_api, "UPSTREAM": "http://127.0.0.1:1",
"_key_balance_usd": lambda key: 7.5,
}
for name in HELPERS:
node = funcs[name]
exec(compile(ast.Module(body=[node], type_ignores=[]), path, "exec"), ns)
return ns
class _Skin:
"""Full transparent dispatch of one skin: hook first, relay_api on the same upstream."""
def __init__(self, ns, upstream):
self.ns = ns
self.upstream = upstream.rstrip("/")
self.ns["UPSTREAM"] = self.upstream
async def __call__(self, request):
req = request
headers = dict(req.headers)
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=30)) as session:
if self.ns["_models_catalogue_response"].__code__.co_kwonlyargcount:
# candidate shape: the helper owns the single session.request.
return await self.ns["_models_catalogue_response"](
req, session, headers=headers, body=b"",
balance_lookup=self.ns["_key_balance_usd"])
async with session.request("GET", URL(self.upstream + req.raw_path),
headers=headers, auto_decompress=False,
skip_auto_headers={"Accept-Encoding"}) as upstream:
if req.method == "GET" and req.path == "/v1/models":
response = await self.ns["_models_catalogue_response"](req, upstream)
if response is not None:
return response
return await self.ns["relay_api"](req, upstream)
class _Upstream:
def __init__(self, status=200, body=b"{}", headers=None):
self.status, self.body = status, body
self.headers = headers or {}
self.hits = 0
async def __call__(self, request):
self.hits += 1
return web.Response(status=self.status, body=self.body, headers=self.headers)
async def _exercise(ns, script):
"""Serve one scripted upstream and the skin dispatch over real HTTP; return (client, hits)."""
upstream = _Upstream(*script)
upstream_app = web.Application()
upstream_app["seen"] = upstream
upstream_app.router.add_route("*", "/{tail:.*}", upstream)
runner = web.AppRunner(upstream_app)
await runner.setup()
site = web.TCPSite(runner, "127.0.0.1", 0)
await site.start()
port = site._server.sockets[0].getsockname()[1]
skin = _Skin(ns, "http://127.0.0.1:%d" % port)
gateway = web.Application()
async def handler(request):
return await skin(request)
gateway.router.add_route("*", "/{tail:.*}", handler)
gateway_runner = web.AppRunner(gateway)
await gateway_runner.setup()
gateway_site = web.TCPSite(gateway_runner, "127.0.0.1", 0)
await gateway_site.start()
gateway_port = gateway_site._server.sockets[0].getsockname()[1]
session = aiohttp.ClientSession()
response = await session.get("http://127.0.0.1:%d/v1/models" % gateway_port,
headers={"Authorization": "Bearer test-key"})
body = await response.read()
result = (response.status, dict(response.headers), body, upstream.hits)
await response.release()
await session.close()
for closing in (gateway_runner, runner):
await closing.cleanup()
return result
def _run(skin_path, script):
pytest.importorskip("aiohttp")
ns = _skin(skin_path)
return asyncio.run(_exercise(ns, script))
def _json_script(payload, headers=None, status=200):
body = json.dumps(payload).encode()
return (status, body, dict({"Content-Type": "application/json"}, **(headers or {})))
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
def test_models_get_carries_metadata_in_one_upstream_request(skin, monkeypatch):
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
model_metadata.reload()
status, _headers, body, hits = _run(skin, _json_script(CATALOGUE))
assert status == 200 and hits == 1
payload = json.loads(body)
assert [row["id"] for row in payload["data"]] == [row["id"] for row in CATALOGUE["data"]]
assert payload["object"] == "list"
known, unknown, other = payload["data"]
assert known["owned_by"] == "x-ai" and other["tags"] == ["chat"]
assert known["model_metadata"]["context_window"] == 500000
assert known["model_metadata"]["gateway_verified"] is False
assert unknown["model_metadata"]["known"] is False
assert unknown["model_metadata"]["context_window"] is None
assert other["model_metadata"]["known"] is True
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
@pytest.mark.parametrize("validator_names", [
("ETag", "Content-MD5"), ("etag", "content-md5"), ("Etag", "Content-Md5"),
])
def test_models_get_drops_stale_validators(skin, monkeypatch, validator_names):
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
model_metadata.reload()
headers = dict(zip(validator_names, ('"stale"', "c29tZS1kaWdlc3Q=")))
status, response_headers, body, hits = _run(skin, _json_script(CATALOGUE, headers))
assert status == 200 and hits == 1
assert "model_metadata" in json.loads(body)["data"][0]
lowered = {key.lower() for key in response_headers}
assert "etag" not in lowered and "content-md5" not in lowered
assert int(response_headers["Content-Length"]) == len(body)
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
def test_models_get_without_reference_is_byte_exact(skin, monkeypatch):
monkeypatch.setenv("IISHKO_MODEL_SPECS", "")
model_metadata.reload()
raw = b'{"data": [ {"id": "grok-4.6"} ] }'
status, _headers, body, hits = _run(skin, (200, raw, {"Content-Type": "application/json"}))
assert status == 200 and hits == 1
assert body == raw
assert "model_metadata" not in body.decode()
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
def test_models_get_unparseable_body_is_byte_exact(skin, monkeypatch):
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
model_metadata.reload()
raw = b'{"data": ['
status, _headers, body, hits = _run(skin, (200, raw, {"Content-Type": "application/json"}))
assert status == 200 and hits == 1
assert body == raw
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
def test_models_get_gzip_reply_is_not_corrupted(skin, monkeypatch):
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
model_metadata.reload()
packed = gzip.compress(json.dumps(CATALOGUE).encode())
status, headers, body, hits = _run(
skin, (200, packed, {"Content-Type": "application/json", "Content-Encoding": "gzip"}))
assert status == 200 and hits == 1
assert headers["Content-Type"].startswith("application/json")
assert [row["id"] for row in json.loads(body)["data"]] == [row["id"] for row in CATALOGUE["data"]]
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
def test_models_error_is_normalized_without_replay(skin, monkeypatch):
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
model_metadata.reload()
payload = {"error": {"message": "slow down", "type": "rate_limit_error"}}
status, headers, body, hits = _run(skin, _json_script(payload, status=429))
assert hits == 1
assert status == 429 # Explicit upstream busy remains retryable without inventing a 503.
assert headers["Content-Type"].startswith("application/json")
assert json.loads(body)["error"]["code"] == "upstream_busy"
assert json.loads(body)["error"]["retryable"] is True
assert "model_metadata" not in body.decode()
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
def test_hook_is_wired_after_gates_before_transparent_dispatch(skin):
_source, tree = _parsed(skin)
proxy = next(node for node in tree.body
if isinstance(node, ast.AsyncFunctionDef) and node.name == "proxy")
calls = [node for node in ast.walk(proxy) if isinstance(node, ast.Call)
and isinstance(node.func, ast.Name) and node.func.id == "_models_catalogue_response"]
assert len(calls) == 1, "single hook call inside the handler"
hook = calls[0]
guard = [node for node in ast.walk(proxy) if isinstance(node, ast.If)
and "/v1/models" in ast.dump(node.test) and "GET" in ast.dump(node.test)]
assert guard and guard[0].lineno < hook.lineno < guard[0].end_lineno
dispatch = [node.lineno for node in ast.walk(proxy) if isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id in ("relay_api", "relay_api_request")]
assert [line for line in dispatch if line > hook.lineno], "dispatch stays after the hook"
for gate in ("gate_check", "_rl_check_sync"):
located = [node.lineno for node in ast.walk(proxy) if isinstance(node, ast.Call)
and ((isinstance(node.func, ast.Name) and node.func.id == gate)
or (isinstance(node.func, ast.Attribute) and node.func.attr == "to_thread"
and node.args and isinstance(node.args[0], ast.Name)
and node.args[0].id == gate))]
assert located and max(located) < hook.lineno, "gate %s runs before the hook" % gate