Files
alzeo/tests/test_clipstral_server.py
T

738 lines
37 KiB
Python

#!/usr/bin/env python3
"""The Clipstral lane's server (clipstral-server.py), its model replaced by one that answers at once: what it takes, what
it refuses and in which words, the order of its answers, and what it does while the model loads or when its client
leaves. The model itself is proved on a box (install-clipstral.sh): CI has no torch."""
import base64
import http.client
import importlib.util
import json
import pathlib
import signal
import socket
import struct
import subprocess
import sys
import threading
import time
import types
import unittest
from http.server import ThreadingHTTPServer
from unittest import mock
REPO = pathlib.Path(__file__).resolve().parents[1]
_spec = importlib.util.spec_from_file_location("clipstral_server", REPO / "clipstral-server.py")
S = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(S)
import vectors_server as V # noqa: E402 (the module above puts the repository on the path)
PNG = base64.b64encode(b"\x89PNG not read by these tests").decode()
URL = "data:image/png;base64," + PNG
CHUNK = {"type": "image_url", "image_url": URL}
class Words:
"""A tokenizer that counts words, with the two marks the model's adds."""
def encode(self, text):
return type("Enc", (), {"ids": [1, *range(3, 3 + len(text.split())), 2]})()
class Lib:
GRID = 28
@staticmethod
def sides(w, h):
return w, h
class Fake(S.Clipstral):
"""The engine with everything but its arithmetic: a text's vector says its length, an image's its place."""
def __init__(self): # not its own: that one reads the model
self.tok, self.lib, self.turns, self.longest = Words(), Lib(), V.Turns(), 9
self.calls, self.sizes = [], {}
def opened(self, raw, where):
if raw == b"broken":
raise S.Bad(f"{where} is not an image this lane reads")
return raw, self.sizes.get(raw, (56, 84))
def images(self, some, between=None):
self.calls.append(("images", [w for w, _ in some]))
return [[float(w[6:-1]) + 0.5] * S.DIM for w, _ in some]
def texts(self, ids, between=None):
self.calls.append(("texts", [len(x) for x in ids]))
return [[float(len(x))] * S.DIM for x in ids]
class WhatARequestAsks(unittest.TestCase):
def test_a_text_an_image_and_a_list_of_both_in_order(self):
raw = base64.b64decode(PNG)
for given, want in (("a", [("text", "a")]), (["a", "b"], [("text", "a"), ("text", "b")]),
(CHUNK, [("image", raw)]), (URL, [("image", raw)]), (URL.upper().replace(PNG.upper(), PNG), [("image", raw)]),
({"type": "image_url", "image_url": {"url": URL, "detail": "low"}}, [("image", raw)]),
([CHUNK, "a", {"type": "text", "text": "b"}, URL],
[("image", raw), ("text", "a"), ("text", "b"), ("image", raw)]),
("data:image/png;charset=utf-8;base64," + PNG[:8] + "\n " + PNG[8:], [("image", raw)]),
("a page that quotes " + URL, [("text", "a page that quotes " + URL)]),
("data:image/png" + ";a" * 9 + ";base64," + PNG, [("text", "data:image/png" + ";a" * 9 + ";base64," + PNG)])):
with self.subTest(str(given)[:60]):
self.assertEqual(S.inputs_of({"input": given}), want)
def test_what_it_refuses_names_the_entry_and_why(self):
for given, words in ((None, "'input' must be"), ([], "not empty"), (3, "'input' must be"), ("", "input[0] is an empty text"),
(["a", " \n"], "input[1] is an empty text"), ([1, 2], "token ids"), ([["a"]], "token ids"),
(["a", {"type": "input_audio", "input_audio": "x"}], "input[1] must be a string or an image chunk"),
({"type": "image_url"}, "image_url must be a string"), ([None], "input[0] must be"),
({"type": "image_url", "image_url": "https://x.org/a.png"}, "this lane reaches no network"),
({"type": "image_url", "image_url": "data:image/png,raw"}, "in base64"),
({"type": "image_url", "image_url": "data:text/html;base64,AAAA"}, "data:image/png;base64"),
(CHUNK | {"image_url": "data:image/png;base64,%%%"}, "not valid base64"),
(["a"] * (S.MAX_INPUTS + 1), f"over {S.MAX_INPUTS}")):
with self.subTest(str(given)[:60]):
with self.assertRaises(S.Bad) as e:
S.inputs_of({"input": given} if given is not None else {})
self.assertIn(words, str(e.exception))
def test_the_vectors_it_makes_and_no_other(self):
for ok in ({}, {"dimensions": 1024}, {"output_dimension": None, "output_dtype": "float"}, {"encoding_format": None}):
self.assertEqual(S.wants(ok), ("float", None))
self.assertEqual(S.wants({"encoding_format": "base64"}), ("base64", None))
for bad in ({"dimensions": 256}, {"output_dimension": 1023}, {"output_dtype": "int8"}, {"encoding_format": "hex"},
{"dimensions": True}):
with self.subTest(bad), self.assertRaises(S.Bad):
S.wants(bad)
class HowItIsComputed(unittest.TestCase):
def test_a_batch_holds_its_budget_and_every_input_is_in_one(self):
lengths = [5, 900, 30, 4000, 31, 6, 9000, 900, 1]
groups = V.batches(lengths, 4096)
self.assertEqual(sorted(i for g in groups for i in g), list(range(len(lengths))))
for g in groups:
self.assertTrue(len(g) == 1 or max(lengths[i] for i in g) * len(g) <= 4096, g)
self.assertEqual(V.batches([], 10), [])
self.assertIn([6], groups, "one over the budget is computed, alone")
def test_the_answers_keep_the_order_of_the_inputs(self):
e = Fake()
a, b = b"first", b"second"
e.sizes = {a: (28, 28), b: (56, 56)}
out, tokens = e.encode([("text", "one two three"), ("image", a), ("text", "one"), ("image", b), ("image", a)])
self.assertEqual([v[0] for v in out], [5.0, 1.5, 3.0, 3.5, 4.5])
self.assertEqual(tokens, [5, 1, 3, 4, 1])
self.assertEqual([c for c in e.calls if c[0] == "images"], [("images", ["input[1]", "input[4]"]), ("images", ["input[3]"])],
"images of one size go together")
def test_images_go_a_few_at_a_time(self):
e = Fake()
e.encode([("image", b"x")] * (2 * V.BATCH_IMAGES + 1))
self.assertEqual([len(c[1]) for c in e.calls], [V.BATCH_IMAGES, V.BATCH_IMAGES, 1])
def test_a_request_refused_costs_nothing(self):
e = Fake()
for bad in ([("text", "a"), ("text", "word " * V.MAX_TOKENS)], [("text", "a"), ("image", b"broken")]):
with self.assertRaises(S.Bad):
e.encode(bad)
self.assertEqual(e.calls, [])
def test_a_request_the_lane_could_not_finish_is_refused(self):
"""2,048 texts of 8,192 tokens were taken, and answered a 503 at the proxy's 900 s, "try again", for good (review of
v1.60.0)."""
e = Fake()
full = V.MAX_REQUEST_TOKENS // 8000
for inputs in ([("text", "word " * 7998)] * (full + 1), [("image", b"x")] * (V.MAX_REQUEST_IMAGES + 1)):
with self.assertRaises(S.Bad) as bad:
e.encode(inputs)
self.assertIn("send its inputs in several", str(bad.exception))
self.assertEqual(e.calls, [])
e.encode([("image", b"x")] * V.MAX_REQUEST_IMAGES + [("text", "a")])
def test_and_before_it_is_all_read(self):
"""Its 2,048 texts were tokenized, or the files of its images opened, and then it was refused (review of v1.60.0)."""
e, read = Fake(), []
e.tok = types.SimpleNamespace(encode=lambda x: read.append(x) or Words().encode(x))
with self.assertRaises(S.Bad):
e.encode([("text", "word " * 7998)] * S.MAX_INPUTS)
self.assertEqual(len(read), V.MAX_REQUEST_TOKENS // 8000 + 1)
e.opened, read[:] = (lambda raw, where: read.append(raw)), []
with self.assertRaises(S.Bad):
e.encode([("image", b"x")] * (V.MAX_REQUEST_IMAGES + 1))
self.assertEqual(read, [])
def test_what_a_client_that_left_asked_is_not_computed(self):
e, seen = Fake(), []
def gone():
seen.append(1)
return len(seen) > 1
with self.assertRaises(V.Gone):
e.encode([("image", b"x")] * (3 * V.BATCH_IMAGES), gone)
self.assertEqual(len(e.calls), 1)
def test_batches_take_turns_in_the_order_they_are_asked_on_one_thread(self):
"""A query waits for one batch of an indexing job, not for the job; and one thread computes them all, as torch keeps a
team of threads for each that does (review of v1.60.0)."""
e, order, on = Fake(), [], set()
started, go = threading.Event(), threading.Event()
def texts(ids, between):
order.append(len(ids[0]))
on.add(threading.get_ident())
started.set()
go.wait(5)
return [[0.0] * S.DIM for _ in ids]
e.texts = texts
long = [("text", "word " * n) for n in (4000, 4001, 4002)] # three batches: over the budget together
job = threading.Thread(target=e.encode, args=(long,))
job.start()
self.assertTrue(started.wait(5))
ask = threading.Thread(target=e.encode, args=([("text", "word " * 2998)],))
ask.start()
end = time.monotonic() + 5
while e.turns.thread._work_queue.qsize() < 1 and time.monotonic() < end:
time.sleep(0.001)
go.set()
job.join(10)
ask.join(10)
self.assertEqual(order, [4002, 3000, 4003, 4004], "it went behind the batch that was computed, not behind the job")
self.assertEqual(len(on), 1)
LAYERS = 4
def layered(self, e, order, gate=None):
"""Texts and images computed in layers, between() called after each, as the model's towers do."""
def compute(kind, some, between):
for k in range(self.LAYERS):
order.append((kind, len(some[0]) if kind == "text" else len(some), k))
if gate:
gate()
if between:
between()
return [[0.0] * S.DIM for _ in some]
e.texts = lambda ids, between: compute("text", ids, between)
e.images = lambda some, between: compute("images", some, between)
def asked_during(self, first, then, wait):
"""The order of the layers computed when `then`, requests, come while the first layer of `first` is."""
e, order, started, go = Fake(), [], threading.Event(), threading.Event()
def gate():
started.set()
go.wait(5)
self.layered(e, order, gate)
job = threading.Thread(target=e.encode, args=(first,))
job.start()
self.assertTrue(started.wait(5))
others, end = [threading.Thread(target=e.encode, args=(x,)) for x in then], time.monotonic() + 5
for n, t in enumerate(others):
t.start()
while e.turns.thread._work_queue.qsize() < n + 1 and time.monotonic() < end:
time.sleep(0.001)
go.set()
for t in (job, *others):
t.join(10)
return order
def test_a_short_text_passes_between_two_layers_of_another_batch(self):
"""A query sent while a batch of 4,096 tokens was computed waited for the whole of it, 3.5 s (measured on 2026-12-01)."""
query, layers = [("text", "a query")], range(self.LAYERS)
for first, kind, n in (([("text", "word " * 4000)], "text", 4002), ([("image", b"x")] * V.BATCH_IMAGES, "images", V.BATCH_IMAGES)):
with self.subTest(kind):
order = self.asked_during(first, [query], 1)
self.assertEqual(order, [(kind, n, 0), *[("text", 4, k) for k in layers], *[(kind, n, k) for k in layers[1:]]])
# one between two layers, in their order, and each once
order = self.asked_during([("text", "word " * 4000)], [[("text", "w " * n)] for n in (5, 6, 7)], 3)
self.assertEqual([x for x in order if x[2] == 0], [("text", 4002, 0), ("text", 7, 0), ("text", 8, 0), ("text", 9, 0)])
self.assertEqual([x for x in order if x[1] == 4002 or x[2] == 0],
[("text", 4002, 0), ("text", 7, 0), ("text", 4002, 1), ("text", 8, 0), ("text", 4002, 2), ("text", 9, 0), ("text", 4002, 3)])
self.assertEqual(len(order), 4 * self.LAYERS, "each computed once")
def test_what_is_longer_or_an_image_waits_for_its_turn(self):
"""One that passed on every side would leave a job its layers and no more."""
long, at = [("text", "word " * 4000)], [("text", 4002, k) for k in range(self.LAYERS)]
for then in ([("text", "w " * V.SHORT_TOKENS)], [("image", b"x")], [("text", "a"), ("image", b"x")], [("text", "w " * 200)] * 2):
with self.subTest(str(then)[:30]):
order = self.asked_during(long, [then], 1)
self.assertEqual(order[:self.LAYERS], at)
# the bound is of its tokens, marks included, whatever the number of its texts
order = self.asked_during(long, [[("text", "w " * (V.SHORT_TOKENS // 4 - 2))] * 4], 1)
self.assertEqual(order[1], ("text", V.SHORT_TOKENS // 4, 0))
def test_a_short_one_that_fails_is_its_own_request_s(self):
e, order, failed = Fake(), [], []
self.layered(e, order)
real, started, go = e.texts, threading.Event(), threading.Event()
def texts(ids, between):
if len(ids[0]) == 4:
raise RuntimeError("no memory")
started.set()
go.wait(5)
return real(ids, between)
e.texts = texts
got = []
job = threading.Thread(target=lambda: got.append(e.encode([("text", "word " * 4000)])))
job.start()
self.assertTrue(started.wait(5))
def ask():
try:
e.encode([("text", "a query")])
except RuntimeError as err:
failed.append(str(err))
t, end = threading.Thread(target=ask), time.monotonic() + 5
t.start()
while e.turns.thread._work_queue.qsize() < 1 and time.monotonic() < end:
time.sleep(0.001)
go.set()
job.join(10)
t.join(10)
self.assertEqual((failed, len(got), len(order)), (["no memory"], 1, self.LAYERS))
def test_a_short_one_lets_none_pass(self):
e, seen = Fake(), []
e.texts = lambda ids, between: seen.append(between) or [[0.0] * S.DIM for _ in ids]
e.encode([("text", "a query")])
e.encode([("text", "w " * 300)])
self.assertEqual(seen, [None, e.turns.let_pass])
def test_one_whose_client_left_while_it_waited_is_not_computed(self):
e = Fake()
started, go, left = threading.Event(), threading.Event(), threading.Event()
real = e.texts
def texts(ids, between):
started.set()
go.wait(5)
return real(ids)
e.texts = texts
first = threading.Thread(target=e.encode, args=([("text", "one")],))
first.start()
self.assertTrue(started.wait(5))
got = []
def second():
try:
e.encode([("text", "two words")], left.is_set)
except V.Gone:
got.append("gone")
t = threading.Thread(target=second)
t.start()
end = time.monotonic() + 5
while e.turns.thread._work_queue.qsize() < 1 and time.monotonic() < end:
time.sleep(0.001)
left.set()
go.set()
first.join(5)
t.join(5)
self.assertEqual((got, [c[1] for c in e.calls]), (["gone"], [[3]]), "its client had left before its turn")
def test_a_vector_is_written_to_the_float(self):
v = [0.1, -1.0, 3.0517578125e-05, 1 / 3]
singles = list(struct.unpack("<4f", struct.pack("<4f", *v)))
self.assertEqual(list(struct.unpack("<4f", base64.b64decode(V.written(singles, "base64")))), singles)
back = V.written(singles, "float")
self.assertEqual(list(struct.unpack("<4f", struct.pack("<4f", *back))), singles)
self.assertLess(max(len(repr(x)) for x in back), 18)
def tiff(orientation=6, order="<", kind=3, count=1, extra=0):
"""An EXIF block: `extra` entries before the orientation's, each pointing at all of the block."""
entries = [struct.pack(order + "HHII", 0x0200 + i, 1, 26 + 12 * extra, 8) for i in range(extra)]
entries.append(struct.pack(order + "HHIHH", 0x0112, kind, count, orientation, 0))
return ({"<": b"II*\0", ">": b"MM\0*"}[order] + struct.pack(order + "I", 8) + struct.pack(order + "H", len(entries))
+ b"".join(entries) + struct.pack(order + "I", 0))
def segment(kind, data):
return bytes([0xFF, kind]) + struct.pack(">H", len(data) + 2) + data
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + b"crc."
class TheFileOfAnImage(unittest.TestCase):
"""What reaches the decoder: the part its pixels are read from. Pillow reads every piece of metadata of a file it opens,
and an EXIF block of 320 KB whose entries all point at the same bytes took the container's 8 GB (review of v1.60.0)."""
JFIF, DQT, SOF, DHT = segment(0xE0, b"JFIF\0"), segment(0xDB, b"q" * 65), segment(0xC2, b"s" * 15), segment(0xC4, b"h" * 20)
SOS = segment(0xDA, b"scan") + b"data\xff\x00data"
END = b"\xff\xd9"
def jpeg(self, *before):
return b"\xff\xd8" + self.JFIF + b"".join(before) + self.DQT + self.SOF + self.DHT + self.SOS + self.END
def test_a_jpeg_keeps_what_its_pixels_need_and_says_its_turn(self):
clean = self.jpeg()
exif = segment(0xE1, b"Exif\0\0" + tiff(6))
adobe = segment(0xEE, b"Adobe")
dropped = (segment(0xE2, b"ICC_PROFILE\0" + b"i" * 900), segment(0xFE, b"a comment"), segment(0xE1, b"http://ns.adobe.com/xap/1.0/\0"),
segment(0xED, b"Photoshop"), segment(0xE1, b"Exif\0\0" + tiff(3)), segment(0xE2, b"MPF\0"))
self.assertEqual(S.bare(clean), ("JPEG", clean, None))
self.assertEqual(S.bare(self.jpeg(exif, *dropped)), ("JPEG", clean, 6), "the first EXIF block is the one read")
self.assertEqual(S.bare(self.jpeg(adobe))[1], self.jpeg(adobe), "it says how the colours are written")
self.assertEqual(S.bare(self.jpeg(b"\xff\xff\xff", exif))[2], 6, "filled")
self.assertEqual(S.bare(self.jpeg(b"\0junk", exif, b"\xff\x01"))[1:], (clean, 6), "junk between its segments")
def test_a_jpeg_of_too_many_scans_or_segments_is_refused(self):
scans, tail = self.jpeg()[:-2], segment(0xFE, b"") * S.MAX_PARTS
self.assertEqual(S.bare(scans + self.SOS * (S.MAX_SCANS - 1) + self.END)[0], "JPEG")
for raw in (scans + self.SOS * S.MAX_SCANS + self.END, self.jpeg(tail), scans + tail + self.END, b"\xff\xd8\xff", self.jpeg()[:40]):
with self.assertRaises((ValueError, IndexError)):
S.bare(raw)
def test_what_follows_a_jpegs_end_is_not_its_own(self):
"""A phone's motion photo is a JPEG with its film behind it, in which the two bytes of a scan come by chance: over 100
were counted there, and the photo refused (review of v1.60.0)."""
film = b"ftypmp42" + b"\xff\xda\0\x0cxx" * (3 * S.MAX_SCANS)
self.assertEqual(S.bare(self.jpeg() + film), ("JPEG", self.jpeg(), None))
# what lies in a segment between two scans is no marker
two = self.jpeg()[:-2] + segment(0xC4, b"\xff\xd9\xff\xda" * 300) + self.SOS + b"\xff\xd0more\xff\x01\xff\xff" + self.END
self.assertEqual(S.bare(two + film), ("JPEG", two, None))
cut = self.jpeg()[:-2]
self.assertEqual(S.bare(cut), ("JPEG", cut, None), "cut short, it is its decoder's to say")
began = time.monotonic()
S.bare(cut + b"\xff" * 4_000_000 + b"\0" + self.END)
self.assertLess(time.monotonic() - began, 5, "read once")
def test_a_png_keeps_what_its_pixels_need_and_says_its_turn(self):
head, ihdr, plte, trns = b"\x89PNG\r\n\x1a\n", chunk(b"IHDR", b"h" * 13), chunk(b"PLTE", b"p" * 6), chunk(b"tRNS", b"t")
idat, iend = chunk(b"IDAT", b"d" * 50), chunk(b"IEND", b"")
exif = chunk(b"eXIf", tiff(8, ">"))
clean = head + ihdr + plte + trns + idat + idat + iend
self.assertEqual(S.bare(clean), ("PNG", clean, None))
self.assertEqual(S.bare(head + ihdr + chunk(b"iCCP", b"i" * 99) + exif + plte + trns + chunk(b"zTXt", b"z" * 99) + idat + idat
+ chunk(b"tEXt", b"after") + iend), ("PNG", clean, 8))
self.assertEqual(S.bare(head + ihdr + plte + trns + idat + idat + exif + iend)[2], 8, "an EXIF block behind its pixels")
self.assertEqual(S.bare(clean[:-30])[1], clean[:-30], "a file cut short is its decoder's to say")
with self.assertRaises(ValueError):
S.bare(head + ihdr + chunk(b"tEXt", b"") * S.MAX_PARTS + idat + iend)
def test_a_gif_is_its_first_frame(self):
head = b"GIF89a" + struct.pack("<HH", 4, 4) + bytes([0x91, 0, 0]) + b"t" * 12
gce, frame = b"\x21\xf9\x04\x01\0\0\0\0", b"\x2c" + struct.pack("<HHHH", 0, 0, 4, 4) + b"\0" + b"\x02\x03abc\0"
comment = b"\x21\xfe" + b"\xff" + b"c" * 255 + b"\x02cc\0"
self.assertEqual(S.bare(head + comment * 3 + gce + comment + frame + gce + frame + b";"), ("GIF", head + gce + frame + b";", None))
local = frame[:9] + b"\x80" + b"l" * 6 + frame[10:]
self.assertEqual(S.bare(head + local + b";")[1], head + local + b";", "a table of its own")
for raw in (head + b";", head + comment, head + b"\x21\xfe" + b"\x01c" * S.MAX_PARTS + b"\0" + frame + b";"):
with self.assertRaises((ValueError, IndexError)):
S.bare(raw)
def test_a_webp_goes_as_it_is_and_anything_else_is_no_image(self):
webp = b"RIFF\x10\0\0\0WEBPVP8 rest"
self.assertEqual(S.bare(webp), ("WEBP", webp, None))
for raw in (b"", b"BM" + b"\0" * 60, b"%!PS-Adobe-3.0 EPSF", b"RIFF\x10\0\0\0WAVE", b"\0" * 60):
with self.assertRaises(ValueError):
S.bare(raw)
def test_the_orientation_and_nothing_else_of_an_exif_block(self):
for order in "<>":
for n in range(1, 9):
self.assertEqual(S.upright(tiff(n, order)), n)
self.assertEqual(S.upright(tiff(3, extra=300)), 3)
for block in (tiff(0), tiff(9), tiff(6, kind=4), tiff(6, count=2), tiff(6, extra=600), tiff()[:19], b"", b"nothing here",
b"II*\0\xff\xff\xff\xff"):
self.assertIsNone(S.upright(block), block[:24])
class Opened:
"""What Pillow gives for an image of the request, as far as this lane reads it: b"<width>x<height> [cut]"."""
alive = []
def __init__(self, raw, kind):
self.raw, (size, *self.cut) = raw, raw.decode().split()
self.size, self.decoded, self.closed = tuple(map(int, size.split("x"))), False, False
self.mode, self.info = "I;16" if "gray16" in self.cut else "RGB", {"exif": b"Exif\0\0" + tiff(5)} if kind == "WEBP" else {}
self.alive.append(self)
def __enter__(self):
return self
def __exit__(self, *_):
self.closed = True
def load(self):
self.decoded = True
if "cut" in self.cut:
raise OSError("image file is truncated")
if "odd" in self.cut:
raise IndexError("index out of range")
def transpose(self, how):
return self, how
def convert(self, mode):
self.mode = mode
return self
def point(self, f):
self.brought = f(65535)
return self
class AnImageOfTheRequest(unittest.TestCase):
"""What the lane reads of an image before its turn, and what it keeps of one after it: an image of a PNG's size was
decoded at its opening, before any check of it, and kept so until the request ended (2026-12-01)."""
def setUp(self):
Opened.alive = []
def opening(fp, formats=None):
raw = fp.read()
if b"x" not in raw:
raise pil.UnidentifiedImageError("cannot identify image file")
return Opened(raw, formats[0])
pil, image = types.ModuleType("PIL"), types.ModuleType("PIL.Image")
pil.UnidentifiedImageError = type("UnidentifiedImageError", (OSError,), {})
image.open, image.Transpose = opening, {x: x.lower() for x in S.TURNS.values()}
pil.Image = image
def bare(raw):
kind, turn, rest = raw.split(b" ", 2)
return kind.decode(), rest, int(turn) or None
for patched in (mock.patch.dict(sys.modules, {"PIL": pil, "PIL.Image": image}), mock.patch.object(S, "bare", bare)):
patched.start()
self.addCleanup(patched.stop)
self.e = object.__new__(S.Clipstral)
self.fitted = []
class Fits(Lib):
@staticmethod
def fit(im):
self.fitted.append(im)
return "pixels"
self.e.lib = Fits()
self.e.model = types.SimpleNamespace(images=lambda ready, between: Vectors([[0.5]] * len(ready)))
self.e.torch = types.SimpleNamespace(isfinite=lambda v: types.SimpleNamespace(all=lambda: v.whole))
def test_it_is_opened_by_its_header_and_let_go(self):
self.assertEqual(self.e.opened(b"PNG 0 640x480", "input[0]"), (("PNG", b"640x480", None), (640, 480)))
self.assertEqual([(o.decoded, o.closed) for o in Opened.alive], [(False, True)])
def test_its_sides_are_those_it_is_shown_with(self):
for raw, size in ((b"JPEG 1 640x480", (640, 480)), (b"JPEG 3 640x480", (640, 480)), (b"JPEG 6 640x480", (480, 640)),
(b"PNG 8 640x480", (480, 640)), (b"PNG 5 640x480", (480, 640)), (b"WEBP 0 640x480", (480, 640))):
with self.subTest(raw):
self.assertEqual(self.e.opened(raw, "input[0]")[1], size)
self.assertFalse(any(o.decoded for o in Opened.alive))
def test_a_short_text_passes_after_each_one_decoded(self):
passed, some = [], [(f"input[{i}]", self.e.opened(b"PNG 0 640x480", "input[0]")[0]) for i in range(3)]
self.e.model = types.SimpleNamespace(images=lambda ready, between: passed.append(between) or Vectors([[0.5]] * len(ready)))
def between():
passed.append("one")
self.e.images(some, between)
self.assertEqual(passed, ["one"] * 3 + [between])
def test_one_too_large_is_refused_by_its_header(self):
for raw, words in ((b"PNG 0 40000x40000", "40000x40000, over 50 million pixels"), (b"PNG 0 70000x10", "65,535 on a side"),
(b"PNG 0 0x9", "it holds nothing"), (b"PNG 0 nothing", "is not an image this lane reads"),
(b"nothing", "is not an image this lane reads"), (b"x" * (S.MAX_IMAGE + 1), "over 20 MiB")):
with self.subTest(raw[:30]), self.assertRaises(S.Bad) as e:
self.e.opened(raw, "input[3]")
self.assertIn("input[3] is ", str(e.exception))
self.assertIn(words, str(e.exception))
self.assertFalse(any(o.decoded for o in Opened.alive))
def test_it_is_decoded_at_its_turn_shown_upright_and_let_go(self):
self.assertEqual(self.e.images([("input[0]", ("PNG", b"640x480", None)), ("input[1]", ("JPEG", b"640x480", 6))]), [[0.5], [0.5]])
first, second = Opened.alive
self.assertEqual(self.fitted, [first, (second, "rotate_270")])
for how, name in ((b"64x48 cut", "OSError"), (b"64x48 odd", "IndexError")):
with self.assertRaises(S.Bad) as e:
self.e.images([("input[0]", ("PNG", how, 6))])
self.assertEqual(str(e.exception), f"input[0] cannot be read whole: {name}")
def test_a_gray_image_of_16_bits_is_brought_to_8(self):
self.e.images([("input[0]", ("PNG", b"64x48 gray16", None))])
self.assertEqual((Opened.alive[0].mode, round(Opened.alive[0].brought, 6)), ("L", 255))
def test_a_vector_that_is_not_a_number_is_never_an_answer(self):
self.e.model = types.SimpleNamespace(images=lambda ready, between: Vectors([[float("nan")]], whole=False))
with self.assertRaises(ArithmeticError):
self.e.images([("input[0]", ("PNG", b"640x480", None))])
def test_a_text_no_token_could_hold_is_refused_unread(self):
e = Fake()
e.tok = types.SimpleNamespace(encode=lambda x: self.fail("it was read"))
with self.assertRaises(S.Bad) as bad:
e.encode([("text", "x" * (V.MAX_TOKENS * e.longest + 1))])
self.assertIn(f"over {V.MAX_TOKENS} tokens", str(bad.exception))
def test_half_a_character_is_a_400_that_names_its_entry(self):
# what JSON.stringify writes of a text cut in the middle of an emoji: the tokenizer raised, a 500 for the whole request
with self.assertRaises(S.Bad) as bad:
Fake().encode([("text", "whole"), ("text", json.loads('"cut \\ud83d"'))])
self.assertIn("input[1] holds half a character", str(bad.exception))
class Vectors:
def __init__(self, rows, whole=True):
self.rows, self.whole = rows, whole
def tolist(self):
return self.rows
class StoppedByItsUnit(unittest.TestCase):
def test_a_sigterm_ends_it_well_and_at_once(self):
"""docker stop sends it, to the container's first process: with no handler the kernel drops it there, and each stop
of the lane lasted its 20 s, ended in a kill and left the unit failed, by its 137 (review of v1.60.0)."""
src = ("import importlib.util, sys, time\n"
f"spec = importlib.util.spec_from_file_location('s', {str(REPO / 'clipstral-server.py')!r})\n"
"S = importlib.util.module_from_spec(spec); spec.loader.exec_module(S)\n"
"S.LANE.engine = lambda *a: time.sleep(60)\n"
"import vectors_server; vectors_server.Server.service_actions = lambda self: print('up', flush=True)\n"
"sys.argv = ['x', '--model-id', '/none', '--port', '0', '--threads', '1']; S.main(S.LANE)\n")
p = subprocess.Popen([sys.executable, "-I", "-c", src], stdout=subprocess.PIPE, text=True)
self.addCleanup(p.kill)
self.assertEqual(p.stdout.readline(), "up\n")
t0 = time.monotonic()
p.send_signal(signal.SIGTERM)
self.assertEqual(p.wait(10), 0, "systemd reads another exit as a failure")
self.assertLess(time.monotonic() - t0, 5)
p.stdout.close()
class OverHttp(unittest.TestCase):
def setUp(self):
self.lines, self.was, V.log = [], V.log, lambda line: self.lines.append(line)
self.addCleanup(setattr, S, "log", self.was)
self.engine = Fake()
self.state = {"engine": self.engine}
self.srv = ThreadingHTTPServer(("127.0.0.1", 0), V.make_handler(self.state, S.LANE))
self.srv.daemon_threads = True
threading.Thread(target=self.srv.serve_forever, daemon=True).start()
self.addCleanup(self.srv.server_close)
self.addCleanup(self.srv.shutdown)
self.conn = http.client.HTTPConnection("127.0.0.1", self.srv.server_address[1], timeout=10)
self.addCleanup(self.conn.close)
def ask(self, body, path="/v1/embeddings", headers=None):
raw = body if isinstance(body, bytes) else json.dumps(body).encode()
self.conn.request("POST", path, raw, {"Content-Type": "application/json", **(headers or {})})
r = self.conn.getresponse()
return r.status, json.loads(r.read()), r
def get(self, path):
self.conn.request("GET", path)
r = self.conn.getresponse()
return r.status, json.loads(r.read())
def test_the_answer_is_the_openai_shape(self):
st, d, _ = self.ask({"model": "whatever", "input": ["one two", CHUNK]})
self.assertEqual((st, d["object"], d["model"]), (200, "list", S.NAME))
self.assertEqual([(x["object"], x["index"], len(x["embedding"])) for x in d["data"]],
[("embedding", 0, 1024), ("embedding", 1, 1024)])
self.assertEqual(d["usage"], {"prompt_tokens": 4 + 6, "total_tokens": 10})
st, b, _ = self.ask({"input": ["one two", CHUNK], "encoding_format": "base64"})
for x, y in zip(d["data"], b["data"]):
self.assertEqual(list(struct.unpack("<1024f", base64.b64decode(y["embedding"]))), x["embedding"])
def test_a_refusal_is_a_400_and_the_connection_goes_on(self):
for body, words in (({"input": []}, "not empty"), (b"[1]", "a JSON object"), (b"{", "a JSON object"),
(b"[" * 100_000, "a JSON object"), ({"input": "a", "dimensions": 8}, "1024 dimensions"),
({"input": "word " * V.MAX_TOKENS}, f"over {V.MAX_TOKENS}")):
with self.subTest(words):
st, d, _ = self.ask(body)
self.assertEqual((st, d["error"]["type"]), (400, "invalid_request_error"))
self.assertIn(words, d["error"]["message"])
self.assertEqual(self.ask({"input": "still here"})[0], 200)
def test_a_body_with_no_length_or_too_long_is_refused_unread(self):
for headers, code, words in (({"Content-Length": str(V.MAX_BODY + 1)}, 413, "64 MiB"), ({"Content-Length": "-1"}, 411, "no Content-Length"),
({"Content-Length": "x"}, 411, "no Content-Length"), ({}, 411, "no Content-Length")):
with self.subTest(headers):
c = http.client.HTTPConnection("127.0.0.1", self.srv.server_address[1], timeout=10)
c.putrequest("POST", "/v1/embeddings")
for k, v in headers.items():
c.putheader(k, v)
c.endheaders()
r = c.getresponse()
self.assertEqual((r.status, r.getheader("Connection")), (code, "close"))
self.assertIn(words, json.loads(r.read())["error"]["message"])
c.close()
st, d, _ = self.ask(b"", headers={"Transfer-Encoding": "chunked"})
self.assertEqual(st, 411)
def test_a_body_refused_unread_is_read_out_for_a_client_that_closes_too(self):
"""Closed at once, the socket answers what the client still sends with a reset, which takes the answer back."""
for head in ("POST /v1/embeddings HTTP/1.1\r\nHost: x\r\nConnection: close\r\n", "POST /v1/embeddings HTTP/1.0\r\n"):
with socket.create_connection(("127.0.0.1", self.srv.server_address[1]), timeout=10) as s:
s.sendall(f"{head}Content-Length: {V.MAX_BODY + 1}\r\n\r\n".encode() + b"x" * 200_000)
time.sleep(0.3)
s.sendall(b"x" * 200_000)
got = b""
while chunk := s.recv(65536):
got += chunk
self.assertIn(b" 413 ", got.split(b"\r\n", 1)[0])
self.assertIn(b"64 MiB", got)
def test_a_client_gone_before_its_answer_leaves_one_line(self):
real = self.engine.texts
def left(ids, between):
c.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
c.close()
time.sleep(0.2)
return real(ids)
self.engine.texts = left
c = http.client.HTTPConnection("127.0.0.1", self.srv.server_address[1], timeout=10)
c.request("POST", "/v1/embeddings", json.dumps({"input": ["word " * 50] * 500}).encode())
end = time.monotonic() + 5
while not any("gone" in x for x in self.lines) and time.monotonic() < end:
time.sleep(0.02)
self.assertEqual(len([x for x in self.lines if "gone" in x]), 1, self.lines)
def test_while_the_model_loads(self):
self.state.clear()
self.assertEqual(self.get("/health"), (503, {"status": "loading"}))
st, d, r = self.ask({"input": "a"})
self.assertEqual((st, d["error"]["type"], r.getheader("Retry-After")), (503, "engine_unavailable", "5"))
self.state["engine"] = self.engine
self.assertEqual(self.get("/health"), (200, {"status": "ok"}))
self.assertEqual(self.ask({"input": "a"})[0], 200)
def test_its_other_routes(self):
st, d = self.get("/v1/models")
self.assertEqual((st, [m["id"] for m in d["data"]]), (200, [S.NAME]))
self.assertEqual(self.get("/nothing")[0], 404)
self.assertEqual(self.ask({"input": "a"}, "/v1/chat/completions")[0], 404)
def test_what_the_model_could_not_compute_is_said_in_a_line(self):
self.engine.texts = lambda ids, between: (_ for _ in ()).throw(RuntimeError("no memory"))
st, d, _ = self.ask({"input": "a"})
self.assertEqual((st, d["error"]["type"], d["error"]["message"]),
(500, "server_error", "the model did not compute it: RuntimeError: no memory"))
del self.engine.texts
self.assertEqual(self.ask({"input": "a"})[0], 200, "the turn was given back")
def test_a_client_that_leaves_stops_its_job(self):
started, go = threading.Event(), threading.Event()
real = Fake.images
def slow(some, between):
started.set()
go.wait(5)
return real(self.engine, some)
self.engine.images = slow
c = http.client.HTTPConnection("127.0.0.1", self.srv.server_address[1], timeout=10)
c.request("POST", "/v1/embeddings", json.dumps({"input": [CHUNK] * (3 * V.BATCH_IMAGES)}).encode())
self.assertTrue(started.wait(5))
c.sock.close()
c.close()
go.set()
end = time.monotonic() + 5
while not any("gone" in x for x in self.lines) and time.monotonic() < end:
time.sleep(0.01)
self.assertEqual(len(self.engine.calls), 1, "it was computed for nobody")
self.assertTrue(any("gone" in x for x in self.lines), self.lines)
if __name__ == "__main__":
unittest.main(verbosity=2)