Files
alzeo/tests/test_proxy_schema_mend.py

183 lines
9.8 KiB
Python

"""A tool schema of another draft no longer ends a session (v6.63).
SGLang checks every tool's parameters against JSON Schema 2020-12 (serving_chat.py, v0.5.21:
Draft202012Validator.check_schema), whatever draft wrote them: a tuple (zod's z.tuple, draft 7), a boolean
exclusiveMinimum (OpenAPI 3.0), a null required or properties (a nil slice of Go's), a required on the
property (draft 3) were each a 400 to every request of the session. That the meaning is kept was checked
with jsonschema 4.26.0 on 2026-11-30: each case below refused by 2020-12 before and taken after, the same 37
instances accepted and refused by the draft it was written for and by 2020-12 after, and 3,000 valid
schemas at random untouched."""
import http.server
import importlib.util
import json
import os
import sys
import threading
import time
import unittest
import urllib.request
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
S, N = {"type": "string"}, {"type": "number"}
class Base(unittest.TestCase):
@classmethod
def setUpClass(cls):
saved = dict(os.environ)
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
os.environ.pop("QWEN38_CLIENT_KEYS_FILE", None)
spec = importlib.util.spec_from_file_location(f"kp_schema_{time.time_ns()}", REPO / "keepalive-proxy.py")
cls.mod = importlib.util.module_from_spec(spec)
sys.argv = ["keepalive-proxy.py"]
spec.loader.exec_module(cls.mod)
@staticmethod
def body(schema, anthropic=False):
tool = {"name": "f", "input_schema": schema} if anthropic else {"type": "function", "function": {"name": "f", "parameters": schema}}
return json.dumps({"model": "m", "messages": [{"role": "user", "content": "x"}], "tools": [tool]}).encode()
def mend(self, schema, anthropic=False):
out, words = self.mod.mend_tool_schemas(self.body(schema, anthropic), "/v1/messages" if anthropic else "/v1/chat/completions")
tool = json.loads(out)["tools"][0]
return (tool["input_schema"] if anthropic else tool["function"]["parameters"]), words
class ASchemaOfAnotherDraftIsWrittenIn2020sWords(Base):
CASES = [
({"type": "array", "items": [S, N]}, {"type": "array", "prefixItems": [S, N]}, ("items",)),
({"type": "array", "items": [S], "additionalItems": False}, {"type": "array", "prefixItems": [S], "items": False}, ("items",)),
({"items": [N], "additionalItems": S, "minItems": 1}, {"prefixItems": [N], "items": S, "minItems": 1}, ("items",)),
({"type": "array", "items": []}, {"type": "array"}, ("items",)),
({"minimum": 0, "exclusiveMinimum": True}, {"exclusiveMinimum": 0}, ("exclusiveMinimum",)),
({"minimum": 0, "exclusiveMinimum": False}, {"minimum": 0}, ("exclusiveMinimum",)),
({"exclusiveMinimum": True}, {}, ("exclusiveMinimum",)),
({"maximum": 1.5, "exclusiveMaximum": True}, {"exclusiveMaximum": 1.5}, ("exclusiveMaximum",)),
({"type": "object", "properties": {"a": S}, "required": None}, {"type": "object", "properties": {"a": S}}, ("required",)),
({"type": "object", "properties": None}, {"type": "object", "properties": {}}, ("properties",)),
({"type": "object", "properties": {"a": {"type": "string", "required": True}, "b": {"type": "number", "required": False}}},
{"type": "object", "properties": {"a": S, "b": N}, "required": ["a"]}, ("required",)),
({"type": "object", "properties": {"a": {"required": True}, "b": {"required": True}}, "required": ["b"]},
{"type": "object", "properties": {"a": {}, "b": {}}, "required": ["b", "a"]}, ("required",)),
]
def test_at_the_top_and_wherever_a_schema_stands(self):
wraps = [lambda s: s, lambda s: {"type": "object", "properties": {"p": s}}, lambda s: {"$defs": {"d": s}},
lambda s: {"anyOf": [{"type": "null"}, s]}, lambda s: {"type": "array", "items": s},
lambda s: {"additionalProperties": s}, lambda s: {"not": s}, lambda s: {"prefixItems": [s]},
lambda s: {"definitions": {"d": {"allOf": [s]}}}]
for given, want, words in self.CASES:
for wrap in wraps:
for anthropic in (False, True):
with self.subTest(given=given, at=wrap({}), anthropic=anthropic):
self.assertEqual(self.mend(wrap(given), anthropic), (wrap(want), words))
def test_the_keys_keep_their_order(self):
got, _ = self.mend({"title": "t", "items": [S], "description": "d"})
self.assertEqual(list(got), ["title", "prefixItems", "description"])
def test_twice_is_once(self):
for given, _, _ in self.CASES:
once, _ = self.mend(given)
out, words = self.mod.mend_tool_schemas(self.body(once), "/v1/chat/completions")
self.assertEqual((out, words), (self.body(once), ()))
def test_a_schema_nested_past_reason_is_left_to_the_engine(self):
schema = {"items": [S]}
for _ in range(200):
schema = {"properties": {"p": schema}}
self.assertEqual(self.mend(schema), (schema, ()))
class AValidSchemaIsNeverTouched(Base):
def test_its_body_goes_on_byte_for_byte(self):
for schema in ({"type": "object", "properties": {"items": {"type": "array", "items": S}, "required": {"type": "boolean"},
"properties": {"type": "object"}, "exclusiveMinimum": N}, "required": ["items"]},
{"type": "array", "prefixItems": [S], "items": False}, {"exclusiveMinimum": 0}, {"type": "object", "required": []},
{"type": "object", "default": {"items": [1], "required": None, "properties": None, "exclusiveMinimum": True}},
{"enum": [{"items": [1]}, {"required": True}], "examples": [{"properties": None}], "const": {"items": []}}):
for anthropic in (False, True):
body = self.body(schema, anthropic)
out, words = self.mod.mend_tool_schemas(body, "/v1/messages" if anthropic else "/v1/chat/completions")
self.assertIs(out, body, schema)
self.assertEqual(words, ())
def test_what_is_not_a_tool_s_schema_is_data(self):
bad = {"items": [S], "required": None}
for doc in ({"messages": [{"role": "user", "content": json.dumps(bad)}]}, {"messages": [], "metadata": bad},
{"messages": [{"role": "assistant", "tool_calls": [{"function": {"name": "f", "arguments": bad}}]}]},
{"response_format": {"json_schema": {"schema": bad}}}, {"tools": bad}, {"tools": [None, "x", {"function": "y"}]}):
body = json.dumps(doc).encode()
self.assertEqual(self.mod.mend_tool_schemas(body, "/v1/chat/completions"), (body, ()))
def test_odd_bodies(self):
for body in (b"", b'not json "items": [', b'["items": [', b'[{"items": [1]}]'):
self.assertEqual(self.mod.mend_tool_schemas(body, "/v1/chat/completions"), (body, ()))
body = self.body({"items": [S]})
self.assertEqual(self.mod.mend_tool_schemas(body, "/generate"), (body, ()))
class Engine(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
seen = []
def log_message(self, *a):
pass
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
if self.path in ("/v1/chat/completions", "/v1/messages"):
self.seen.append(raw)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"{}")
class TheEngineGetsThem(Base):
@classmethod
def setUpClass(cls):
engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
engine.daemon_threads = True
threading.Thread(target=engine.serve_forever, daemon=True).start()
cls.addClassCleanup(engine.server_close)
cls.addClassCleanup(engine.shutdown)
saved = dict(os.environ) # before its own are set: Base's copy is of these
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
os.environ.update(UPSTREAM=f"http://127.0.0.1:{engine.server_port}", PROXY_HOLD_UNITS="", QWEN38_UPSTREAM_API_KEY="k" * 20)
super().setUpClass()
cls.journal = []
cls.mod.log = cls.journal.append
cls.mod._SERVED.update(names=("m",), engine="sglang", ts=time.time())
cls.mod._POOL.update(tokens=10_000_000, window=1000, ts=time.time())
proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H)
threading.Thread(target=proxy.serve_forever, daemon=True).start()
cls.addClassCleanup(proxy.server_close)
cls.addClassCleanup(proxy.shutdown)
cls.at = f"http://127.0.0.1:{proxy.server_address[1]}"
def sent(self, schema, anthropic=False):
Engine.seen.clear()
body = self.body(schema, anthropic)
req = urllib.request.Request(self.at + ("/v1/messages" if anthropic else "/v1/chat/completions"), data=body, headers={
"Authorization": "Bearer " + "k" * 20, "Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=8).read()
return Engine.seen[0], body
def test_mended_and_said_once_a_word(self):
for anthropic in (False, True):
raw, _ = self.sent({"type": "object", "properties": {"p": {"type": "array", "items": [S, N]}}}, anthropic)
self.assertIn(b'"prefixItems"', raw)
self.assertNotIn(b'"items"', raw)
self.assertEqual(len([ln for ln in self.journal if "tool schema: 'items'" in ln]), 1, self.journal)
def test_a_valid_one_byte_for_byte(self):
raw, body = self.sent({"type": "object", "properties": {"items": {"type": "array", "items": S}}, "required": ["items"]})
self.assertEqual(raw, body)
if __name__ == "__main__":
unittest.main()