Files
alzeo/tests/test_proxy_embeddings.py
T
Hasan BasbunarandClaude Opus 5.5 ce2d2124c4 renumbering: v1.60.0 takes the proxy versions after v6.62, which the Inkling lane's v1.59.0 holds
The embeddings lane ships as v1.60.0, after v1.58.0 (the speech lane by default) and v1.59.0
(the Inkling lane, prepared on a branch of its own, which takes the next proxy version, v6.62, as
every text lane of the pair's routes did: v6.60 for LFM2.5, v6.61 for LFM3). The lane's commits
took v6.62 and v6.63 when they were written on v1.55.0; they become v6.63 (the relay) and v6.64
(the port read from the lane's unit) everywhere they appear: keepalive-proxy.py's header, history
notes and start-up log, tests/test_proxy_embeddings.py's docstring, dashboard/tests/test_lifecycle.py's
comment. The comments that dated the lane to v1.53 or v1.56 say v1.60 (cockpit.py, base.js,
test_embed_cockpit.py, ci.yml). The relay's behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 16:40:20 +01:00

221 lines
10 KiB
Python

#!/usr/bin/env python3
"""The proxy and the embeddings lane (keepalive-proxy v6.64): 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 400 as SGLang does on a route it does not serve (the answer the lane's
proof measured). 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 400, the answer the lane's
proof measured through the proxy without the lane (and with it stopped), 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(400, {"error": "no such route"})
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, embed_upstream=True, unit_file=None):
"""embed_upstream: False leaves EMBED_UPSTREAM unset, so the proxy reads the lane's port
where it poses it, the --port of the unit EMBED_UNIT_FILE names (the installed unit in
production; a fake one here)."""
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}",
PATH=f"{fake}:{os.environ.get('PATH', '')}", HOME=str(self.homes[0]))
if embed_upstream:
env["EMBED_UPSTREAM"] = f"http://127.0.0.1:{self.tei.server_port}"
if unit_file is not None:
env["EMBED_UNIT_FILE"] = str(unit_file)
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, 400, "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_the_port_is_read_where_the_lane_poses_it(self):
"""EMBED_PORT moves the lane's engine (install-embeddings.sh renders the unit's --port
from it) and the proxy followed a port written in advance: with EMBED_PORT=30128 the
relay kept aiming at 30028, a 503 as long as the lane served (the blind review of
2026-11-20). With EMBED_UPSTREAM unset the relay aims at the --port of the lane's own
unit, read again every few seconds so a lane installed later is followed too."""
d = pathlib.Path(tempfile.mkdtemp(prefix="fake-embed-unit-"))
self.addCleanup(shutil.rmtree, d, True)
unit = d / "qwen38-embed.service"
unit.write_text("[Service]\n"
"ExecStart=/usr/bin/docker run --rm --name qwen38-embed "
f"--hostname 127.0.0.1 --port {self.tei.server_port}\n")
port = self.spawn(embed_active=True, embed_upstream=False, unit_file=unit)
status, raw = self.ask(port, "/v1/embeddings", self.embeddings())
self.assertEqual(status, 200, raw[:200])
self.assertEqual(TEI.asked, ["/v1/embeddings"])
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()