# SPDX-License-Identifier: Apache-2.0 """Host tests of the HTTP server with the fake backend (no device, no weights): routes, the official response shape, validation errors, auth, batching of concurrent requests, and the configuration parser. python -m pytest tt_laya/tests/test_host_server.py -q """ from __future__ import annotations import concurrent.futures import os import pytest Q = { "department": {"type": "choice", "instructions": "Which department?", "criteria": {"billing": "invoices", "technical": "bugs", "other": None}}, "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["low", "mid", "high"]}, "churn": {"type": "noul", "instructions": "Will they leave?"}, } @pytest.fixture() def client(monkeypatch): from fastapi.testclient import TestClient from tt_laya import config as C from tt_laya.api import Laya from tt_laya.server.app import create_app for k in list(os.environ): if k.startswith("LAYA_"): monkeypatch.delenv(k, raising=False) app = create_app(lambda cfg: Laya.from_pretrained(config=cfg, backend="fake")) with TestClient(app) as c: yield c def test_health_info(client): h = client.get("/health").json() assert h["status"] == "ok" and h["profile"] == "english" i = client.get("/info").json() assert i["ready"] and i["limits"]["max_questions"] == 64 and i["config"]["engine"] == "mk" def test_systemone_shape(client): r = client.post("/v1/systemone", json={"state": {"body": "billed twice"}, "questions": Q}) assert r.status_code == 200, r.text d = r.json() assert d["model"] == "laya-rl-agent" and d["routing"]["model"] == "english" a = d["answers"] assert a["department"]["choice"] in ("billing", "technical", "other") assert set(a["department"]) >= {"type", "choice", "probabilities", "confidence", "answer_confidence", "action", "x_jev_confidence"} assert set(a["urgency"]) >= {"score", "legend", "probabilities"} assert 0.0 <= a["churn"]["noul"] <= 1.0 and "x_jev_confidence" not in a["churn"] assert d["usage"]["output_tokens"] == 0 and d["usage"]["input_tokens"] > 0 def test_min_confidence_and_batch(client): r = client.post("/v1/systemone", json={"state": "x y z", "questions": Q, "min_confidence": 0.99}) assert all(a["abstention"] in ("passed", "abstained") for a in r.json()["answers"].values()) r = client.post("/v1/systemone/batch", json={"states": ["a", {"k": "v"}, [{"role": "user", "content": "c"}]], "questions": Q}) assert r.status_code == 200 and len(r.json()["results"]) == 3 r = client.post("/predict_batch", json={"states": ["a", "b"], "questions": Q}) assert r.status_code == 200 and isinstance(r.json(), list) and "routing" not in r.json()[0] def test_errors(client): assert client.post("/v1/systemone", content=b"{bad").status_code == 400 assert client.post("/v1/systemone", json={"state": "x"}).status_code == 400 r = client.post("/v1/systemone", json={"state": "x", "questions": {"q": {"type": "maybe", "instructions": "i"}}}) assert r.status_code == 422 and "unknown type" in r.json()["detail"] r = client.post("/v1/systemone", json={"state": "x", "questions": Q, "max_len": 100000}) assert r.status_code == 422 and "max_len" in r.json()["detail"] r = client.post("/v1/systemone", json={"state": "x", "questions": Q, "min_confidence": 2}) assert r.status_code == 422 r = client.post("/v1/systemone", json={"state": "x", "questions": Q, "model": "multilingual"}) assert r.status_code == 422 and "LAYA_PROFILE" in r.json()["detail"] many = {"q": {"type": "choice", "instructions": "i", "criteria": [str(i) for i in range(101)]}} r = client.post("/v1/systemone", json={"state": "x", "questions": many}) assert r.status_code == 422 and "LAYA_MAX_OPTIONS" in r.json()["detail"] def test_auth(monkeypatch): from fastapi.testclient import TestClient from tt_laya.api import Laya from tt_laya.server.app import create_app monkeypatch.setenv("LAYA_API_KEY", "s3cret") app = create_app(lambda cfg: Laya.from_pretrained(config=cfg, backend="fake")) with TestClient(app) as c: assert c.post("/v1/systemone", json={"state": "x", "questions": Q}).status_code == 401 ok = c.post("/v1/systemone", json={"state": "x", "questions": Q}, headers={"Authorization": "Bearer s3cret"}) assert ok.status_code == 200 def test_concurrent_requests_merge(client): with concurrent.futures.ThreadPoolExecutor(8) as ex: rs = list(ex.map(lambda i: client.post("/v1/systemone", json={"state": f"state {i}", "questions": Q}), range(16))) assert all(r.status_code == 200 for r in rs) st = client.get("/info").json()["batcher"] assert st["items"] >= 16 def test_config_parser(): from tt_laya import config as C c = C.resolve_config({}) assert (c.profile, c.engine, c.max_len, c.max_batch) == ("english", "mk", 512, 32) c = C.resolve_config({"LAYA_PROFILE": "multilingual"}) assert c.max_len == 1024 and 1024 in c.seq_buckets for bad in ({"LAYA_PROFILE": "klingon"}, {"LAYA_ENGINE": "gpu"}, {"LAYA_MAX_LEN": "9000"}, {"LAYA_FIDELITY": "LoFi"}, {"LAYA_MAX_OPTIONS": "128"}, {"LAYA_CALIBRATION": "{not json"}): with pytest.raises(ValueError): C.resolve_config(bad) def test_official_compat(client): """laya-serve behaviour: lone surrogate -> 400, state over 50,000 chars -> 413, max_len below the head budget answered, the batch route's total_usage.""" body = '{"state": "bad \\ud800 text", "questions": {"q": {"type": "noul", "instructions": "i"}}}' r = client.post("/v1/systemone", content=body.encode(), headers={"Content-Type": "application/json"}) assert r.status_code == 400 and "surrogate" in r.json()["detail"] body = '{"state": "ok", "questions": {"q": {"type": "noul", "instructions": "i \\udc00"}}}' assert client.post("/predict", content=body.encode(), headers={"Content-Type": "application/json"}).status_code == 400 assert client.post("/v1/systemone", json={"state": "pair \U0001F600 ok", "questions": Q}).status_code == 200 assert client.post("/v1/systemone", json={"state": "x" * 50000, "questions": Q}).status_code == 200 r = client.post("/v1/systemone", json={"state": "x" * 50001, "questions": Q}) assert r.status_code == 413 and "50001 > 50000" in r.json()["detail"] r = client.post("/v1/systemone/batch", json={"states": ["a", {"body": "y" * 50000}], "questions": Q}) assert r.status_code == 413 # the dict serializes to more than 50,000 characters r = client.post("/v1/systemone", json={"state": "a short ticket", "questions": Q, "max_len": 96}) assert r.status_code == 200, r.text # below the default head budget (192), as officially for bad in (0, -5, True, 1.5): assert client.post("/v1/systemone", json={"state": "x", "questions": Q, "max_len": bad}).status_code == 422 r = client.post("/v1/systemone/batch", json={"states": ["a", "b"], "questions": Q}) assert r.status_code == 200 and r.json()["total_usage"]["input_tokens"] == r.json()["usage"]["input_tokens"] > 0 def test_state_cap_knob(monkeypatch): from fastapi.testclient import TestClient from tt_laya.api import Laya from tt_laya.server.app import create_app monkeypatch.setenv("LAYA_MAX_STATE_CHARS", "0") app = create_app(lambda cfg: Laya.from_pretrained(config=cfg, backend="fake")) with TestClient(app) as c: assert c.post("/v1/systemone", json={"state": "x" * 60000, "questions": Q}).status_code == 200 def test_device_opened_and_closed_off_the_device_thread(monkeypatch): """The default factory path: the chip is opened and closed on the lifespan's thread (the main thread under uvicorn), the model is built and run on the device thread. UMD's per-chip lock must be released by the thread that took it, and tt-metal releases it at exit on the main thread (a chip opened on the device thread aborted every container stop).""" import threading from fastapi.testclient import TestClient from tt_laya import device as D from tt_laya.api import Laya from tt_laya.server import app as A for k in list(os.environ): if k.startswith("LAYA_"): monkeypatch.delenv(k, raising=False) monkeypatch.delenv("TT_MESH_SHAPE", raising=False) seen = {"run": set()} def fake_open(**kw): seen["open"] = threading.get_ident() return "chip" def fake_close(dev): seen["close"] = (threading.get_ident(), dev) def fake_factory(cfg, device=None): seen["build"] = (threading.get_ident(), device) m = Laya.from_pretrained(config=cfg, backend="fake") inner = m.infer def infer(rows): seen["run"].add(threading.get_ident()) return inner(rows) m.infer = infer return m monkeypatch.setattr(D, "open_device", fake_open) monkeypatch.setattr(D, "close_device", fake_close) monkeypatch.setattr(A, "default_model_factory", fake_factory) app = A.create_app() with TestClient(app) as c: assert c.get("/health").json()["status"] == "ok" assert c.post("/v1/systemone", json={"state": "x", "questions": Q}).status_code == 200 assert seen["build"][1] == "chip" and seen["close"][1] == "chip" assert seen["open"] == seen["close"][0] # the same thread opens and closes the chip assert seen["build"][0] != seen["open"] # the model is built on the device thread assert seen["run"] == {seen["build"][0]} # ... and runs there assert app.state.laya.device is None and not app.state.laya.batcher.alive