mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
479 lines
26 KiB
Python
479 lines
26 KiB
Python
#!/usr/bin/env python3
|
|
"""The proxy and the embeddings lanes (keepalive-proxy v6.66): POST /v1/embeddings goes to the
|
|
embeddings lane's engine (TEI, EMBED_UPSTREAM) while qwen38-embed.service is active, and to the text
|
|
engine as before otherwise; a request that names the Clipstral lane's model goes to that lane alone.
|
|
|
|
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 importlib.util
|
|
import io
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import select
|
|
import shutil
|
|
import socket
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import types
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
from unittest import mock
|
|
|
|
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 Clipstral(http.server.BaseHTTPRequestHandler):
|
|
"""The Clipstral lane's server as the proxy meets it. `busy`: it computes until its client leaves, and says so."""
|
|
protocol_version = "HTTP/1.1"
|
|
asked, auths, bodies = [], [], []
|
|
busy, loading, left = False, False, threading.Event()
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def do_POST(self):
|
|
Clipstral.asked.append(self.path)
|
|
Clipstral.auths.append(self.headers.get("Authorization"))
|
|
Clipstral.bodies.append(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
|
|
if Clipstral.busy:
|
|
if select.select([self.connection], [], [], 15)[0] and not self.connection.recv(1, socket.MSG_PEEK):
|
|
Clipstral.left.set()
|
|
self.close_connection = True
|
|
return
|
|
out = json.dumps({"object": "list", "model": "mistral-multimodal-embed-1b", "data": []}).encode()
|
|
self.send_response(503 if Clipstral.loading else 200)
|
|
if Clipstral.loading:
|
|
self.send_header("Retry-After", "5")
|
|
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)
|
|
self.clip = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Clipstral)
|
|
for s in (self.tei, self.text, self.clip):
|
|
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[:] = [], [], [], []
|
|
Clipstral.asked[:], Clipstral.auths[:], Clipstral.bodies[:] = [], [], []
|
|
Clipstral.busy = False
|
|
Clipstral.left.clear()
|
|
|
|
def spawn(self, embed_active, embed_upstream=True, unit_file=None, clipstral_active=False, clipstral_unit=None, **more):
|
|
"""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)."""
|
|
state = clipstral_active if isinstance(clipstral_active, str) else "active" if clipstral_active else "inactive"
|
|
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'
|
|
f'[ "$*" = "is-active qwen38-clipstral.service" ] && {{ echo {state}; exit {0 if state == "active" else 3}; }}\n'
|
|
"exit 3\n")
|
|
(fake / "systemctl").chmod(0o755)
|
|
env = dict(UPSTREAM=f"http://127.0.0.1:{self.text.server_port}",
|
|
PATH=f"{fake}:{os.environ.get('PATH', '')}", HOME=str(self.homes[0]), **more)
|
|
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)
|
|
if clipstral_unit is None:
|
|
env["CLIPSTRAL_UPSTREAM"] = f"http://127.0.0.1:{self.clip.server_port}"
|
|
else:
|
|
env["CLIPSTRAL_UNIT_FILE"] = str(clipstral_unit)
|
|
# in this process, its environment set first as its unit does: what CI's coverage floor measures
|
|
was = {k: os.environ.get(k) for k in env}
|
|
self.addCleanup(lambda: [os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v) for k, v in was.items()])
|
|
os.environ.update(env)
|
|
spec = importlib.util.spec_from_file_location("kproxy_embeddings", REPO / "keepalive-proxy.py")
|
|
mod = importlib.util.module_from_spec(spec)
|
|
err, sys.stderr = sys.stderr, io.StringIO()
|
|
try:
|
|
spec.loader.exec_module(mod)
|
|
finally:
|
|
sys.stderr = err
|
|
mod.log = lambda line: None
|
|
srv = mod.Server(("127.0.0.1", 0), mod.H)
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
self.addCleanup(srv.server_close)
|
|
self.addCleanup(srv.shutdown)
|
|
return srv.server_address[1]
|
|
|
|
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_a_client_that_leaves_ends_its_request_at_the_lane(self):
|
|
"""One that gives up and asks again had its first job computed to its end for nobody, the second behind it: the
|
|
lane's own client is this proxy, which waited for the answer and looked at nothing else."""
|
|
Clipstral.busy = True
|
|
port = self.spawn(embed_active=False, clipstral_active=True)
|
|
body = json.dumps({"model": "clipstral", "input": "a"}).encode()
|
|
with socket.create_connection(("127.0.0.1", port), timeout=10) as s:
|
|
s.sendall(b"POST /v1/embeddings HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
|
|
b"Authorization: Bearer " + KEY.encode() + b"\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
|
|
end = time.monotonic() + 10
|
|
while not Clipstral.asked and time.monotonic() < end:
|
|
time.sleep(0.02)
|
|
self.assertEqual(Clipstral.asked, ["/v1/embeddings"])
|
|
self.assertFalse(Clipstral.left.wait(1.5), "while its client waits, the lane computes")
|
|
self.assertTrue(Clipstral.left.wait(8), "the lane computed for a client that had left")
|
|
|
|
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")
|
|
|
|
NAMES = ("mistral-multimodal-embed-1b", "mistralai/Mistral-Multimodal-Embed-1B", " Clipstral ", "mistral-multimodal-embed")
|
|
|
|
def test_a_request_that_names_the_clipstral_lanes_model_goes_to_it_alone(self):
|
|
for embed in (True, False):
|
|
port = self.spawn(embed_active=embed, clipstral_active=True)
|
|
for name in self.NAMES:
|
|
with self.subTest(name=name, embed=embed):
|
|
body = {"model": name, "input": ["a", {"type": "image_url", "image_url": "data:image/png;base64,AAAA"}]}
|
|
status, raw = self.ask(port, "/v1/embeddings", body)
|
|
self.assertEqual((status, json.loads(raw)["model"]), (200, "mistral-multimodal-embed-1b"))
|
|
self.assertEqual(json.loads(Clipstral.bodies[-1]), body)
|
|
self.assertEqual(Clipstral.auths, [None] * len(Clipstral.auths), "no key is sent to it")
|
|
self.assertEqual((TEI.asked, TextEngine.asked), ([], []))
|
|
|
|
def test_not_running_it_is_a_404_never_another_models_vectors(self):
|
|
"""Two models' vectors are of two spaces: answered by the embeddings lane, a query would compare with nothing
|
|
its index holds, and say nothing of it."""
|
|
port = self.spawn(embed_active=True, clipstral_active=False)
|
|
for name in self.NAMES:
|
|
status, raw = self.ask(port, "/v1/embeddings", {"model": name, "input": "a"})
|
|
err = json.loads(raw)["error"]
|
|
self.assertEqual((status, err["type"], err["code"]), (404, "model_not_found", "model_not_found"), name)
|
|
self.assertIn("qwen38-clipstral.service", err["message"])
|
|
self.assertEqual((TEI.asked, TextEngine.asked, Clipstral.asked), ([], [], []))
|
|
|
|
def test_every_other_request_goes_where_it_went(self):
|
|
port = self.spawn(embed_active=True, clipstral_active=True)
|
|
for body in (self.embeddings(), {"input": "a"}, {"model": None, "input": "a"}, {"model": "text-embedding-3-small", "input": "a"},
|
|
{"model": ["clipstral"], "input": "a"}, {"input": "clipstral"}):
|
|
self.assertEqual(self.ask(port, "/v1/embeddings", body)[0], 200)
|
|
self.assertEqual((len(TEI.asked), Clipstral.asked), (6, []))
|
|
port = self.spawn(embed_active=False, clipstral_active=True)
|
|
self.assertEqual(self.ask(port, "/v1/embeddings", self.embeddings())[0], 400, "the text engine's own answer")
|
|
self.assertEqual(Clipstral.asked, [], "it answers to its name alone")
|
|
|
|
def test_a_body_that_cannot_be_read_goes_to_the_engine_that_says_so(self):
|
|
port = self.spawn(embed_active=True, clipstral_active=True)
|
|
for raw in (b"{", b"[1]", b"[" * 200_000, b'"clipstral"'):
|
|
req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/embeddings", data=raw, method="POST",
|
|
headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
self.assertEqual(r.status, 200)
|
|
self.assertEqual((len(TEI.asked), Clipstral.asked), (4, []))
|
|
|
|
def test_its_key_is_asked_at_the_door_too(self):
|
|
port = self.spawn(embed_active=True, clipstral_active=True)
|
|
self.assertEqual(self.ask(port, "/v1/embeddings", {"model": "clipstral", "input": "a"}, key=None)[0], 401)
|
|
self.assertEqual(self.ask(port, "/v1/embeddings", {"model": "clipstral", "input": "a"}, key="wrong")[0], 401)
|
|
self.assertEqual(Clipstral.asked, [])
|
|
|
|
def test_its_server_silent_is_a_503_that_names_it(self):
|
|
self.clip.shutdown()
|
|
self.clip.server_close()
|
|
port = self.spawn(embed_active=True, clipstral_active=True)
|
|
status, raw = self.ask(port, "/v1/embeddings", {"model": "clipstral", "input": "a"})
|
|
self.assertEqual((status, json.loads(raw)["error"]["type"]), (503, "engine_unavailable"))
|
|
self.assertIn("qwen38-clipstral.service", json.loads(raw)["error"]["message"])
|
|
self.assertEqual(TEI.asked, [])
|
|
|
|
def test_a_lane_that_moves_is_a_503_to_try_again(self):
|
|
"""Its restart, or the 10 s systemd waits after a death: a 404 is final, no SDK asks again (review of v1.60.0)."""
|
|
for state, want in (("activating", 503), ("deactivating", 503), ("reloading", 503), ("", 503), ("inactive", 404), ("failed", 404)):
|
|
with self.subTest(state):
|
|
port = self.spawn(embed_active=True, clipstral_active=state)
|
|
req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/embeddings", data=b'{"model": "clipstral", "input": "a"}',
|
|
headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
|
|
with self.assertRaises(urllib.error.HTTPError) as e:
|
|
urllib.request.urlopen(req, timeout=10)
|
|
with e.exception:
|
|
err = json.loads(e.exception.read())["error"]
|
|
kind = err["type"]
|
|
if want == 503: # in words that are true (review of v1.60.0)
|
|
self.assertIn("is starting or stopping" if state else "systemd does not say whether", err["message"])
|
|
self.assertEqual((e.exception.code, kind, e.exception.headers.get("Retry-After")),
|
|
(503, "engine_unavailable", "10") if want == 503 else (404, "model_not_found", None))
|
|
self.assertEqual((TEI.asked, Clipstral.asked), ([], []))
|
|
|
|
def test_what_systemd_said_last_stands_while_it_does_not_answer(self):
|
|
"""Its 2 s can pass on a box at work: a lane that served was said to be starting, or its requests went to the text
|
|
engine (review of v1.60.0)."""
|
|
self.spawn(embed_active=True)
|
|
spec = importlib.util.spec_from_file_location("kproxy_silent", REPO / "keepalive-proxy.py")
|
|
mod = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(mod)
|
|
|
|
def late(*a, **k):
|
|
raise mod.subprocess.TimeoutExpired("systemctl", 2)
|
|
for silent in (late, lambda *a, **k: types.SimpleNamespace(stdout="", returncode=1)):
|
|
with mock.patch.object(mod.subprocess, "run", silent):
|
|
for said in ("active", "inactive", "activating", ""):
|
|
mod._CLIPSTRAL_SEEN.update(state=said, ts=-1e9)
|
|
self.assertEqual(mod.clipstral_lane(), said)
|
|
with mock.patch.object(mod.subprocess, "run", late):
|
|
for was in (True, False):
|
|
mod._EMBED_SEEN.update(active=was, ts=-1e9)
|
|
self.assertIs(mod.embed_lane_serving(), was)
|
|
|
|
def test_what_names_it_is_read_without_the_json(self):
|
|
"""An indexing job's body is tens of MiB of images: json.loads of it took up to 27 times its size, for the requests of
|
|
the other lane as well (review of v1.60.0)."""
|
|
port = self.spawn(embed_active=True, clipstral_active=True)
|
|
|
|
def goes(raw):
|
|
TEI.asked[:], Clipstral.asked[:] = [], []
|
|
req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/embeddings", data=raw, method="POST",
|
|
headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
|
|
urllib.request.urlopen(req, timeout=10).close()
|
|
return "clipstral" if Clipstral.asked else "embed"
|
|
for raw in (b'{"input": "a", "model" :\n "mistralai/Mistral-Multimodal-Embed-1B"}',
|
|
b'{"model":"mistralai\\/Mistral-Multimodal-Embed-1B","input":"a"}', # as PHP's json_encode writes it
|
|
b'{"model": " Clipstral ", "input": ["a"]}'):
|
|
self.assertEqual(goes(raw), "clipstral", raw)
|
|
for raw in (json.dumps({"model": "pplx-embed-v1-0.6b", "input": 'a config: {"model": "clipstral"}'}).encode(),
|
|
json.dumps({"input": '"model": "clipstral"'}).encode(), b'{"model": "clipstral-2", "input": "a"}',
|
|
b'{"models": "clipstral", "input": "a"}'):
|
|
self.assertEqual(goes(raw), "embed", raw)
|
|
|
|
def test_its_bodies_hold_their_share_and_no_more(self):
|
|
"""Six requests of images held the room of every body until the lane, on the CPU, had answered: an agent's long
|
|
context was a 503 meanwhile (review of v1.60.0)."""
|
|
Clipstral.busy = True
|
|
port = self.spawn(embed_active=True, clipstral_active=True, EMBED_BODIES_MAX="3000", EMBED_BODY_MAX="2500")
|
|
body = json.dumps({"model": "clipstral", "input": "a" * 1900}).encode()
|
|
with socket.create_connection(("127.0.0.1", port), timeout=10) as s:
|
|
s.sendall(b"POST /v1/embeddings HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
|
|
b"Authorization: Bearer " + KEY.encode() + b"\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
|
|
end = time.monotonic() + 10
|
|
while not Clipstral.asked and time.monotonic() < end:
|
|
time.sleep(0.02)
|
|
status, raw = self.ask(port, "/v1/embeddings", {"model": "clipstral", "input": "b" * 1900})
|
|
self.assertEqual((status, json.loads(raw)["error"]["type"]), (503, "engine_unavailable"))
|
|
self.assertEqual(self.ask(port, "/v1/embeddings", self.embeddings())[0], 200, "there is room for a small one")
|
|
status, raw = self.ask(port, "/v1/embeddings", {"model": "clipstral", "input": "c" * 2600})
|
|
self.assertEqual((status, json.loads(raw)["error"]["type"]), (413, "request_too_large"))
|
|
self.assertTrue(Clipstral.left.wait(8))
|
|
Clipstral.busy = False
|
|
end = time.monotonic() + 5
|
|
while self.ask(port, "/v1/embeddings", {"model": "clipstral", "input": "b" * 1900})[0] != 200:
|
|
self.assertLess(time.monotonic(), end, "its room was not given back")
|
|
time.sleep(0.1)
|
|
|
|
def test_when_to_ask_again_is_relayed(self):
|
|
Clipstral.loading = True
|
|
self.addCleanup(setattr, Clipstral, "loading", False)
|
|
port = self.spawn(embed_active=True, clipstral_active=True)
|
|
req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/embeddings", data=b'{"model": "clipstral", "input": "a"}',
|
|
headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
|
|
with self.assertRaises(urllib.error.HTTPError) as e:
|
|
urllib.request.urlopen(req, timeout=10)
|
|
with e.exception:
|
|
self.assertEqual((e.exception.code, e.exception.headers.get("Retry-After")), (503, "5"))
|
|
|
|
def test_its_port_is_read_in_its_unit(self):
|
|
d = pathlib.Path(tempfile.mkdtemp(prefix="fake-clipstral-unit-"))
|
|
self.addCleanup(shutil.rmtree, d, True)
|
|
unit = d / "qwen38-clipstral.service"
|
|
unit.write_text(f"[Service]\nExecStart=/usr/bin/docker run x --host 127.0.0.1 --port {self.clip.server_port}\n")
|
|
port = self.spawn(embed_active=False, clipstral_active=True, clipstral_unit=unit)
|
|
self.assertEqual(self.ask(port, "/v1/embeddings", {"model": "clipstral", "input": "a"})[0], 200)
|
|
self.assertEqual(Clipstral.asked, ["/v1/embeddings"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|