"""Gateway wiring regressions: model metadata attach point and unpinned effort schema. Static/behavioural checks on the canonical skin, plus the live-vintage candidate from skin.baseline.py when ``IISHKO_CANDIDATE_SKIN`` points at it (the Linux stage does not have a Windows path baked in). Boundary claims are proven on the AST of ``proxy()``, not by text offsets: a def or an unrelated symbol earlier in the file must not be able to satisfy them. """ import ast import os import sys import pytest 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") EFFORT_PATHS = ("/v1/chat/completions", "/v1/responses") MODELS_PATHS = ("/v1/models", "/api/user/models") SKINS = [CANON_SKIN] + ([CANDIDATE_SKIN] if CANDIDATE_SKIN else []) SKINS = [p for p in SKINS if os.path.exists(p)] SKIN_IDS = ["canonical", "candidate"][:len(SKINS)] def _read(path): with open(path, encoding="utf-8") as handle: return handle.read() def _parsed(path): source = _read(path) return source, ast.parse(source) FUNCTION_NODES = (ast.FunctionDef, ast.AsyncFunctionDef) def _functions(tree): """Module-level definitions only: a nested def must not shadow the real handler.""" return {node.name: node for node in tree.body if isinstance(node, FUNCTION_NODES)} def _text(node): return ast.dump(node) def _path_to(node, target): """Ancestors of ``target`` from ``node`` (outermost first), or None.""" if node is target: return [node] for child in ast.iter_child_nodes(node): found = _path_to(child, target) if found is not None: return [node] + found return None def _function(tree, source, names): functions = _functions(tree) for name in names: if name in functions: return functions[name] pytest.fail("none of %s found in %s" % (names, source)) def _proxy(tree, source): return _function(tree, source, ("proxy", "handle", "handler")) def _line_of(predicate, root): for node in ast.walk(root): if isinstance(node, ast.stmt) and predicate(node): return node return None def _contains_call(node, name): return any(isinstance(item, ast.Call) and ((isinstance(item.func, ast.Name) and item.func.id == name) or (isinstance(item.func, ast.Attribute) and item.func.attr == name)) for item in ast.walk(node)) @pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS) def test_skin_imports_the_shared_validator(path): source, tree = _parsed(path) assert "from request_effort import InvalidEffort, read_effort" in source imported = {alias.name for node in ast.walk(tree) if isinstance(node, ast.ImportFrom) and node.module == "request_effort" for alias in node.names} assert {"InvalidEffort", "read_effort"} <= imported if os.path.basename(path) != "skin.candidate.py": return # Live vintage ships no pinned relay package; introducing one would not import at all. assert "gateway_providers" not in source for forbidden in ("ProviderError", "denial_response"): assert forbidden not in source, "live vintage has no %s: do not introduce it" % forbidden @pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS) def test_effort_guard_precedes_body_rewrites(path): source, tree = _parsed(path) proxy = _proxy(tree, path) parse_stmt = _line_of( lambda node: isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "request_object" for t in node.targets) and isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Attribute) and node.value.func.attr == "loads", proxy) guard = _line_of( lambda node: isinstance(node, ast.If) and any(isinstance(inner, ast.ExceptHandler) and inner.type is not None and "InvalidEffort" in ast.dump(inner.type) for inner in ast.walk(node)), proxy) normalize = _line_of( lambda node: isinstance(node, ast.If) and _contains_call(node, "_normalize_developer_roles"), proxy) assert parse_stmt is not None and guard is not None and normalize is not None # All three live in proxy() itself, not in module-level helpers sharing a name. assert parse_stmt.lineno < guard.lineno < normalize.lineno @pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS) def test_invalid_effort_returns_the_contract_400(path): _source, tree = _parsed(path) proxy = _proxy(tree, path) guard = _line_of( lambda node: isinstance(node, ast.If) and any(isinstance(inner, ast.ExceptHandler) and inner.type is not None and "InvalidEffort" in ast.dump(inner.type) for inner in ast.walk(node)), proxy) assert guard is not None dumped = ast.dump(guard) assert "invalid_effort" in dumped and "invalid_request_error" in dumped assert "retryable" in dumped and "status" in dumped and "400" in dumped # POST-only, gated on the two unpinned endpoints, and the parsed object itself. gated = ast.dump(guard.test) if isinstance(guard, ast.If) else dumped for token in ('"POST"', "/v1/chat/completions", "/v1/responses", "rstrip", "isinstance", "read_effort"): assert token.replace('"', '') in gated.replace('"', ''), token # The guard consumes the parsed dict and only returns an error: it never # re-serializes or rewrites the request bytes. for inner in ast.walk(guard): assert not _contains_call(inner, "json.dumps") or not isinstance(inner, ast.stmt) if isinstance(inner, ast.Return): assert _contains_call(inner, "json_response") @pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS) def test_metadata_attach_only_under_models_get_branch(path): _source, tree = _parsed(path) calls = [node for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "_attach_model_metadata"] # Two branches carry the catalogue: the legacy relay() enrichment and the transparent # GET /v1/models hook. Both must stay scoped to a models GET, never to generation. assert len(calls) == 2, "legacy relay branch + transparent /v1/models hook" top_level = {node for node in tree.body if isinstance(node, FUNCTION_NODES)} for call in calls: chain = _path_to(tree, call) owner = [node for node in chain if isinstance(node, FUNCTION_NODES)] assert owner and isinstance(owner[-1], ast.AsyncFunctionDef), "attach must be in a handler" assert owner[-1] in top_level, "attach owner must be a module-level handler" guards = [node for node in chain if isinstance(node, ast.If)] models_guard = [node for node in guards if any(tok in ast.dump(node.test) for tok in MODELS_PATHS)] assert models_guard, "attach must sit under the models branch" get_guard = [node for node in models_guard if "GET" in ast.dump(node.test)] assert get_guard, "models branch must be the GET path" @pytest.mark.skipif(not SKINS, reason="no skin available") def test_attach_result_is_used_to_reserialize_only_then(): path = SKINS[0] _source, tree = _parsed(path) calls = [node for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "_attach_model_metadata"] assert len(calls) == 2, "legacy relay branch + transparent /v1/models hook" for call in calls: owners = [node for node in _path_to(tree, call) if isinstance(node, ast.If)] assert owners, "attach result must gate a re-serialization" reserializing = [node for node in owners if "_attach_model_metadata" in ast.dump(node.test)] assert reserializing, "each attach result must be consumed by its own guard" for node in reserializing: inner = ast.dump(node) assert "dumps" in inner and "encode" in inner def _load_attach(path): """Exec only the module-level helper out of the script (no aiohttp side effects).""" _source, tree = _parsed(path) node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_attach_model_metadata") globals_ = {"json": __import__("json"), "model_metadata": __import__("model_metadata")} class _Log: def warning(self, *a, **k): pass globals_["LOG"] = _Log() exec(compile(ast.Module(body=[node], type_ignores=[]), path, "exec"), globals_) return globals_["_attach_model_metadata"] @pytest.mark.skipif(not SKINS, reason="no skin available") def test_attach_helper_enriches_rows_without_touching_ids(): attach = _load_attach(SKINS[0]) env = {"object": "list", "data": [{"id": "grok-4.6", "object": "model", "owned_by": "x-ai"}, {"id": "unknown-model"}]} assert attach(env) is True assert [row["id"] for row in env["data"]] == ["grok-4.6", "unknown-model"] assert env["data"][0]["owned_by"] == "x-ai" assert env["data"][0]["model_metadata"]["context_window"] == 500000 assert env["data"][1]["model_metadata"]["known"] is False @pytest.mark.skipif(not SKINS, reason="no skin available") def test_attach_helper_keeps_raw_body_when_reference_is_unusable(monkeypatch): attach = _load_attach(SKINS[0]) module = sys.modules["model_metadata"] monkeypatch.setattr(module, "attach_rows", lambda rows: (_ for _ in ()).throw(RuntimeError("boom"))) env = {"object": "list", "data": [{"id": "grok-4.6"}]} assert attach(env) is False assert env == {"object": "list", "data": [{"id": "grok-4.6"}]} @pytest.mark.skipif(not SKINS, reason="no skin available") def test_attach_helper_ignores_env_without_model_rows(): attach = _load_attach(SKINS[0]) env = {"object": "list", "data": [{"object": "model"}]} assert attach(env) is False assert env == {"object": "list", "data": [{"object": "model"}]}