"""A base URL set wrong is said to the person, not shown as a model that does not exist (v6.63). An OpenAI client takes http://:30001/v1 and an Anthropic one http://:30001. With one for the other, the engines answered {"detail":"Not Found"}, and Claude Code showed "There's an issue with the selected model (qwen3.8-27b). It may not exist or you may not have access to it" (2.1.326, 2026-11-30).""" import http.server import importlib.util import json import os import sys import tempfile import threading import time import unittest import urllib.error import urllib.request from pathlib import Path REPO = Path(__file__).resolve().parents[1] KEY = "k3y-of-this-test-0123456789" class Engine(http.server.BaseHTTPRequestHandler): """SGLang's: a 404 for any route but its own, and for a model it does not have.""" protocol_version = "HTTP/1.1" seen = [] def log_message(self, *a): pass def answer(self): raw = self.rfile.read(int(self.headers.get("Content-Length") or 0)) self.seen.append(self.path) ok = self.path in ("/v1/chat/completions", "/v1/messages", "/v1/models") and b"no-such-model" not in raw out = b'{"ok": true}' if ok else b'{"detail":"Not Found"}' self.send_response(200 if ok else 404) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(out))) self.end_headers() self.wfile.write(out) do_GET = do_POST = answer class Base(unittest.TestCase): WALL = None @classmethod def setUpClass(cls): saved = dict(os.environ) cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved))) cls.engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine) cls.engine.daemon_threads = True threading.Thread(target=cls.engine.serve_forever, daemon=True).start() cls.addClassCleanup(cls.engine.server_close) cls.addClassCleanup(cls.engine.shutdown) os.environ.pop("QWEN38_CLIENT_KEYS_FILE", None) if cls.WALL: fd, path = tempfile.mkstemp(suffix=".json", text=True) with open(fd, "w") as f: json.dump(cls.WALL, f) cls.addClassCleanup(os.unlink, path) os.environ["QWEN38_CLIENT_KEYS_FILE"] = path os.environ.update(UPSTREAM=f"http://127.0.0.1:{cls.engine.server_port}", CLIENT_IO_S="5", PROMPT_CEILING_TOKENS="0", PROXY_HOLD_UNITS="", QWEN38_UPSTREAM_API_KEY=KEY) spec = importlib.util.spec_from_file_location(f"kp_base_{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) cls.mod.log = lambda msg: None cls.mod._SERVED.update(names=("m",), engine="sglang", ts=time.time()) cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H) threading.Thread(target=cls.proxy.serve_forever, daemon=True).start() cls.addClassCleanup(cls.proxy.server_close) cls.addClassCleanup(cls.proxy.shutdown) cls.at = f"127.0.0.1:{cls.proxy.server_address[1]}" def ask(self, path, body=b'{"model": "m"}', key=KEY): req = urllib.request.Request(f"http://{self.at}{path}", data=body, headers={ "Authorization": f"Bearer {key}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=8) as r: return r.status, r.read() except urllib.error.HTTPError as e: return e.code, e.read() class ABaseUrlSetWrong(Base): WRONG = {"/chat/completions": "/v1/chat/completions", "/v1/v1/chat/completions": "/v1/chat/completions", "/v1//chat/completions": "/v1/chat/completions", "/v1/v1/messages": "/v1/messages", "/v1/v1/messages/count_tokens?beta=true": "/v1/messages/count_tokens", "/messages": "/v1/messages", "/v1/chat/completions/chat/completions": "/v1/chat/completions", "/responses": "/v1/responses", "/v1/messages/v1/messages": "/v1/messages", "/completions": "/v1/completions"} def test_its_refusal_names_the_right_one(self): for path, right in self.WRONG.items(): with self.subTest(path=path): Engine.seen.clear() status, raw = self.ask(path) # a 400 on the Anthropic dialect: Claude Code shows a 404 as a model that does not exist self.assertEqual(status, 400 if "messages" in path else 404) doc = json.loads(raw) self.assertIn(right, doc["error"]["message"]) self.assertIn(f"http://{self.at}/v1", doc["error"]["message"]) self.assertIn(path, Engine.seen) self.assertNotIn(right, Engine.seen, "the route is the client's, never rewritten") if "messages" in path: self.assertEqual((doc["type"], doc["error"]["type"]), ("error", "invalid_request_error")) else: self.assertEqual(doc["error"]["type"], "invalid_request_error") def test_on_a_get(self): status, raw = self.ask("/v1/v1/models", body=None) self.assertEqual(status, 404) self.assertIn("/v1/models", json.loads(raw)["error"]["message"]) def test_any_other_404_is_the_engine_s(self): for path, body in (("/v1/files", b"{}"), ("/nothing", b"{}"), ("/v1/messages/batches", b"{}"), ("/v1/chat/completions", b'{"model": "no-such-model"}')): status, raw = self.ask(path, body) self.assertEqual((status, raw), (404, b'{"detail":"Not Found"}'), path) def test_the_right_ones_are_served(self): for path in ("/v1/chat/completions", "/v1/messages"): self.assertEqual(self.ask(path)[0], 200) def test_the_host_it_repeats_is_a_host(self): hint = self.mod.base_url_hint self.assertIn("http://box.lan:30001/v1", hint("/chat/completions", "box.lan:30001")) self.assertIn("https://[fd7a::1]:30001/v1", hint("/chat/completions", "[fd7a::1]:30001", tls=True)) for host in (None, "", "a b", "