File size: 27,810 Bytes
c60a316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's GLM-OCR bundle (tt_glmocr/tests/test_host_server.py, Apache-2.0).
"""Host tests of the HTTP server on the fake backend (no device, no weights): routes, SSE, errors, the queue, the
main-thread open / close of the chip (a fake chip), and the stdlib client + smoke test against a live uvicorn:

    TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_dsocr/tests/test_host_server.py
"""

from __future__ import annotations

import base64
import io
import json
import os
import socket
import subprocess
import sys
import threading
import time
from dataclasses import replace

import numpy as np
import pytest

pytest.importorskip("fastapi")
CODE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, CODE)

from tt_dsocr import config as C  # noqa: E402
from tt_dsocr import postprocess as PP  # noqa: E402
from tt_dsocr.backends import FakeBackend  # noqa: E402

SAMPLES = os.path.join(CODE, "tt_dsocr", "samples")
LINE_PNG = open(os.path.join(SAMPLES, "line_en", "sample.png"), "rb").read()
DATA_URL = "data:image/png;base64," + base64.b64encode(LINE_PNG).decode()
FAKE = {"DSOCR_BACKEND": "fake"}


def _app(env=None, factory=None):
    from tt_dsocr.server.app import create_app

    app = create_app(model_factory=factory)
    app.state.dsocr.config_loader = lambda: C.resolve_config(dict(FAKE, **(env or {})))
    return app


@pytest.fixture(scope="module")
def client():
    from fastapi.testclient import TestClient

    with TestClient(_app()) as c:
        yield c


def _chat(text=None, image=DATA_URL, **kw):
    content = []
    if image is not None:
        content.append({"type": "image_url", "image_url": {"url": image}})
    if text is not None:
        content.append({"type": "text", "text": text})
    return dict({"model": "deepseek-ocr", "messages": [{"role": "user", "content": content}]}, **kw)


def _sse(r):
    lines = [ln for ln in r.iter_lines() if ln.startswith("data: ")]
    assert lines[-1] == "data: [DONE]", lines[-3:]
    return [json.loads(ln[6:]) for ln in lines[:-1]]


def test_import_has_no_heavy_side_effects():
    code = ("import sys, tt_dsocr.server.app as a; assert a.app; "
            "heavy = sorted(m for m in sys.modules if m.split('.')[0] in ('torch', 'ttnn', 'numpy', 'PIL')); "
            "assert not heavy, heavy")
    env = dict(os.environ, PYTHONPATH=os.pathsep.join([CODE] + [p for p in sys.path if p]))
    subprocess.check_call([sys.executable, "-c", code], env=env)


def test_health_info_models(client):
    r = client.get("/health")
    assert r.status_code == 200 and r.json()["status"] == "ok" and r.json()["backend"] == "fake"
    assert client.get("/v1/health").status_code == 200
    i = client.get("/info").json()
    assert i["model"] == "deepseek-ocr" and i["variant"] == "deepseek-ocr" and i["backend"] == "fake"
    assert i["weights"]["repo"] == "deepseek-ai/DeepSeek-OCR" and i["weights"]["license"] == "MIT"
    assert i["code_license"] == "Apache-2.0" and i["package"] == "changh95/DeepSeek-OCR"
    assert i["configuration"]["DSOCR_MODES"] == "tiny,small,base,large,gundam"
    assert i["limits"]["max_new_tokens"] == 8192 and i["buckets"]["prefill_rows"][-1] == 1792
    assert i["defaults"]["temperature"] == 0.0 and i["default_mode"] == "gundam" and "model card" in i["performance"]
    assert client.get("/v1/models").json()["data"][0]["id"] == "deepseek-ocr"
    assert "POST /ocr" in client.get("/").json()["routes"]


