mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 12:54:19 +01:00
The branch was cut before v1.59.1. Its proxy roles take the next two version numbers, its installer's disk figures add its 5 GB to v1.59.1's, its card keeps the Lanes view's order and the lanes' boot button with its own systemd verbs, and its tests of an empty chunked body send the chunk the proxy reads since v6.63. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
250 lines
12 KiB
Python
250 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""The proxy and the embeddings lane (keepalive-proxy v6.65): 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)
|
|
|
|
def raw(self, port, head):
|
|
"""The proxy's answer to a request written by hand: its status line and its body, or what
|
|
the socket gave when the proxy closed it with no answer."""
|
|
import socket
|
|
with socket.create_connection(("127.0.0.1", port), timeout=10) as s:
|
|
s.sendall(head.encode())
|
|
got = b""
|
|
while True:
|
|
chunk = s.recv(65536)
|
|
if not chunk:
|
|
break
|
|
got += chunk
|
|
status, _, rest = got.partition(b"\r\n")
|
|
return status.decode(errors="replace"), rest.partition(b"\r\n\r\n")[2]
|
|
|
|
def test_a_post_with_no_body_is_refused_in_json_not_cut(self):
|
|
"""A POST of the route with the key and no body, by Content-Length 0 or an empty chunked one (read since
|
|
v6.63), reached the relay with body None: len(None) raised, and the client's connection was cut with
|
|
no answer at all (code review of v1.60.0). It is a 400 in JSON, and the engine is asked nothing."""
|
|
port = self.spawn(embed_active=True)
|
|
for how in ("Content-Length: 0\r\n", "Transfer-Encoding: chunked\r\n"):
|
|
with self.subTest(how=how.strip()):
|
|
status, body = self.raw(port, f"POST /v1/embeddings HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {KEY}\r\n"
|
|
f"Content-Type: application/json\r\n{how}Connection: close\r\n\r\n"
|
|
+ ("0\r\n\r\n" if "chunked" in how else ""))
|
|
self.assertEqual(status, "HTTP/1.1 400 Bad Request", (status, body))
|
|
self.assertEqual(json.loads(body)["error"]["type"], "invalid_request", body)
|
|
self.assertEqual(TEI.asked, [], "the engine is asked nothing")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|