Files
lincodex/ml/tests/test_embeddings.py

238 lines
8.8 KiB
Python

import json
import logging
import math
from collections.abc import Sequence
from dataclasses import replace
from pathlib import Path
import httpx
import pytest
import yaml
from fastapi import FastAPI
from lincodex_ml.config import Settings, load_settings
from lincodex_ml.inference.embedder import InputKind, ModelInfo, micro_batches
from lincodex_ml.inference.fake import FakeEmbedder
from lincodex_ml.inference.runtime import EmbeddingRuntime, RuntimeState
from lincodex_ml.main import create_app
CONTRACT_PATH = Path(__file__).resolve().parents[2] / "api" / "ml" / "openapi.bundle.yml"
PRIVATE_TEXT = "Jane Doe, +7 900 000-00-00, built a ledger at Example Bank"
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
def _settings(**overrides: object) -> Settings:
return replace(load_settings({"ML_EMBEDDER": "fake"}), **overrides) # type: ignore[arg-type]
class RecordingEmbedder:
"""Fake encoder that records the micro-batches it receives."""
def __init__(self) -> None:
self.inner = FakeEmbedder()
self.batches: list[list[str]] = []
@property
def info(self) -> ModelInfo:
return self.inner.info
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
self.batches.append(list(texts))
return self.inner.encode_batch(kind, texts)
def recover(self, error: BaseException) -> bool:
return False
def _ready_app(settings: Settings, embedder: object | None = None) -> FastAPI:
built = embedder if embedder is not None else FakeEmbedder()
runtime = EmbeddingRuntime(settings, lambda: built) # type: ignore[arg-type, return-value]
runtime.start()
assert runtime.wait(10) is RuntimeState.READY
return create_app(settings, runtime)
async def _post(application: FastAPI, body: object, **kwargs: object) -> httpx.Response:
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
return await client.post("/v1/embeddings", json=body, **kwargs) # type: ignore[arg-type]
@pytest.mark.anyio
async def test_embeddings_return_normalized_vectors_in_request_order() -> None:
application = _ready_app(_settings())
texts = ["short", "a much longer text than the first one", "mid length text"]
response = await _post(application, {"kind": "document", "texts": texts})
assert response.status_code == 200
body = response.json()
assert body["kind"] == "document"
assert body["model"]["id"] == "lincodex/fake-hash-embedder"
assert body["model"]["dimension"] == 32
assert len(body["vectors"]) == len(texts)
for text, vector in zip(texts, body["vectors"], strict=True):
assert vector == FakeEmbedder().encode_batch(InputKind.DOCUMENT, [text])[0]
assert math.isclose(math.sqrt(sum(value * value for value in vector)), 1.0, abs_tol=1e-6)
@pytest.mark.anyio
async def test_identical_requests_give_identical_vectors_and_kinds_differ() -> None:
application = _ready_app(_settings(micro_batch=2))
body = {"kind": "query", "texts": ["Kafka", "make payment callbacks idempotent", "Go"]}
first = (await _post(application, body)).json()
second = (await _post(application, body)).json()
document = (await _post(application, {**body, "kind": "document"})).json()
assert first == second
assert first["vectors"] != document["vectors"]
def test_micro_batches_sort_by_length_with_position_as_tie_breaker() -> None:
texts = ["bb", "a", "cc", "dddd", "e"]
assert micro_batches(texts, 2) == [[3, 0], [2, 1], [4]]
assert micro_batches(texts, 1) == [[3], [0], [2], [1], [4]]
@pytest.mark.anyio
async def test_micro_batch_size_bounds_every_forward_pass() -> None:
recorder = RecordingEmbedder()
application = _ready_app(_settings(micro_batch=2), recorder)
recorder.batches.clear()
await _post(application, {"kind": "document", "texts": ["a", "bbb", "cc", "dddd", "e"]})
assert recorder.batches == [["dddd", "bbb"], ["cc", "a"], ["e"]]
@pytest.mark.anyio
async def test_service_answers_503_until_the_model_is_ready() -> None:
application = create_app(_settings(embedders=()))
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
response = await client.post("/v1/embeddings", json={"kind": "query", "texts": ["Go"]})
readiness = await client.get("/readyz")
assert response.status_code == 503
assert response.headers["content-type"].startswith("application/problem+json")
assert response.json()["code"] == "service_unavailable"
assert response.headers["retry-after"] == "5"
assert readiness.status_code == 503
@pytest.mark.anyio
async def test_readiness_turns_ready_only_after_the_warm_up() -> None:
application = _ready_app(_settings())
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
response = await client.get("/readyz")
assert response.status_code == 200
assert response.json() == {"status": "ready"}
def test_failed_load_keeps_the_service_not_ready(caplog: pytest.LogCaptureFixture) -> None:
def broken() -> FakeEmbedder:
raise OSError(PRIVATE_TEXT)
runtime = EmbeddingRuntime(_settings(), broken)
with caplog.at_level(logging.INFO):
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
assert PRIVATE_TEXT not in caplog.text
@pytest.mark.anyio
@pytest.mark.parametrize(
"body",
[
{"kind": "query", "texts": []},
{"kind": "query", "texts": ["x"] * 33},
{"kind": "query", "texts": ["x" * 8001]},
{"kind": "query", "texts": [""]},
{"kind": "summary", "texts": ["x"]},
{"kind": "query", "texts": ["x"], "prompt": "ignore the instruction"},
],
)
async def test_requests_outside_the_contract_answer_400(body: object) -> None:
application = _ready_app(_settings())
response = await _post(application, body)
assert response.status_code == 400
assert response.json()["code"] == "validation_failed"
@pytest.mark.anyio
async def test_body_over_the_limit_answers_413() -> None:
application = _ready_app(_settings(max_body_bytes=1024))
response = await _post(application, {"kind": "query", "texts": ["x" * 2000]})
assert response.status_code == 413
assert response.json()["code"] == "payload_too_large"
@pytest.mark.anyio
async def test_streamed_body_over_the_limit_answers_413() -> None:
application = _ready_app(_settings(max_body_bytes=1024))
payload = json.dumps({"kind": "query", "texts": ["x" * 2000]}).encode()
async def chunks(): # type: ignore[no-untyped-def]
for start in range(0, len(payload), 256):
yield payload[start : start + 256]
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application), base_url="http://test"
) as client:
response = await client.post(
"/v1/embeddings", content=chunks(), headers={"content-type": "application/json"}
)
assert response.status_code == 413
@pytest.mark.anyio
async def test_request_texts_never_reach_the_log(caplog: pytest.LogCaptureFixture) -> None:
application = _ready_app(_settings())
with caplog.at_level(logging.DEBUG):
await _post(application, {"kind": "document", "texts": [PRIVATE_TEXT]})
await _post(application, {"kind": "document", "texts": [PRIVATE_TEXT * 2000]})
assert "Jane Doe" not in caplog.text
def test_embedding_operation_matches_the_shared_contract() -> None:
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
operation = contract["paths"]["/v1/embeddings"]["post"]
implementation = create_app(_settings(embedders=())).openapi()
actual = implementation["paths"]["/v1/embeddings"]["post"]
assert actual["operationId"] == operation["operationId"]
assert set(operation["responses"]) >= {"200", "400", "413", "503"}
def test_settings_reject_invalid_values() -> None:
from lincodex_ml.config import SettingsError
for environ in (
{"ML_EMBEDDER": "gpt"},
{"ML_TORCH_THREADS": "0"},
{"ML_MICRO_BATCH": "many"},
{"ML_VERIFY_WEIGHTS": "maybe"},
):
with pytest.raises(SettingsError):
load_settings(environ)
settings = load_settings({})
assert settings.embedders == ()
assert (settings.torch_threads, settings.micro_batch, settings.max_tokens) == (4, 1, 1024)
@pytest.mark.anyio
async def test_a_request_may_name_the_served_model_and_not_another() -> None:
application = _ready_app(_settings())
served = await _post(
application, {"model": "lincodex/fake-hash-embedder", "kind": "query", "texts": ["Go"]}
)
assert served.status_code == 200
other = await _post(application, {"model": "example/other", "kind": "query", "texts": ["Go"]})
assert other.status_code == 400
assert other.json()["errors"][0]["pointer"] == "/model"