# ---------------------------------------------------------------------------------------------- chat
def test_chat_completion(client):
    r = client.post("/v1/chat/completions", json=_chat())
    assert r.status_code == 200, r.text
    j = r.json()
    assert j["object"] == "chat.completion" and j["id"].startswith("chatcmpl-") and j["model"] == "deepseek-ocr"
    ch = j["choices"][0]
    assert ch["message"] == {"role": "assistant", "content": FakeBackend.MARKDOWN} and ch["finish_reason"] == "stop"
    u = j["usage"]
    assert u["prompt_tokens_details"]["image_tokens"] == 1183
    assert u["total_tokens"] == u["prompt_tokens"] + u["completion_tokens"]
    assert j["image"]["grid"] == [9, 1] and "total_ms" in j["timings"] and len(j["refs"]) == 4
    assert client.get("/info").json()["last_request"]["usage"] == {
        "prompt_tokens": u["prompt_tokens"], "image_tokens": 1183, "completion_tokens": u["completion_tokens"],
        "total_tokens": u["total_tokens"]}


def test_chat_prompt_task_mode(client):
    j = client.post("/v1/chat/completions", json=_chat("Free OCR.", mode="tiny")).json()
    assert j["choices"][0]["message"]["content"] == FakeBackend.TEXT and j["image"]["image_tokens"] == 73
    j = client.post("/v1/chat/completions", json=_chat("<image>\nParse the figure.")).json()
    assert j["choices"][0]["message"]["content"] == FakeBackend.FIGURE
    j = client.post("/v1/chat/completions", json=_chat("What is written?")).json()
    assert j["choices"][0]["message"]["content"] == "Fake reply to: What is written?"
    j = client.post("/v1/chat/completions", json=_chat(task="locate", ref="the date")).json()
    assert j["choices"][0]["message"]["content"].startswith("<|ref|>the date<|/ref|><|det|>")
    raw = client.post("/v1/chat/completions", json=_chat("Free OCR.", image=base64.b64encode(LINE_PNG).decode()))
    assert raw.json()["choices"][0]["message"]["content"] == FakeBackend.TEXT
    body = {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": DATA_URL}]}],
            "ngram_preset": "vllm", "max_crops": 3}
    j = client.post("/v1/chat/completions", json=body).json()
    assert j["image"]["grid"] == [3, 1]


def test_chat_max_tokens(client):
    j = client.post("/v1/chat/completions", json=_chat("Free OCR.", max_tokens=5)).json()
    assert j["choices"][0]["finish_reason"] == "length" and j["choices"][0]["message"]["content"] == "Fake "
    j = client.post("/v1/chat/completions", json=_chat("Free OCR.", max_completion_tokens=4, max_tokens=100)).json()
    assert j["usage"]["completion_tokens"] == 4


def test_chat_stream(client):
    with client.stream("POST", "/v1/chat/completions",
                       json=_chat("Free OCR.", stream=True, stream_options={"include_usage": True})) as r:
        assert r.status_code == 200 and r.headers["content-type"].startswith("text/event-stream")
        chunks = _sse(r)
    assert all(c["object"] == "chat.completion.chunk" for c in chunks)
    assert chunks[0]["choices"][0]["delta"] == {"role": "assistant", "content": ""}
    content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks if c["choices"])
    assert content == FakeBackend.TEXT
    fin = [c for c in chunks if c["choices"] and c["choices"][0]["finish_reason"]]
    assert len(fin) == 1 and fin[0]["choices"][0]["finish_reason"] == "stop"
    assert chunks[-1]["choices"] == [] and chunks[-1]["usage"]["completion_tokens"] > 0
    assert len({c["id"] for c in chunks}) == 1


@pytest.mark.parametrize("extra,status", [
    ({"n": 2}, 400), ({"stop": ["\n"]}, 400), ({"logprobs": True}, 400), ({"presence_penalty": 0.5}, 400),
    ({"tools": [{"type": "function"}]}, 400), ({"response_format": {"type": "json_object"}}, 400),
    ({"temperature": 5}, 400), ({"top_k": 100}, 400), ({"max_tokens": 0}, 400), ({"seed": "abc"}, 400),
    ({"mode": "huge"}, 400), ({"max_crops": 10}, 400), ({"no_repeat_ngram_size": 1}, 400),
    ({"ngram_whitelist": [-1]}, 400), ({"task": "locate"}, 400), ({"task": "bogus"}, 400)])
def test_chat_refusals(client, extra, status):
    r = client.post("/v1/chat/completions", json=_chat(**extra))
    assert r.status_code == status, r.text
    j = r.json()
    assert j["detail"] and j["error"]["code"] == status and j["error"]["type"] == "invalid_request_error"


