Files
alzeo/tests/test_proxy_embeddings.py
T
Hasan Basbunar ac474d15ee embeddings: the lane's installer and tests pass the static checks
The blind review of 2026-11-19 left statique.sh RED on the branch: SC2034
(IMAGE_GB declared and never read, its room check comes with the next
commit), SC2178 (missing_gb's need and size are arrays in lanes.sh, so
scalars of that name here are a silent clash: renamed fsize and miss),
SC2046 (the model's files went to gguf-fetch unquoted: mapfile into an
array), ruff F841 (a dead variable in the proxy test) and F401 (an unused
import in the pending test, hidden until now by the check's own head).
A test runs the CI's shellcheck on the installer beside lanes.sh, the
pair that reproduces what the whole-repo run sees; it fails on the
commit before.

Generated by Mistral Vibe.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 16:40:19 +01:00

196 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""The proxy and the embeddings lane (keepalive-proxy v6.62): POST /v1/embeddings goes to the
lane's engine (TEI, EMBED_UPSTREAM) while qwen38-embed.service is active, and to the text
engine as before otherwise.
The route keeps the door's key check (TEI has none of its own, and no key may be passed to it:
TEI 1.9.4 logs its argument list unredacted), no Authorization is sent to it, and no other route
goes there: /v1/models does not change. The size guard never tokenizes an embeddings body with
the text engine: today, on a box without the lane, the route passes the /v1/ prefix of
CLIENT_ROUTE_PREFIXES and _is_prompt_route, so the guard counts its body with the text engine's
tokenizer against the text lane's pool; relayed to TEI, that count would be the wrong engine's,
and the text engine may be absent altogether, so the relayed route skips the text engine's
guards whole. The fake TEI answers one vector and writes down every request it is asked; the
fake text engine answers 404 as SGLang does on a route it does not serve. systemd is asked
through PATH, so a fake systemctl stands in for it, in both directions (test_proxy_guard.py's
shape).
"""
import http.server
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest
import urllib.error
import urllib.request
sys.path.insert(0, str(pathlib.Path(__file__).parent))
import localports # noqa: E402
HERE = pathlib.Path(__file__).resolve()
REPO = HERE.parents[1]
KEY = "test-key"
def key_home():
home = pathlib.Path(tempfile.mkdtemp(prefix="proxy-embed-home-"))
(home / ".config/qwen38").mkdir(parents=True)
(home / ".config/qwen38/api-key").write_text(KEY + "\n")
return home
class TEI(http.server.BaseHTTPRequestHandler):
"""The embeddings lane's engine as the proxy meets it: one JSON answer, no key asked."""
protocol_version = "HTTP/1.1"
asked, auths, bodies = [], [], []
def log_message(self, *a):
pass
def do_POST(self):
TEI.asked.append(self.path)
TEI.auths.append(self.headers.get("Authorization"))
n = int(self.headers.get("Content-Length") or 0)
TEI.bodies.append(self.rfile.read(n))
if self.path != "/v1/embeddings":
self.send_response(404)
out = b"{}"
else:
self.send_response(200)
out = json.dumps({"object": "list", "model": "pplx-embed-v1-0.6b",
"data": [{"object": "embedding", "index": 0,
"embedding": [0.1] * 1024}]}).encode()
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
class TextEngine(http.server.BaseHTTPRequestHandler):
"""The text engine on a route it does not serve: SGLang's own 404, as a box without the
lane always had."""
protocol_version = "HTTP/1.1"
asked = []
def log_message(self, *a):
pass
def _answer(self, code, doc):
out = json.dumps(doc).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
def do_POST(self):
TextEngine.asked.append(self.path)
self._answer(404, {"error": "not found"})
def do_GET(self):
TextEngine.asked.append(self.path)
self._answer(200, {"object": "list", "data": [{"id": "qwen3.8-27b", "object": "model"}]})
class TheRelay(unittest.TestCase):
def setUp(self):
self.homes = [key_home()]
self.addCleanup(lambda: [shutil.rmtree(h, True) for h in self.homes])
self.tei = http.server.ThreadingHTTPServer(("127.0.0.1", 0), TEI)
self.text = http.server.ThreadingHTTPServer(("127.0.0.1", 0), TextEngine)
for s in (self.tei, self.text):
threading.Thread(target=s.serve_forever, daemon=True).start()
self.addCleanup(s.shutdown)
self.addCleanup(s.server_close)
TEI.asked[:], TEI.auths[:], TEI.bodies[:], TextEngine.asked[:] = [], [], [], []
def spawn(self, embed_active):
fake = pathlib.Path(tempfile.mkdtemp(prefix="fake-systemctl-"))
self.addCleanup(shutil.rmtree, fake, True)
(fake / "systemctl").write_text(
"#!/bin/sh\n"
f'[ "$*" = "is-active --quiet qwen38-embed.service" ] && exit {0 if embed_active else 3}\n'
"exit 3\n")
(fake / "systemctl").chmod(0o755)
env = dict(os.environ,
UPSTREAM=f"http://127.0.0.1:{self.text.server_port}",
EMBED_UPSTREAM=f"http://127.0.0.1:{self.tei.server_port}",
PATH=f"{fake}:{os.environ.get('PATH', '')}", HOME=str(self.homes[0]))
proc, port = localports.spawn(lambda port: subprocess.Popen(
[sys.executable, str(REPO / "keepalive-proxy.py"), str(port)],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
self.addCleanup(lambda: (proc.terminate(), proc.wait(timeout=5)))
return port
def ask(self, port, path, body=None, key=KEY):
headers = {"Content-Type": "application/json"}
if key is not None:
headers["Authorization"] = f"Bearer {key}"
req = urllib.request.Request(f"http://127.0.0.1:{port}{path}",
data=json.dumps(body or {}).encode() if body is not None else None,
headers=headers, method="POST" if body is not None else "GET")
try:
with urllib.request.urlopen(req, timeout=10) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def embeddings(self):
return {"model": "pplx-embed-v1-0.6b", "input": ["un texte", "un autre"]}
def test_with_the_lane_active_the_route_goes_to_its_engine(self):
port = self.spawn(embed_active=True)
status, raw = self.ask(port, "/v1/embeddings", self.embeddings())
self.assertEqual(status, 200, raw[:200])
doc = json.loads(raw)
self.assertEqual(doc["model"], "pplx-embed-v1-0.6b")
self.assertEqual(len(doc["data"][0]["embedding"]), 1024)
self.assertEqual(TEI.asked, ["/v1/embeddings"])
self.assertEqual(json.loads(TEI.bodies[0]), self.embeddings())
self.assertEqual(TextEngine.asked, [], "the text engine was asked nothing")
def test_no_key_of_any_kind_is_sent_to_it(self):
"""The client's key is checked at the door and never relayed: TEI has no authentication,
and a key passed to it would land in its journal (TEI 1.9.4 prints its arguments)."""
port = self.spawn(embed_active=True)
self.ask(port, "/v1/embeddings", self.embeddings())
self.assertEqual(TEI.auths, [None])
def test_without_the_key_the_door_refuses_it_before_anything(self):
port = self.spawn(embed_active=True)
status, raw = self.ask(port, "/v1/embeddings", self.embeddings(), key=None)
self.assertEqual(status, 401)
self.assertEqual(TEI.asked, [])
self.assertEqual(TextEngine.asked, [])
def test_its_engine_silent_is_a_503_to_try_again(self):
self.tei.shutdown()
self.tei.server_close()
port = self.spawn(embed_active=True)
status, raw = self.ask(port, "/v1/embeddings", self.embeddings())
self.assertEqual(status, 503)
self.assertEqual(json.loads(raw)["error"]["type"], "engine_unavailable")
def test_without_the_lane_the_route_goes_to_the_text_engine_as_before(self):
port = self.spawn(embed_active=False)
status, raw = self.ask(port, "/v1/embeddings", self.embeddings())
self.assertEqual(status, 404, "the text engine's own answer, as on a box without the lane")
self.assertEqual(TEI.asked, [])
self.assertIn("/v1/embeddings", TextEngine.asked)
def test_no_other_route_goes_to_its_engine(self):
port = self.spawn(embed_active=True)
self.ask(port, "/v1/chat/completions", {"model": "qwen3.8-27b", "messages": []})
self.ask(port, "/v1/models")
self.assertEqual(TEI.asked, [], "the embeddings engine is asked nothing but its route")
self.assertIn("/v1/chat/completions", TextEngine.asked)
self.assertIn("/v1/models", TextEngine.asked)
if __name__ == "__main__":
unittest.main()