File size: 9,887 Bytes
f882f26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# 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