def test_chat_bad_messages(client):
    two = {"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": DATA_URL}},
                                                     {"type": "image_url", "image_url": {"url": DATA_URL}}]}]}
    for body in (two, {"messages": "hi"}, {"messages": [{"role": "system", "content": "x"}]}, {},
                 _chat(image=None, text="Free OCR."), _chat(image="data:image/png;base64,!!!"),
                 _chat(image="http://example.com/a.png"), _chat(image="/etc/hostname"),
                 _chat(image=base64.b64encode(b"not an image").decode())):
        r = client.post("/v1/chat/completions", json=body)
        assert r.status_code == 400, (body, r.text)
    r = client.post("/v1/chat/completions", content=b"{not json", headers={"content-type": "application/json"})
    assert r.status_code == 422
    assert client.post("/v1/chat/completions", json=[1, 2]).status_code == 422
    # ignored OpenAI fields
    assert client.post("/v1/chat/completions", json=_chat(user="u1", metadata={"a": 1}, n=1, stop=None,
                                                          presence_penalty=0)).status_code == 200


# ---------------------------------------------------------------------------------------------- /ocr
def test_ocr_multipart(client):
    r = client.post("/ocr", files={"file": ("a.png", LINE_PNG, "image/png")})
    assert r.status_code == 200, r.text
    j = r.json()
    assert j["model"] == "deepseek-ocr" and j["task"] == "markdown" and j["format"] == "markdown"
    assert j["mode"] == "gundam" and j["text"] == PP.to_markdown(FakeBackend.MARKDOWN)
    assert j["raw_text"] == FakeBackend.MARKDOWN and len(j["refs"]) == 4 and j["json"] is None
    assert j["finish_reason"] == "stop" and j["usage"]["image_tokens"] == 1183 and j["image"]["width"] == 709
    r = client.post("/ocr", files={"file": ("a.png", LINE_PNG)}, data={"task": "free", "mode": "tiny"})
    assert r.json()["text"] == FakeBackend.TEXT and r.json()["image"]["image_tokens"] == 73
    r = client.post("/ocr", files={"image": ("a.png", LINE_PNG)},
                    data={"task": "locate", "ref": "the date", "temperature": "0", "max_new_tokens": "200",
                          "seed": "", "ngram_preset": "vllm", "ngram_whitelist": "1,2", "max_crops": "2"})
    j = r.json()
    assert r.status_code == 200 and j["format"] == "json" and j["json"]["refs"][0]["label"] == "the date"
    assert j["sampling"]["ngram_whitelist"] == [1, 2] and j["sampling"]["no_repeat_ngram_size"] == 30
    assert json.loads(j["text"]) == j["json"] and j["image"]["grid"] == [2, 1]


def test_ocr_json_and_raw_body(client):
    body = {"image": DATA_URL, "task": "ocr", "format": "json", "max_tokens": 300,
            "ngram_whitelist": [128821, 128822], "no_repeat_ngram_size": 0}
    j = client.post("/ocr", json=body).json()
    assert j["json"]["text"] == FakeBackend.TEXT and j["sampling"]["no_repeat_ngram_size"] == 0
    j = client.post("/ocr", json={"image": base64.b64encode(LINE_PNG).decode(), "task": "describe"}).json()
    assert j["text"] == FakeBackend.DESCRIBE
    r = client.post("/ocr?task=free&mode=small", content=LINE_PNG, headers={"content-type": "image/png"})
    assert r.status_code == 200 and r.json()["text"] == FakeBackend.TEXT and r.json()["mode"] == "small"
    r = client.post("/ocr?max_new_tokens=3&task=free", content=LINE_PNG,
                    headers={"content-type": "application/octet-stream"})
    assert r.json()["finish_reason"] == "length" and r.json()["raw_text"] == "Fak"


