142 lines
7.3 KiB
Python
142 lines
7.3 KiB
Python
import copy
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
import urllib.error
|
|
|
|
from pages_ml import Application, Engine, Failure, MAX_BODY, digest, tokens, validate_vectors
|
|
from train import train
|
|
|
|
DOMAIN = "11111111-1111-4111-8111-111111111111"
|
|
SCOPE = "22222222-2222-4222-8222-222222222222"
|
|
TOKEN = "t" * 40
|
|
|
|
|
|
def request():
|
|
return {"protocol": "1", "domain_uuid": DOMAIN, "scope_uuid": SCOPE,
|
|
"provider": "openai", "model": "text-embedding-3-small", "dimensions": 2,
|
|
"inputs": [{"id": "page:chunk0", "text": "合成文書 library books"}], "allow_external": True}
|
|
|
|
|
|
def call(app, data=None, **changes):
|
|
body = json.dumps(data if data is not None else request()).encode()
|
|
env = {"PATH_INFO": "/v1/embeddings", "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/json",
|
|
"CONTENT_LENGTH": str(len(body)), "HTTP_AUTHORIZATION": "Bearer " + TOKEN, "wsgi.input": io.BytesIO(body)}
|
|
env.update(changes)
|
|
result = []
|
|
raw = b"".join(app(env, lambda status, headers: result.extend([int(status.split()[0]), dict(headers)])))
|
|
return result[0], json.loads(raw), result[1]
|
|
|
|
|
|
class BoundaryTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.engine = Engine("/nonexistent")
|
|
self.app = Application(TOKEN, self.engine)
|
|
|
|
def test_auth_and_health(self):
|
|
for value in ("", "Bearer wrong", "Bearer ü"):
|
|
self.assertEqual(call(self.app, HTTP_AUTHORIZATION=value)[0], 401)
|
|
self.assertEqual(call(self.app, PATH_INFO="/healthz", REQUEST_METHOD="GET", HTTP_AUTHORIZATION="")[0], 200)
|
|
self.assertEqual(call(self.app, PATH_INFO="/healthz?token=secret")[0], 404)
|
|
with self.assertRaises(ValueError):
|
|
Application("short", self.engine)
|
|
|
|
def test_external_off_without_network(self):
|
|
with patch("urllib.request.build_opener") as opener:
|
|
self.assertEqual(call(self.app)[0], 403)
|
|
self.engine.external_enabled, self.engine.api_key = True, "fake-key"
|
|
data = request(); data["allow_external"] = False
|
|
self.assertEqual(call(self.app, data)[0], 403)
|
|
opener.assert_not_called()
|
|
|
|
def test_bounds_and_busy(self):
|
|
for changes, status in [({"CONTENT_LENGTH": str(MAX_BODY+1)}, 413),
|
|
({"CONTENT_LENGTH": ""}, 411), ({"CONTENT_TYPE": "text/plain"}, 415),
|
|
({"wsgi.input": io.BytesIO(b"{")}, 400)]:
|
|
self.assertEqual(call(self.app, **changes)[0], status)
|
|
for key, value in [("scope_uuid", "../../"), ("dimensions", True), ("dimensions", 1537),
|
|
("inputs", []), ("inputs", [{"id": "a", "text": "x"*6001}]),
|
|
("allow_external", "true"), ("unexpected", "x")]:
|
|
data = request(); data[key] = value
|
|
self.assertEqual(call(self.app, data)[0], 400)
|
|
data = request(); data["inputs"] *= 2
|
|
self.assertEqual(call(self.app, data)[0], 400)
|
|
self.app.slot.acquire()
|
|
try:
|
|
status, _, headers = call(self.app)
|
|
self.assertEqual(status, 429); self.assertEqual(headers["Retry-After"], "5")
|
|
self.assertEqual(call(self.app, PATH_INFO="/healthz", REQUEST_METHOD="GET")[0], 200)
|
|
finally:
|
|
self.app.slot.release()
|
|
|
|
def test_openai_contract(self):
|
|
self.engine.external_enabled, self.engine.api_key = True, "fake-key"
|
|
data = request()
|
|
result = {"model": data["model"], "data": [{"index": 0, "embedding": [0.5, -0.2]}], "usage": {"total_tokens": 10}}
|
|
with patch("urllib.request.build_opener") as opener:
|
|
opener.return_value.open.return_value.__enter__.return_value.read.return_value = json.dumps(result).encode()
|
|
status, body, _ = call(self.app, data)
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(body["outputs"][0]["input_sha256"], digest(data["inputs"][0]["text"].encode()))
|
|
sent = opener.return_value.open.call_args.args[0]
|
|
self.assertEqual(sent.full_url, "https://api.openai.com/v1/embeddings")
|
|
self.assertEqual(json.loads(sent.data)["encoding_format"], "float")
|
|
result["data"][0]["embedding"] = [float("nan"), 1]
|
|
opener.return_value.open.return_value.__enter__.return_value.read.return_value = json.dumps(result).encode()
|
|
self.assertEqual(call(self.app)[0], 502)
|
|
opener.return_value.open.side_effect = urllib.error.HTTPError(sent.full_url, 429, "secret input", {}, io.BytesIO(b"secret"))
|
|
status, body, _ = call(self.app)
|
|
self.assertEqual(status, 429); self.assertNotIn("secret", json.dumps(body))
|
|
# No automatic provider retries.
|
|
self.assertEqual(opener.return_value.open.call_count, 3)
|
|
|
|
def test_bad_vectors_and_tokenizer(self):
|
|
for vectors in ([[0, 0]], [[1]], [[True, 1]], [[float("inf"), 1]], [[10**1000, 1]], []):
|
|
with self.assertRaises(Failure): validate_vectors(vectors, 1, 2)
|
|
self.assertEqual(tokens("図書館 BOOK"), ["図書", "書館", "book"])
|
|
|
|
|
|
class Doc2VecTests(unittest.TestCase):
|
|
def test_real_train_infer_and_isolation(self):
|
|
# Only generated fixture text, never data/ or user documents.
|
|
with tempfile.TemporaryDirectory() as root:
|
|
source = Path(root) / "synthetic.jsonl"
|
|
source.write_text("\n".join(json.dumps({"text": text}) for text in [
|
|
"図書館 読書 本 library books reading", "図書館 本 文書 library documents books",
|
|
"ネットワーク サーバー network server routing", "サーバー 通信 network routing server"]))
|
|
manifest = train(source, root, DOMAIN, SCOPE, 8)
|
|
engine = Engine(root); app = Application(TOKEN, engine)
|
|
data = request(); data.update(provider="doc2vec", model=manifest["model_sha256"], dimensions=8, allow_external=False)
|
|
status, result, _ = call(app, data)
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(len(result["outputs"][0]["vector"]), 8)
|
|
self.assertEqual(call(app, data)[1]["outputs"], result["outputs"])
|
|
for key in ("domain_uuid", "scope_uuid"):
|
|
other = copy.deepcopy(data); other[key] = "33333333-3333-4333-8333-333333333333"
|
|
self.assertEqual(call(app, other)[0], 404)
|
|
unknown = copy.deepcopy(data); unknown["inputs"][0]["text"] = "zzzzunknownword"
|
|
self.assertEqual(call(app, unknown)[0], 422)
|
|
wrong = copy.deepcopy(data); wrong["dimensions"] = 9
|
|
self.assertEqual(call(app, wrong)[0], 409)
|
|
model_dir = Path(root) / DOMAIN / SCOPE / data["model"]
|
|
model_file = model_dir / "model.bin"
|
|
original = model_file.read_bytes()
|
|
model_file.write_bytes(b"untrusted replacement")
|
|
self.assertEqual(call(app, data)[0], 409)
|
|
model_file.write_bytes(original)
|
|
self.assertEqual(call(app, data)[0], 200)
|
|
model_file.unlink()
|
|
self.assertEqual(call(app, data)[0], 404)
|
|
model_file.write_bytes(original)
|
|
self.assertEqual(call(app, data)[0], 200)
|
|
(model_dir / "manifest.json").unlink()
|
|
self.assertEqual(call(app, data)[0], 404) # Cached model cannot outlive removal.
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|