Files
lincodex/ml/tests/test_ensemble_and_auth.py

353 lines
12 KiB
Python

"""Several models in one service, device memory failures, and the bearer token."""
import logging
from collections.abc import Sequence
from dataclasses import replace
from pathlib import Path
import httpx
import pytest
from fastapi import FastAPI
from lincodex_ml import serve
from lincodex_ml.config import (
DType,
EmbedderKind,
ServiceToken,
Settings,
SettingsError,
is_loopback_host,
load_settings,
)
from lincodex_ml.inference import runtime as runtime_module
from lincodex_ml.inference.embedder import InputKind, ModelInfo
from lincodex_ml.inference.fake import FakeEmbedder
from lincodex_ml.inference.runtime import (
OOM_COOL_DOWN_SECONDS,
EmbeddingRuntime,
RuntimeState,
)
from lincodex_ml.main import create_app
TOKEN = "t0k3n-" + "x" * 40
OTHER_MODEL = "lincodex/fake-second-embedder"
@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 Clock:
def __init__(self) -> None:
self.now = 1000.0
def __call__(self) -> float:
return self.now
class DeviceFull(Exception):
"""Stands for a CUDA out-of-memory error."""
class FlakyEmbedder:
"""Runs out of device memory while `full` is set."""
def __init__(self) -> None:
self.inner = FakeEmbedder(model_id=OTHER_MODEL)
self.full = False
self.released = 0
@property
def info(self) -> ModelInfo:
return self.inner.info
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
if self.full:
raise DeviceFull
return self.inner.encode_batch(kind, texts)
def recover(self, error: BaseException) -> bool:
self.released += 1
return isinstance(error, DeviceFull)
def _ready(settings: Settings, *embedders: object, clock: Clock | None = None) -> FastAPI:
runtime = EmbeddingRuntime(
settings,
[lambda embedder=embedder: embedder for embedder in embedders], # type: ignore[misc]
clock=clock or Clock(),
)
runtime.start()
assert runtime.wait(10) is RuntimeState.READY
return create_app(settings, runtime)
async def _call(
application: FastAPI,
method: str,
path: str,
client: tuple[str, int] = ("127.0.0.1", 50000),
**kwargs: object,
) -> httpx.Response:
transport = httpx.ASGITransport(app=application, client=client)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
return await http.request(method, path, **kwargs) # type: ignore[arg-type]
# ---------------------------------------------------------------- settings
def test_settings_accept_an_ordered_model_list_and_cuda_options(tmp_path: Path) -> None:
token_file = tmp_path / "token"
token_file.write_text(TOKEN + "\n", encoding="utf-8")
settings = load_settings(
{
"ML_EMBEDDER": "giga, qwen3",
"ML_DEVICE": "cuda",
"ML_DTYPE": "float16",
"ML_CUDA_MEMORY_LIMIT_MB": "2300",
"ML_SERVICE_TOKEN_FILE": str(token_file),
"ML_GIGA_MODEL_DIR": "/models/giga",
"ML_QWEN3_MODEL_DIR": "/models/qwen3",
"ML_QWEN3_MODEL_LOCK": "/locks/qwen3.lock.json",
"ML_LISTEN_HOST": "192.168.10.25",
"ML_LISTEN_PORT": "8790",
}
)
assert settings.embedders == (EmbedderKind.GIGA, EmbedderKind.QWEN3)
assert (settings.device, settings.dtype, settings.cuda_memory_limit_mb) == (
"cuda",
DType.FLOAT16,
2300,
)
assert settings.token is not None and settings.token.reveal() == TOKEN
assert settings.location(EmbedderKind.GIGA).lock == Path("/models/giga/model.lock.json")
assert settings.location(EmbedderKind.QWEN3).lock == Path("/locks/qwen3.lock.json")
assert (settings.listen_host, settings.listen_port) == ("192.168.10.25", 8790)
assert TOKEN not in repr(settings) and TOKEN not in str(settings.token)
@pytest.mark.parametrize(
"environ",
[
{"ML_EMBEDDER": "giga,giga"},
{"ML_EMBEDDER": "fake,giga"},
{"ML_EMBEDDER": "giga,gpt"},
{"ML_DEVICE": "tpu"},
{"ML_DTYPE": "float16"},
{"ML_DEVICE": "cuda", "ML_DTYPE": "int8"},
{"ML_CUDA_MEMORY_LIMIT_MB": "2000"},
{"ML_SERVICE_TOKEN": "short"},
{"ML_SERVICE_TOKEN": "x" * 20 + " " + "y" * 20},
{"ML_SERVICE_TOKEN": TOKEN, "ML_SERVICE_TOKEN_FILE": "/run/token"},
{"ML_SERVICE_TOKEN_FILE": "/nonexistent/token"},
{"ML_LISTEN_PORT": "70000"},
],
)
def test_settings_reject_invalid_combinations(environ: dict[str, str]) -> None:
with pytest.raises(SettingsError) as raised:
load_settings(environ)
assert TOKEN not in str(raised.value)
def test_loopback_detection() -> None:
assert all(is_loopback_host(host) for host in ("127.0.0.1", "::1", "[::1]", "localhost"))
assert not any(is_loopback_host(host) for host in ("0.0.0.0", "192.168.10.25", "ml", "::"))
# ---------------------------------------------------------------- several models
@pytest.mark.anyio
async def test_the_model_field_selects_one_of_the_loaded_models() -> None:
application = _ready(_settings(), FakeEmbedder(), FakeEmbedder(model_id=OTHER_MODEL))
body = {"kind": "query", "texts": ["Kafka consumer idempotency"]}
default = await _call(application, "POST", "/v1/embeddings", json=body)
second = await _call(application, "POST", "/v1/embeddings", json={**body, "model": OTHER_MODEL})
unknown = await _call(application, "POST", "/v1/embeddings", json={**body, "model": "x/y"})
assert default.status_code == 200 and second.status_code == 200
assert default.json()["model"]["id"] == "lincodex/fake-hash-embedder"
assert second.json()["model"]["id"] == OTHER_MODEL
assert default.json()["vectors"] != second.json()["vectors"]
assert unknown.status_code == 400
assert unknown.json()["errors"][0]["pointer"] == "/model"
def test_readiness_needs_every_model_and_a_broken_one_fails_the_service() -> None:
def broken() -> FakeEmbedder:
raise OSError("weights are missing")
runtime = EmbeddingRuntime(_settings(), [FakeEmbedder, broken])
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
assert not runtime.ready()
def test_a_permanent_load_failure_calls_the_exit_hook_and_memory_does_not() -> None:
calls: list[str] = []
def broken() -> FakeEmbedder:
raise OSError("weights are missing")
runtime = EmbeddingRuntime(_settings(), [broken], on_failure=lambda: calls.append("exit"))
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
assert calls == ["exit"]
assert load_settings({"ML_EXIT_ON_LOAD_FAILURE": "true"}).exit_on_load_failure
def test_two_encoders_with_one_model_id_are_refused() -> None:
runtime = EmbeddingRuntime(_settings(), [FakeEmbedder, FakeEmbedder])
runtime.start()
assert runtime.wait(10) is RuntimeState.FAILED
# ---------------------------------------------------------------- device memory
@pytest.mark.anyio
async def test_out_of_memory_answers_503_and_cools_readiness_down_without_crashing() -> None:
clock = Clock()
flaky = FlakyEmbedder()
application = _ready(_settings(), flaky, clock=clock)
body = {"kind": "document", "texts": ["Stack: go, kafka"]}
flaky.full = True
failed = await _call(application, "POST", "/v1/embeddings", json=body)
readiness = await _call(application, "GET", "/readyz")
assert failed.status_code == 503
assert failed.json()["code"] == "service_unavailable"
assert failed.headers["retry-after"] == "5"
assert readiness.status_code == 503
assert flaky.released >= 1
flaky.full = False
clock.now += OOM_COOL_DOWN_SECONDS + 1
recovered = await _call(application, "POST", "/v1/embeddings", json=body)
assert recovered.status_code == 200
assert (await _call(application, "GET", "/readyz")).status_code == 200
def test_a_load_that_runs_out_of_memory_is_retried(monkeypatch: pytest.MonkeyPatch) -> None:
attempts: list[int] = []
pauses: list[float] = []
def factory() -> FakeEmbedder:
attempts.append(1)
if len(attempts) < 3:
raise DeviceFull
return FakeEmbedder()
monkeypatch.setattr(
runtime_module, "_released_after", lambda error, _: isinstance(error, DeviceFull)
)
runtime = EmbeddingRuntime(_settings(), [factory], sleep=pauses.append)
runtime.start()
assert runtime.wait(10) is RuntimeState.READY
assert len(attempts) == 3
assert pauses == [15.0, 30.0]
# ---------------------------------------------------------------- bearer token
@pytest.mark.anyio
async def test_a_configured_token_guards_every_route_but_the_probes(
caplog: pytest.LogCaptureFixture,
) -> None:
application = _ready(_settings(token=ServiceToken(TOKEN)), FakeEmbedder())
body = {"kind": "query", "texts": ["Go"]}
remote = ("192.168.10.30", 41000)
with caplog.at_level(logging.DEBUG):
missing = await _call(application, "POST", "/v1/embeddings", remote, json=body)
wrong = await _call(
application,
"POST",
"/v1/embeddings",
remote,
json=body,
headers={"Authorization": "Bearer " + TOKEN[:-1] + "y"},
)
basic = await _call(
application,
"POST",
"/v1/embeddings",
remote,
json=body,
headers={"Authorization": "Basic " + TOKEN},
)
metrics = await _call(application, "GET", "/metrics/", remote)
accepted = await _call(
application,
"POST",
"/v1/embeddings",
remote,
json=body,
headers={"Authorization": "bearer " + TOKEN},
)
health = await _call(application, "GET", "/healthz", remote)
ready = await _call(application, "GET", "/readyz", remote)
for refused in (missing, wrong, basic, metrics):
assert refused.status_code == 401
assert refused.headers["www-authenticate"] == "Bearer"
assert refused.json()["code"] == "unauthenticated"
assert TOKEN not in refused.text
assert accepted.status_code == 200
assert health.status_code == 200 and ready.status_code == 200
assert TOKEN not in caplog.text
@pytest.mark.anyio
async def test_without_a_token_only_loopback_callers_are_served() -> None:
application = _ready(_settings(), FakeEmbedder())
body = {"kind": "query", "texts": ["Go"]}
local = await _call(application, "POST", "/v1/embeddings", json=body)
remote = await _call(application, "POST", "/v1/embeddings", ("10.0.0.7", 5000), json=body)
assert local.status_code == 200
assert remote.status_code == 401
@pytest.mark.anyio
async def test_an_unauthenticated_body_is_never_read() -> None:
application = _ready(_settings(token=ServiceToken(TOKEN), max_body_bytes=1024), FakeEmbedder())
response = await _call(
application,
"POST",
"/v1/embeddings",
("10.0.0.7", 5000),
json={"kind": "query", "texts": ["x" * 4000]},
)
assert response.status_code == 401
# ---------------------------------------------------------------- entry point
def test_serve_refuses_a_network_address_without_a_token(monkeypatch: pytest.MonkeyPatch) -> None:
started: list[object] = []
monkeypatch.setattr(serve.uvicorn, "run", lambda *args, **kwargs: started.append(kwargs))
for name in ("ML_SERVICE_TOKEN", "ML_SERVICE_TOKEN_FILE", "ML_EMBEDDER"):
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("ML_LISTEN_HOST", "0.0.0.0")
assert serve.main() == 2
assert started == []
monkeypatch.setenv("ML_SERVICE_TOKEN", TOKEN)
assert serve.main() == 0
assert started and started[0]["host"] == "0.0.0.0" # type: ignore[index]
monkeypatch.delenv("ML_SERVICE_TOKEN")
monkeypatch.setenv("ML_LISTEN_HOST", "127.0.0.1")
assert serve.main() == 0