def test_ocr_stream(client):
    with client.stream("POST", "/ocr", files={"file": ("a.png", LINE_PNG)},
                       data={"stream": "true", "task": "free"}) as r:
        assert r.status_code == 200
        evs = _sse(r)
    deltas = [e["text"] for e in evs if e["type"] == "delta"]
    done = evs[-1]
    assert done["type"] == "done" and "".join(deltas) == done["raw_text"] == FakeBackend.TEXT
    assert "🙂" in deltas and all("�" not in d for d in deltas)
    assert done["usage"]["completion_tokens"] == len(done["raw_text"].encode()) + 1


@pytest.mark.parametrize("kind,payload,status", [
    ("form", {"bogus": "1"}, 400), ("form", {"task": "ocr2"}, 400), ("form", {"format": "xml"}, 400),
    ("form", {"mode": "huge"}, 400), ("form", {"max_crops": "99"}, 400), ("form", {"min_crops": "0"}, 400),
    ("form", {"max_new_tokens": "0"}, 400), ("form", {"max_new_tokens": "5", "max_tokens": "5"}, 400),
    ("form", {"temperature": "x"}, 400), ("form", {"stream": "perhaps"}, 400), ("form", {"task": "locate"}, 400),
    ("form", {"no_repeat_ngram_size": "1"}, 400), ("form", {"ngram_window": "-3"}, 400),
    ("form", {"ngram_preset": "gpu"}, 400), ("form", {"ngram_whitelist": "[1,"}, 400),
    ("form", {"prompt": "<image><image>"}, 400), ("json", {"task": "free"}, 400),
    ("json", {"image": "@@@"}, 400), ("json", {"image": DATA_URL, "top_k": 65}, 400),
    ("json", {"image": DATA_URL, "top_k": True}, 400), ("json", {"image": DATA_URL, "ref": 3}, 400)])
def test_ocr_refusals(client, kind, payload, status):
    if kind == "form":
        r = client.post("/ocr", files={"file": ("a.png", LINE_PNG)}, data=payload)
    else:
        r = client.post("/ocr", json=payload)
    assert r.status_code == status, r.text


def test_ocr_bad_bodies(client):
    assert client.post("/ocr", data={"task": "free"}, files={"other": ("x.txt", b"x")}).status_code == 400
    assert client.post("/ocr", files={"file": ("a.png", b"")}).status_code == 400
    assert client.post("/ocr", files={"file": ("a.png", b"not an image")}).status_code == 400
    assert client.post("/ocr", files={"file": ("a.png", LINE_PNG)}, data={"image": DATA_URL}).status_code == 400
    assert client.post("/ocr", content=b"hello", headers={"content-type": "text/plain"}).status_code == 415
    assert client.post("/ocr", content=b"{", headers={"content-type": "application/json"}).status_code == 422
    r = client.post("/ocr", content=b"--x\r\n", headers={"content-type": "multipart/form-data; boundary=zz"})
    assert r.status_code in (400, 422)
    assert client.post("/ocr", content=b"", headers={"content-type": "image/png"}).status_code == 400
    b = "xyzBOUNDARY"                                                    # multipart without a file: image as text
    body = "".join(f"--{b}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n{v}\r\n"
                   for k, v in (("image", DATA_URL), ("task", "free"))) + f"--{b}--\r\n"
    r = client.post("/ocr", content=body.encode(), headers={"content-type": f"multipart/form-data; boundary={b}"})
    assert r.status_code == 200 and r.json()["text"] == FakeBackend.TEXT
    assert client.post("/ocr", data={"image": DATA_URL}).status_code == 415          # url-encoded forms: no


def test_size_limits():
    from fastapi.testclient import TestClient

    with TestClient(_app({"DSOCR_MAX_BODY_MB": "1", "DSOCR_MAX_INPUT_MEGAPIXELS": "0.5"})) as c:
        r = c.post("/ocr", content=b"\0" * (2 << 20), headers={"content-type": "image/png"})
        assert r.status_code == 413 and r.json()["error"]["code"] == 413
        from PIL import Image

        b = io.BytesIO()
        Image.fromarray(np.full((800, 800, 3), 255, np.uint8)).save(b, format="PNG")
        r = c.post("/ocr", files={"file": ("big.png", b.getvalue())})
        assert r.status_code == 413 and "MEGAPIXELS" in r.json()["detail"]


def test_disabled_mode_and_small_config():
    from fastapi.testclient import TestClient

    with TestClient(_app({"DSOCR_MODES": "tiny,base", "DSOCR_MAX_CONTEXT": "2048"})) as c:
        i = c.get("/info").json()
        assert list(i["modes"]) == ["tiny", "base"] and i["default_mode"] == "tiny"   # the first enabled
        r = c.post("/ocr", files={"file": ("a.png", LINE_PNG)}, data={"mode": "gundam"})
        assert r.status_code == 400 and "DSOCR_MODES" in r.json()["detail"]
        assert c.post("/ocr", files={"file": ("a.png", LINE_PNG)}).json()["mode"] == "tiny"


def test_queue_full_and_timeouts():
    from fastapi.testclient import TestClient

    with TestClient(_app({"DSOCR_QUEUE_DEPTH": "0"})) as c:
        st = c.app.state.dsocr
        gate, started = threading.Event(), threading.Event()
        st.worker.submit(lambda j: (started.set(), gate.wait(30)), kind="block")
        assert started.wait(10)
        r = c.post("/ocr", files={"file": ("a.png", LINE_PNG)})
        assert r.status_code == 429 and r.headers["retry-after"] == "2"
        assert c.get("/health").json()["queue"]["running"] == "block"
        gate.set()
        time.sleep(0.2)
        assert c.post("/ocr", files={"file": ("a.png", LINE_PNG)}).status_code == 200


def test_not_ready_is_503():
    from fastapi.testclient import TestClient

    c = TestClient(_app())  # no lifespan: the model is never built
    r = c.get("/health")
    assert r.status_code == 503 and r.json()["status"] == "starting"
    assert c.post("/ocr", files={"file": ("a.png", LINE_PNG)}).status_code == 503
    assert c.post("/v1/chat/completions", json=_chat()).status_code == 503
    assert c.get("/info").json()["status"] == "starting"


def test_startup_failure_refuses_to_start():
    from fastapi.testclient import TestClient

    from tt_dsocr.server.app import create_app, load_config

    app = create_app()
    app.state.dsocr.config_loader = lambda: load_config({"DSOCR_MAX_CROPS": "1"})
    with pytest.raises(RuntimeError, match="DSOCR_MAX_CROPS"):
        with TestClient(app):
            pass
    assert app.state.dsocr.error and not app.state.dsocr.ready


# ---------------------------------------------------------------------------------------------- the chip's thread
def _patch_chip(monkeypatch, seen, fail_build=False):
    from tt_dsocr.ttaw import device as D
    from tt_dsocr.api import DeepSeekOcr
    from tt_dsocr.server import app as A

    def fake_open(device_id=0, **kw):
        seen["open"] = (threading.get_ident(), device_id, kw.get("dispatch"), kw.get("trace_region_size"),
                        kw.get("l1_small_size"))
        seen.setdefault("order", []).append("open")
        return "chip"

    def fake_close(dev):
        seen["close"] = (threading.get_ident(), dev)
        seen.setdefault("order", []).append("close")

    def fake_factory(cfg, device=None):
        seen["build"] = (threading.get_ident(), device, cfg.backend)
        if fail_build:
            raise RuntimeError("engine build failed")
        m = DeepSeekOcr.from_config(replace(cfg, backend="fake"))
        orig = m.close

        def close():
            seen.setdefault("order", []).append("model.close")
            seen["model_close"] = threading.get_ident()
            orig()

        m.close = close
        return m

    monkeypatch.setattr(D, "open_device", fake_open)
    monkeypatch.setattr(D, "close_device", fake_close)
    monkeypatch.setattr(A, "default_model_factory", fake_factory)


def test_chip_opened_and_closed_on_the_main_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, run and released 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."""
    from fastapi.testclient import TestClient

    from tt_dsocr.server import app as A

    seen = {}
    _patch_chip(monkeypatch, seen)
    app = A.create_app()
    app.state.dsocr.config_loader = lambda: C.resolve_config({"DSOCR_BACKEND": "device", "TT_DEVICE_ID": "0"})
    with TestClient(app) as c:
        assert c.get("/health").json()["status"] == "ok"
        r = c.post("/ocr", files={"file": ("a.png", LINE_PNG)}, data={"task": "free"})
        assert r.json()["text"] == FakeBackend.TEXT
    assert seen["open"][1:] == (0, "eth", 1024 << 20, C.L1_SMALL_SIZE) and seen["build"][1:] == ("chip", "device")
    assert seen["close"][1] == "chip"
    assert seen["open"][0] == seen["close"][0]               # the same thread opens and closes the chip
    assert seen["build"][0] != seen["open"][0]               # the model is built on the device thread
    assert seen["model_close"] == seen["build"][0]           # and released there, before the chip closes
    assert seen["order"] == ["open", "model.close", "close"]


def test_chip_closed_when_the_build_fails(monkeypatch):
    from fastapi.testclient import TestClient

    from tt_dsocr.server import app as A

    seen = {}
    _patch_chip(monkeypatch, seen, fail_build=True)
    app = A.create_app()
    app.state.dsocr.config_loader = lambda: C.resolve_config({"DSOCR_BACKEND": "device"})
    with pytest.raises(RuntimeError, match="engine build failed"):
        with TestClient(app):
            pass
    assert seen["order"] == ["open", "close"] and seen["open"][0] == seen["close"][0]
    assert "engine build failed" in app.state.dsocr.error


# ---------------------------------------------------------------------------------------------- live server
def _free_port() -> int:
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    p = s.getsockname()[1]
    s.close()
    return p


def _bundle_variant() -> str:
    """The variant of the bundle this checkout belongs to (its tt-model.yaml pins DSOCR_VARIANT), else the default."""
    import re

    y = os.path.join(os.path.dirname(CODE), "tt-model.yaml")
    if os.path.isfile(y):
        m = re.search(r'^\s*DSOCR_VARIANT:\s*"?([\w-]+)"?', open(y).read(), re.M)
        if m:
            return m.group(1)
    return C.DEFAULT_VARIANT


@pytest.mark.parametrize("variant", sorted(C.VARIANTS))
def test_client_and_smoke_test_against_a_live_server(monkeypatch, tmp_path, variant):
    import uvicorn

    from tt_dsocr.server.app import create_app

    for k in list(os.environ):
        if k.startswith("DSOCR_") or k == "TT_MESH_SHAPE":
            monkeypatch.delenv(k, raising=False)
    monkeypatch.setenv("DSOCR_BACKEND", "fake")
    monkeypatch.setenv("DSOCR_VARIANT", variant)
    port = _free_port()
    server = uvicorn.Server(uvicorn.Config(create_app(), host="127.0.0.1", port=port, log_level="warning",
                                           lifespan="on"))
    th = threading.Thread(target=server.run, daemon=True)
    th.start()
    try:
        t0 = time.time()
        while not server.started:
            assert time.time() - t0 < 60 and th.is_alive(), "uvicorn did not start"
            time.sleep(0.05)
        url = f"http://127.0.0.1:{port}"
        out = tmp_path / "smoke.json"
        p = subprocess.run([sys.executable, os.path.join(CODE, "tt_dsocr", "server", "smoke_test.py"), "--url", url,
                            "--wait", "30", "--allow-fake", "--out", str(out)], capture_output=True, text=True,
                           timeout=600)
        assert p.returncode == 0 and p.stdout.startswith("PASS"), p.stdout + p.stderr
        m = json.loads(out.read_text())
        assert m["fails"] == [] and m["variant"] == variant
        formula = os.path.join(SAMPLES, "formula_quad", "sample.png")
        line = os.path.join(SAMPLES, "line_en", "sample.png")
        table = os.path.join(SAMPLES, "table_sales", "sample.png")
        client = os.path.join(CODE, "tt_dsocr", "server", "client.py")
        if variant == "unlimited-ocr-2":
            assert m["multipage_text"].count("<PAGE>") == 2 and m["multipage_image"]["n_pages"] == 2
            p = subprocess.run([sys.executable, client, table, formula, "--url", url, "--format", "json"],
                               capture_output=True, text=True, timeout=120)
            assert p.returncode == 0 and "<!-- page 2 -->" in p.stdout and "<PAGE>" not in p.stdout, p.stdout + p.stderr
            p = subprocess.run([sys.executable, client, formula, "--url", url, "--chat", "--stream"],
                               capture_output=True, text=True, timeout=120)
            assert p.returncode == 0 and p.stdout.strip() == FakeBackend.PAGE.format(n=1), p.stdout + p.stderr
        elif variant == "schift-ocr-1-beta":
            ko = os.path.join(SAMPLES, "ko_table", "sample.png")
            p = subprocess.run([sys.executable, client, ko, "--url", url], capture_output=True, text=True, timeout=120)
            assert p.returncode == 0 and "가짜 문서 제목" in p.stdout and "<|det|>" not in p.stdout, p.stdout + p.stderr
            p = subprocess.run([sys.executable, client, ko, "--url", url, "--chat", "--stream"],
                               capture_output=True, text=True, timeout=120)
            assert p.returncode == 0 and p.stdout.strip() == FakeBackend.DET.strip(), p.stdout + p.stderr
            p = subprocess.run([sys.executable, client, ko, line, "--url", url], capture_output=True, text=True,
                               timeout=120)
            assert p.returncode == 1 and "400" in p.stdout, p.stdout + p.stderr     # one image per request
        else:
            if variant == "deepseek-ocr":
                assert m["locate"]["refs"][0]["label"] == "the text"
            p = subprocess.run([sys.executable, client, formula, "--url", url, "--task", "free",
                                "--mode", "small" if variant == "deepseek-ocr-2" else "tiny"],
                               capture_output=True, text=True, timeout=120)
            assert p.returncode == 0 and p.stdout.strip() == FakeBackend.TEXT, p.stdout + p.stderr
            p = subprocess.run([sys.executable, client, formula, "--url", url, "--chat", "--stream",
                                "--prompt", "Free OCR."], capture_output=True, text=True, timeout=120)
            assert p.returncode == 0 and p.stdout.strip() == FakeBackend.TEXT, p.stdout + p.stderr
            p = subprocess.run([sys.executable, client, formula, line, "--url", url], capture_output=True, text=True,
                               timeout=120)
            assert p.returncode == 1 and "400" in p.stdout, p.stdout + p.stderr     # one image per request
        if variant != _bundle_variant():
            return
        examples = os.path.join(os.path.dirname(CODE), "examples")   # the bundle root's examples/
        quick = os.path.join(examples, "quickstart.py")
        if os.path.isfile(quick):
            if variant == "unlimited-ocr-2":
                args, want = [table, formula, "--url", url], FakeBackend.PAGE.format(n=2)
            elif variant == "schift-ocr-1-beta":
                args, want = [os.path.join(SAMPLES, "ko_table", "sample.png"), "--url", url], FakeBackend.DET
            else:
                args, want = [line, url, "free"], FakeBackend.TEXT
            p = subprocess.run([sys.executable, quick] + args, capture_output=True, text=True, timeout=120)
            assert p.returncode == 0 and want in p.stdout, p.stdout + p.stderr
        boxes = os.path.join(examples, "locate.py")
        if os.path.isfile(boxes):
            p = subprocess.run([sys.executable, boxes, line, "the date", url], capture_output=True, text=True,
                               timeout=120)
            assert p.returncode == 0 and "the date" in p.stdout, p.stdout + p.stderr
    finally:
        server.should_exit = True
        th.join(30)


def test_lone_surrogate_text_is_400(client):
    """A prompt with an unpaired surrogate (valid JSON "\\ud800") is a 400 on both routes, the server stays healthy."""
    body = '{"model": "deepseek-ocr", "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": ' \
           '{"url": "' + DATA_URL + '"}}, {"type": "text", "text": "read \\ud800 this"}]}]}'
    r = client.post("/v1/chat/completions", content=body, headers={"Content-Type": "application/json"})
    assert r.status_code == 400 and "surrogate" in r.text, r.text
    body = '{"image": "' + DATA_URL + '", "prompt": "x\\udfff"}'
    r = client.post("/ocr", content=body, headers={"Content-Type": "application/json"})
    assert r.status_code == 400 and "surrogate" in r.text, r.text
    assert client.get("/health").status_code == 200