Files
alzeo/tests/test_ocr_server.py
Hasan BasbunarandClaude Opus 5.5 eaf06fbb67 tests: test_ocr_server takes its front's port from localports.spawn
The three SIGTERM tests bound a socket, read its port and closed it before starting
ocr-server.py on it, so another program of the machine could be handed that number
meanwhile; spawn starts the front on port 0 and reads the port back from /proc once it
listens, as the suite's rule asks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 00:00:25 +01:00

1225 lines
63 KiB
Python

#!/usr/bin/env python3
"""The OCR lane's front (ocr-server.py), its engine and its drawing container replaced by stand-ins: what /v1/ocr takes in
Mistral's shapes (JSON with a data: URL, a multipart form as LiteLLM's proxy sends it), what it refuses and in which words, what a
page becomes (Markdown, tables, header and footer, blocks in pixels), the pages streamed as they are read, a client that
leaves, two documents at a time at most (a third is a 429 with a Retry-After, and the slot is given back however the
document ends), and a drawing container that gives nothing, stopped after a delay. The drawing of real files is proved on
a box (ocr_pages.py in its container); the model's reading too."""
import base64
import http.client
import importlib.util
import json
import os
import pathlib
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
REPO = pathlib.Path(__file__).resolve().parents[1]
_spec = importlib.util.spec_from_file_location("ocr_server", REPO / "ocr-server.py")
S = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(S)
import ocr_models as M # noqa: E402 (the module above puts the repository on the path)
import ocr_pages as P # noqa: E402
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import localports # noqa: E402
PDF = b"%PDF-1.7\n" + bytes(200)
JPEG = b"\xff\xd8\xff\xe0" + bytes(60)
# The drawing container's stand-in: the protocol of ocr_pages.py, pages of a document of 3 (page 1 fails), pictures of no meaning.
DRAWER = r'''
import json, sys, time
ask = json.loads(sys.stdin.buffer.readline())
data = sys.stdin.buffer.read()
out = sys.stdout.buffer
def say(o, *b):
out.write(json.dumps(o).encode() + b"\n"); [out.write(x) for x in b]; out.flush()
if data.startswith(b"%PDF-1.7\nLOCKED"):
say({"error": "it is locked by a password"}); sys.exit()
if data.startswith(b"%PDF-1.7\nSLOW"):
time.sleep(2.5) # a document whose pages take a while to come
if data.startswith(b"%PDF-1.7\nHANG"):
time.sleep(3600) # one that gives nothing at all, as a page stuck in a call of PDFium
if data.startswith(b"%PDF-1.7\nNOISY-EXIT"):
for i in range(600): # more than a pipe holds (64 KiB) of warnings, then it ends without a page
sys.stderr.write(f"warning {i} " + "x" * 200 + "\n")
sys.stderr.write("THE-LAST-WARNING-9182\n")
sys.stderr.flush()
sys.exit(1)
if data.startswith(b"%PDF-1.7\nNOISY"):
for i in range(600): # the same noise, then the document's pages as usual
sys.stderr.write(f"warning {i} " + "x" * 200 + "\n")
sys.stderr.flush()
if data.startswith(b"%PDF-1.7\nMANY"):
pages = list(range(30)) # a document of 30 pages, to watch what the front holds back
else:
pages = ask["pages"] if ask["pages"] is not None else [0, 1, 2]
pages = [p for p in pages if 0 <= p < 3]
if not pages:
say({"error": "it has 3 pages, and none of those asked"}); sys.exit()
for p in pages:
if p == 1:
say({"page": 1, "of": 3, "error": "this page did not draw in 30 s"}); continue
r, v = b"\xff\xd8\xff" + bytes([p]) * 40, b"\xff\xd8\xff" + bytes(10)
say({"page": p, "of": 3, "width": 1000, "height": 2000, "dpi": 200, "read": len(r), "view": len(v)}, r, v)
say({"end": True})
'''
# The drawing container's stand-in for the SIGTERM tests: it draws the pages (so the engine's reads start),
# writes its pid, then sleeps: the container stays alive until the front ends it.
DRAWER_HOLD = r'''
import json, os, sys, time
open(os.environ["DRAWER_PID"], "w").write(str(os.getpid()))
ask = json.loads(sys.stdin.buffer.readline())
data = sys.stdin.buffer.read()
out = sys.stdout.buffer
pages = ask["pages"] if ask["pages"] is not None else [0, 1, 2]
pages = [p for p in pages if 0 <= p < 3]
for p in pages:
if p == 1:
out.write(json.dumps({"page": 1, "of": 3, "error": "this page did not draw in 30 s"}).encode() + b"\n")
else:
r, v = b"\xff\xd8\xff" + bytes([p]) * 40, b"\xff\xd8\xff" + bytes(10)
out.write(json.dumps({"page": p, "of": 3, "width": 1000, "height": 2000, "dpi": 200, "read": len(r), "view": len(v)}).encode()
+ b"\n" + r + v)
out.flush()
time.sleep(3600)
'''
class Engine(BaseHTTPRequestHandler):
"""The engine's stand-in: a page in blocks, JSON cut short for the third (as a model at its length), plain text otherwise."""
protocol_version = "HTTP/1.1"
seen, slow = [], 0.0
fail, hold = set(), None # pages it refuses with a 500, and an Event that holds every page back
def log_message(self, *a):
pass
def do_GET(self):
self.reply(200, {"status": "ok"})
def do_POST(self):
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
Engine.seen.append(req)
content = req["messages"][0]["content"]
picture = base64.b64decode(content[0]["image_url"]["url"].split(",", 1)[1])
page = picture[3] if len(picture) > 3 else 0
if Engine.hold is not None:
Engine.hold.wait(30)
time.sleep(Engine.slow)
if page in Engine.fail:
self.reply(500, {"error": {"message": "the engine is on fire"}})
return
text, finish = "plain text of the page", "stop"
if len(content) > 1 and "JSON array" in content[1]["text"]:
blocks = [{"bbox": [100, 50, 900, 90], "category": "doc_title", "content": "Invoice"},
{"bbox": [0, 0, 999, 30], "category": "header", "content": "ACME, page head"},
{"bbox": [100, 150, 950, 400], "category": "table", "content": "<table><tr><th>Item</th><th>Qty</th></tr><tr><td>Screw</td><td>13</td></tr></table>"},
{"bbox": [100, 420, 300, 500], "category": "image", "content": "<img src=\"images/bbox_100_420_300_500.jpg\" />"},
{"bbox": [0, 960, 999, 999], "category": "footer", "content": "page foot"}]
text = json.dumps(blocks)
if page == 2:
text, finish = text[:-40], "length"
elif len(content) > 1 and "following keys" in content[1]["text"]:
text = '```json\n{"invoice_number": "F-2026-2576", "total": "1 525,80 €"}\n```'
self.reply(200, {"choices": [{"message": {"content": text}, "finish_reason": finish}], "usage": {"completion_tokens": 7}})
def reply(self, code, obj):
b = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def lane(folder):
eng = ThreadingHTTPServer(("127.0.0.1", 0), Engine)
threading.Thread(target=eng.serve_forever, daemon=True).start()
prompts = pathlib.Path(folder, "prompts")
prompts.mkdir()
for f, text in (("document_structured", "Return a single JSON array in natural reading order."), ("document_markdown", "Markdown, please."),
("plain_ocr", "Read all the text."), ("formula_recognition", "LaTeX."),
("kie_fields", "Extract the values for the following keys from the image: {keys_json}. Output JSON only.")):
(prompts / f"{f}.txt").write_text(text)
drawer = pathlib.Path(folder, "drawer.py")
drawer.write_text(DRAWER)
recipe = M.Ovis(folder)
engine = S.Engine(f"http://127.0.0.1:{eng.server_address[1]}", "ovisocr3", recipe, 4)
front = S.Server(("127.0.0.1", 0), S.make_handler(engine, recipe, [sys.executable, "-I", str(drawer)], "ovisocr3"))
threading.Thread(target=front.serve_forever, daemon=True).start()
return front, eng
class TheLane(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = tempfile.TemporaryDirectory(prefix="ocr-lane-")
cls.front, cls.eng = lane(cls.dir.name)
cls.port = cls.front.server_address[1]
@classmethod
def tearDownClass(cls):
for srv in (cls.front, cls.eng):
srv.shutdown()
srv.server_close()
cls.dir.cleanup()
def post(self, body, ctype="application/json"):
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=60)
c.request("POST", "/v1/ocr", body=body if isinstance(body, bytes) else json.dumps(body).encode(), headers={"Content-Type": ctype})
r = c.getresponse()
raw = r.read()
c.close()
return r.status, raw
def doc(self, data=PDF, **more):
return {"model": "ovisocr3", "document": {"type": "document_url", "document_url": "data:application/pdf;base64," + base64.b64encode(data).decode()}, **more}
def test_a_document_in_mistrals_shape(self):
s, raw = self.post(self.doc(pages=[0]))
d = json.loads(raw)
self.assertEqual(s, 200, raw)
self.assertEqual(d["model"], "ovisocr3")
self.assertEqual(d["usage_info"], {"pages_processed": 1, "doc_size_bytes": len(PDF)})
page = d["pages"][0]
self.assertEqual(page["index"], 0)
self.assertEqual(page["dimensions"], {"dpi": 200, "height": 2000, "width": 1000})
self.assertTrue(page["markdown"].startswith("# Invoice\n\n"), page["markdown"])
self.assertIn("<table>", page["markdown"]) # inline, as Mistral's API puts a table when no table_format is asked
self.assertIn("![img-0.jpeg](img-0.jpeg)", page["markdown"])
self.assertEqual(page["images"][0]["id"], "img-0.jpeg")
self.assertEqual((page["images"][0]["top_left_x"], page["images"][0]["top_left_y"]), (100, 840))
self.assertIsNone(page["images"][0]["image_base64"])
self.assertEqual([b["type"] for b in page["blocks"]], ["title", "header", "table", "image", "footer"])
self.assertEqual(page["blocks"][0]["bottom_right_y"], 180) # 90 of 1000 on a page 2000 high
def test_tables_header_and_footer_apart(self):
s, raw = self.post(self.doc(pages=[0], table_format="markdown", extract_header=True, extract_footer=True))
page = json.loads(raw)["pages"][0]
self.assertEqual((page["header"], page["footer"]), ("ACME, page head", "page foot"))
self.assertNotIn("page head", page["markdown"])
self.assertEqual(page["tables"], [{"id": "tbl-0.md", "content": "| Item | Qty |\n| --- | --- |\n| Screw | 13 |", "format": "markdown"}])
self.assertIn("[tbl-0.md](tbl-0.md)", page["markdown"])
s, raw = self.post(self.doc(pages=[0], table_format="html"))
self.assertEqual(json.loads(raw)["pages"][0]["tables"][0]["id"], "tbl-0.html")
def test_a_page_that_fails_and_one_cut_short_are_said(self):
s, raw = self.post(self.doc())
d = json.loads(raw)
self.assertEqual(s, 200, raw)
self.assertEqual([p["index"] for p in d["pages"]], [0, 2])
self.assertEqual(d["errors"], [{"index": 1, "error": "this page did not draw in 30 s"}])
self.assertEqual(d["document_pages"], 3)
self.assertTrue(d["pages"][1]["truncated"])
self.assertEqual([b["type"] for b in d["pages"][1]["blocks"]], ["title", "header", "table", "image"]) # the blocks that parse
def test_a_page_the_model_did_not_read_is_named_in_errors_and_not_counted(self):
"""docs/ocr-lane.md: a page that could not be read is named in errors, with its index and why, and the others come back."""
Engine.fail.add(2)
try:
s, raw = self.post(self.doc())
finally:
Engine.fail.clear()
d = json.loads(raw)
self.assertEqual(s, 200, raw)
self.assertEqual([p["index"] for p in d["pages"]], [0], raw) # page 2 did not read: it is not a page
self.assertEqual(d["usage_info"]["pages_processed"], 1, raw)
self.assertEqual([e["index"] for e in d["errors"]], [1, 2], raw) # 1 did not draw, 2 did not read
self.assertIn("the model refused this page (HTTP 500)", d["errors"][1]["error"], raw)
# in a stream the page that could not be read is still sent, with its error, and not counted in the done's usage
Engine.fail.add(2)
try:
s, raw = self.post(self.doc(stream=True))
finally:
Engine.fail.clear()
events = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith("data: ")]
pages = {e["page"]["index"]: e["page"] for e in events if e["type"] == "page"}
self.assertEqual(sorted(pages), [0, 1, 2])
self.assertNotIn("error", pages[0])
self.assertIn("error", pages[2])
self.assertEqual(events[-1]["usage_info"]["pages_processed"], 1, raw)
self.assertEqual([e["index"] for e in events[-1]["errors"]], [1, 2], raw)
def test_the_pages_asked_in_mistrals_two_ways(self):
for pages in ("0,2", [2, 0], "0-2"):
d = json.loads(self.post(self.doc(pages=pages))[1])
self.assertEqual(sorted(p["index"] for p in d["pages"]), [0, 2], pages)
self.assertEqual([p["index"] for p in json.loads(self.post(self.doc(pages=[2, 0]))[1])["pages"]], [2, 0]) # the order asked
def test_the_other_modes(self):
Engine.seen.clear()
page = json.loads(self.post(self.doc(pages=[0], mode="text"))[1])["pages"][0]
self.assertEqual((page["markdown"], "blocks" in page), ("plain text of the page", False))
self.assertEqual(Engine.seen[-1]["messages"][0]["content"][1]["text"], "Read all the text.")
self.assertEqual(Engine.seen[-1]["chat_template_kwargs"], {"enable_thinking": False})
self.assertEqual(Engine.seen[-1]["temperature"], 0.0)
page = json.loads(self.post(self.doc(pages=[0], mode="fields", fields=["invoice_number", "total"]))[1])["pages"][0]
self.assertEqual(page["fields"], {"invoice_number": "F-2026-2576", "total": "1 525,80 €"})
self.assertIn('["invoice_number", "total"]', Engine.seen[-1]["messages"][0]["content"][1]["text"])
def test_a_picture_and_a_form(self):
body = {"document": {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(JPEG).decode()}}, "pages": [0]}
self.assertEqual(self.post(body)[0], 200)
b = "b0undary"
form = (f'--{b}\r\nContent-Disposition: form-data; name="model"\r\n\r\novisocr3\r\n--{b}\r\nContent-Disposition: form-data; name="pages"\r\n\r\n[2]\r\n'
f'--{b}\r\nContent-Disposition: form-data; name="file"; filename="a.pdf"\r\nContent-Type: application/pdf\r\n\r\n').encode() + PDF + f"\r\n--{b}--\r\n".encode()
s, raw = self.post(form, f"multipart/form-data; boundary={b}")
self.assertEqual((s, [p["index"] for p in json.loads(raw)["pages"]]), (200, [2]))
def test_what_it_refuses_and_why(self):
cases = [({"document": {"type": "document_url", "document_url": "https://example.org/a.pdf"}}, 400, "reaches no network"),
({"document": {"type": "file", "file_id": "123"}}, 400, "keeps no files"),
({"document": "x"}, 400, "'document' must be an object"),
(self.doc(b"MZ\x90\0" + bytes(100)), 400, "no PDF, PNG, JPEG, WebP or TIFF"),
(self.doc(b""), 400, "is empty"),
(self.doc(b"%PDF-1.7\nLOCKED"), 400, "locked by a password"),
(self.doc(pages=[7]), 400, "none of those asked"),
(self.doc(pages="2-0"), 400, "backwards"),
(self.doc(pages="all"), 400, "page numbers"),
(self.doc(mode="poetry"), 400, "'mode' is 'poetry'"),
(self.doc(mode="fields"), 400, "takes 'fields'"),
(self.doc(table_format="csv"), 400, "markdown or html"),
(self.doc(document_annotation_format={"type": "json_schema"}), 400, "not read by this lane"),
(self.doc(model="mistral-ocr-latest"), 404, "this lane serves ovisocr3"),
({"model": "ovisocr3", "document": {"type": "document_url", "document_url": "data:application/pdf;base64,@@@"}}, 400, "not valid base64")]
for body, code, words in cases:
s, raw = self.post(body)
self.assertEqual(s, code, (body, raw[:200]))
self.assertIn(words, json.loads(raw)["error"]["message"], body)
self.assertEqual(self.post(b"[1, 2]")[0], 400)
def test_the_pages_streamed_as_they_are_read(self):
s, raw = self.post(self.doc(stream=True, include_page_image=True))
events = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith("data: ")]
kinds = [e["type"] for e in events]
self.assertEqual(s, 200)
self.assertEqual(kinds[-1], "done")
self.assertEqual(sorted(e["index"] for e in events if e["type"] == "drawn"), [0, 2])
self.assertTrue(all(e["image"].startswith("data:image/jpeg;base64,") for e in events if e["type"] == "drawn"))
# a stream that does not ask for the pictures gets none: each is a JPEG of up to 1,400 pixels a side
s, raw = self.post(self.doc(stream=True))
drawn = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith('data: {"type": "drawn"')]
self.assertEqual((s, len(drawn), [e for e in drawn if "image" in e]), (200, 2, []))
pages = {e["page"]["index"]: e["page"] for e in events if e["type"] == "page"}
self.assertEqual(sorted(pages), [0, 1, 2])
self.assertEqual(pages[1]["error"], "this page did not draw in 30 s")
for e in events: # a page is drawn before it is read
if e["type"] == "page" and "error" not in e["page"]:
self.assertLess(kinds.index("drawn"), events.index(e))
self.assertEqual(events[-1]["usage_info"]["pages_processed"], 2)
def test_a_client_that_leaves_ends_its_pages(self):
Engine.slow, Engine.seen[:] = 1.0, []
try:
sock = socket.create_connection(("127.0.0.1", self.port))
body = json.dumps(self.doc(stream=True, pages=[0, 2, 0, 2, 0, 2])).encode()
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(0.4)
sock.close()
time.sleep(3.5)
self.assertLessEqual(len(Engine.seen), 4, "the pages after its client left were still asked")
finally:
Engine.slow = 0.0
def test_two_documents_at_a_time_and_their_slots_given_back(self):
slots = getattr(self.front.RequestHandlerClass, "slots", None)
slow = self.doc(b"%PDF-1.7\nSLOW" + bytes(200))
results = []
def send(body):
results.append(self.post(body))
def wait_busy(target, within=10):
end = time.monotonic() + within
while slots.busy != target and time.monotonic() < end:
time.sleep(0.05)
return slots.busy
t1 = threading.Thread(target=send, args=(slow,))
t2 = threading.Thread(target=send, args=(slow,))
t1.start()
t2.start()
if slots is None:
time.sleep(0.8) # a front with no slots: just let the two documents start
else:
self.assertEqual(wait_busy(2), 2, "two documents are being read, both hold a slot")
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
body = json.dumps(self.doc()).encode()
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
self.assertEqual(r.status, 429, raw)
self.assertEqual(r.getheader("Retry-After"), "15")
d = json.loads(raw)
self.assertEqual(d["error"]["type"], "server_busy_error")
self.assertIn(f"the box reads {S.DOCS} documents at a time", d["error"]["message"], raw)
t1.join()
t2.join()
self.assertEqual([s for s, _ in results], [200, 200], results)
if slots is None:
return
self.assertEqual(wait_busy(0), 0, "the slots were not given back when the documents ended")
# a document that fails gives its slot back too
t3 = threading.Thread(target=send, args=(slow,))
t3.start()
self.assertEqual(wait_busy(1), 1)
s, raw = self.post(self.doc(b"%PDF-1.7\nLOCKED" + bytes(200)))
self.assertEqual(s, 400, raw)
self.assertEqual(wait_busy(1), 1, "the slot of a document that failed was not given back")
t3.join()
self.assertEqual(wait_busy(0), 0)
# a client that left gives its slot back too
t4 = threading.Thread(target=send, args=(slow,))
t4.start()
self.assertEqual(wait_busy(1), 1)
sock = socket.create_connection(("127.0.0.1", self.port))
body = json.dumps(self.doc(b"%PDF-1.7\nSLOW" + bytes(200), stream=True)).encode()
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(0.5)
sock.close()
t4.join(timeout=30)
self.assertEqual(wait_busy(0), 0, "the slot of a client that left was not given back")
def test_a_refusal_reads_the_body_it_refuses_before_answering(self):
"""A 429 answered while the announced body is still unread makes the close send a RST: the proxy fails to
write and answers a 503 "try again", and the 429 with its Retry-After is lost. The announced body
(bounded as the request is) is read and thrown away in chunks, never kept, then the refusal is answered,
and the connection stays usable. A 429 costs no body memory: no place is taken for it."""
slots = getattr(self.front.RequestHandlerClass, "slots", None)
if slots is None:
self.skipTest("this front has no slots")
end = time.monotonic() + 10
while slots.busy != 0 and time.monotonic() < end: # the places of the requests before are given back
time.sleep(0.05)
self.assertEqual(slots.busy, 0, "places were still held when the test began")
slow = self.doc(b"%PDF-1.7\nSLOW" + bytes(200))
threads = [threading.Thread(target=lambda: self.post(slow)) for _ in range(2)]
for t in threads:
t.start()
end = time.monotonic() + 10
while slots.busy != 2 and time.monotonic() < end:
time.sleep(0.05)
self.assertEqual(slots.busy, 2, "two documents are being read")
body = json.dumps(self.doc(b"%PDF-1.7\n" + bytes(24 * 1024 * 1024))).encode() # about 32 MiB announced
sock = socket.create_connection(("127.0.0.1", self.port), timeout=30)
try:
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
got = b""
while b"\r\n\r\n" not in got:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
head, _, rest = got.partition(b"\r\n\r\n")
lines = head.split(b"\r\n")
self.assertIn(b" 429 ", lines[0], head) # the refusal came, not a connection cut
self.assertIn(b"Retry-After: 15", head)
n = next(int(l.split(b":", 1)[1]) for l in lines if l.lower().startswith(b"content-length:"))
while len(rest) < n:
rest += sock.recv(65536)
d = json.loads(rest)
self.assertEqual(d["error"]["type"], "server_busy_error")
self.assertIn(f"the box reads {S.DOCS} documents at a time", d["error"]["message"], rest)
# the body was fully read before the answer: the connection is not reset, it takes the next request
sock.sendall(b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
got = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
self.assertIn(b" 200 ", got.split(b"\r\n")[0], got[:200])
finally:
sock.close()
for t in threads:
t.join()
end = time.monotonic() + 10
while slots.busy != 0 and time.monotonic() < end:
time.sleep(0.05)
self.assertEqual(slots.busy, 0, "the slots were not given back when the documents ended")
def test_a_client_that_announces_a_body_then_goes_silent_gives_its_place_back(self):
"""The place is taken before the body is read: a client that announces a Content-Length and then goes
silent (or sends drop by drop) must not hold one of the two places for ever. The body's read has an
inactivity delay, BODY_S without a byte: past it the place is given back and the connection closed."""
slots = getattr(self.front.RequestHandlerClass, "slots", None)
if slots is None:
self.skipTest("this front has no slots")
had, was = hasattr(S, "BODY_S"), getattr(S, "BODY_S", None)
S.BODY_S = 1
try:
end = time.monotonic() + 10
while slots.busy != 0 and time.monotonic() < end: # the places of the requests before are given back
time.sleep(0.05)
sock = socket.create_connection(("127.0.0.1", self.port), timeout=10)
try:
# a body announced, only its beginning sent, then silence
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: 100000\r\n\r\n"
+ b'{"partial": ')
t0 = time.monotonic()
got = b""
try:
while True:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
except (socket.timeout, ConnectionError):
pass
took = time.monotonic() - t0
self.assertLess(took, 8, f"the front answered or closed only after {took:.1f} s")
if got:
self.assertIn(b" 408 ", got.split(b"\r\n")[0], got[:200])
self.assertIn(b"body", got, got[:300])
finally:
sock.close()
end = time.monotonic() + 5
while slots.busy != 0 and time.monotonic() < end:
time.sleep(0.05)
self.assertEqual(slots.busy, 0, "the place of a client that went silent was not given back")
finally:
if had:
S.BODY_S = was
else:
del S.BODY_S
def test_a_document_not_streamed_is_bounded_and_told_to_stream(self):
"""A document read without stream has a total bound at the front, NONSTREAM_S (2 h: 1000 pages at the
0.22 page/s measured beside the 27B under load take 4545 s). Past it the front stops the document (its
reads and its drawing container, as when the client leaves) and answers a 504 that says to send
"stream": true for a long document, without a Retry-After. A streamed document has no such bound."""
had, was = hasattr(S, "NONSTREAM_S"), getattr(S, "NONSTREAM_S", None)
S.NONSTREAM_S = 2
try:
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
body = json.dumps(self.doc(b"%PDF-1.7\nSLOW" + bytes(200))).encode() # its pages take 2.5 s to come
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
self.assertEqual(r.status, 504, raw)
self.assertIsNone(r.getheader("Retry-After"), "a bound past is never a try-again")
self.assertIn('"stream": true', json.loads(raw)["error"]["message"], raw)
# a streamed document has no such bound: its events come as they are read
s, raw = self.post(self.doc(b"%PDF-1.7\nSLOW" + bytes(200), stream=True))
events = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith("data: ")]
self.assertEqual(s, 200, raw[:300])
self.assertEqual(events[-1]["type"], "done", raw[-300:])
finally:
if had:
S.NONSTREAM_S = was
else:
del S.NONSTREAM_S
def test_a_drawing_is_refused_while_the_front_is_stopping(self):
"""SIGTERM sets a flag that is checked before a drawing is created, under the lock the drawing registers
itself with: a request that took a place after it is refused cleanly (a 503 with a Retry-After), not left
to create a container nobody ends."""
ev = getattr(S.Drawing, "stopping", None)
if ev is None:
ev = S.Drawing.stopping = threading.Event()
ev.set()
try:
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
body = json.dumps(self.doc()).encode()
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
self.assertEqual(r.status, 503, raw)
self.assertEqual(r.getheader("Retry-After"), "5")
self.assertIn("stopping", json.loads(raw)["error"]["message"], raw)
finally:
ev.clear()
self.assertEqual(self.post(self.doc(pages=[0]))[0], 200, "the lane reads again once the flag is cleared")
def test_the_drawing_waits_for_a_place_to_read(self):
"""A document of many pages, an engine that holds every page back: the front holds at most the read
parallelism of drawn pages waiting, not the whole document (1000 pages of 1 to 3 MiB each)."""
hold = threading.Event()
Engine.hold = hold
had, was = hasattr(S, "DRAW_S"), getattr(S, "DRAW_S", None)
S.DRAW_S = 2 # the no-line delay must not run while the front waits for a place, only while it reads the pipe
try:
sock = socket.create_connection(("127.0.0.1", self.port), timeout=30)
body = json.dumps(self.doc(b"%PDF-1.7\nMANY" + bytes(200), stream=True)).encode()
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(2.5) # the engine answers nothing: the drawing must wait for a place
sock.settimeout(2)
got = b""
try:
while True:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
except socket.timeout:
pass
drawn = got.count(b'"type": "drawn"')
self.assertLessEqual(drawn, 6, f"{drawn} pages of the 30 were drawn and held while the engine read none: "
"the document piles up in the front's memory")
self.assertGreaterEqual(drawn, 1)
self.assertNotIn(b'"type": "error"', got, "the no-line delay ran while the front waited for a place")
sock.close()
finally:
hold.set()
Engine.hold = None
if had:
S.DRAW_S = was
else:
del S.DRAW_S
def test_a_drawing_container_that_warns_a_lot_does_not_block_on_its_stderr(self):
"""Its stderr is read as it comes, only its last 2000 bytes kept: more than a pipe holds (64 KiB) of
warnings must not block the container, which would then be stopped for having given no line."""
had, was = hasattr(S, "DRAW_S"), getattr(S, "DRAW_S", None)
S.DRAW_S = 2 # a short delay for the test; the lane's is 2 x PAGE_S
try:
s, raw = self.post(self.doc(b"%PDF-1.7\nNOISY" + bytes(200)))
self.assertEqual(s, 200, raw) # its pages came: its stderr did not fill the pipe
self.assertEqual([p["index"] for p in json.loads(raw)["pages"]], [0, 2], raw)
s, raw = self.post(self.doc(b"%PDF-1.7\nNOISY-EXIT" + bytes(200)))
self.assertEqual(s, 500, raw)
self.assertIn("THE-LAST-WARNING-9182", json.loads(raw)["error"]["message"], raw) # the tail, not the head
finally:
if had:
S.DRAW_S = was
else:
del S.DRAW_S
def test_sigterm_ends_the_drawings_in_progress_and_exits_0(self):
"""SIGTERM: no more request is taken, the drawings in progress are ended (their containers are removed
with them), and the front exits 0 at once after that cleanup, without waiting for the reads in flight."""
d = tempfile.TemporaryDirectory(prefix="ocr-sigterm-")
self.addCleanup(d.cleanup)
root = pathlib.Path(d.name)
prompts = root / "prompts"
prompts.mkdir()
for f in ("document_structured", "document_markdown", "plain_ocr", "formula_recognition", "kie_fields"):
(prompts / f"{f}.txt").write_text("prompt")
drawer = root / "drawer.py"
drawer.write_text('import os, time\nopen(os.environ["DRAWER_PID"], "w").write(str(os.getpid()))\ntime.sleep(3600)\n')
pidfile = root / "drawer.pid"
proc, port = localports.spawn(lambda p: subprocess.Popen(
[sys.executable, "-I", str(REPO / "ocr-server.py"), "--host", "127.0.0.1", "--port", str(p),
"--engine", f"http://127.0.0.1:{self.eng.server_address[1]}", "--model-id", str(root),
"--recipe", "ovis", "--render-cmd", json.dumps([sys.executable, "-I", str(drawer)])],
env={**os.environ, "DRAWER_PID": str(pidfile)}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
drawer_pid = None
try:
for _ in range(100): # the front comes up
try:
c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
c.request("GET", "/health")
ok = c.getresponse().status == 200
c.close()
if ok:
break
except OSError:
time.sleep(0.05)
else:
self.fail("the front did not come up")
body = json.dumps(self.doc(b"%PDF-1.7\nHANG" + bytes(200))).encode()
def send(): # a document whose drawing never ends
c = http.client.HTTPConnection("127.0.0.1", port, timeout=60)
try:
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
c.getresponse().read()
except OSError:
pass
finally:
c.close()
threading.Thread(target=send, daemon=True).start()
for _ in range(100):
if pidfile.exists():
break
time.sleep(0.05)
self.assertTrue(pidfile.exists(), "the drawing container did not start")
drawer_pid = int(pidfile.read_text())
os.kill(drawer_pid, 0) # it runs
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=15), 0, "the front did not exit 0 on SIGTERM")
for _ in range(50):
try:
os.kill(drawer_pid, 0)
except OSError:
return # the drawing ended with the front
time.sleep(0.1)
self.fail("the drawing container was still alive after the front's SIGTERM")
finally:
if proc.poll() is None:
proc.kill()
if drawer_pid is not None:
try:
os.kill(drawer_pid, signal.SIGKILL)
except OSError:
pass
def test_sigterm_while_a_request_reads_its_body_exits_at_once_and_leaves_no_drawing(self):
"""SIGTERM while a request still reads its body (another document's pages are being read at the engine):
the flag set at SIGTERM refuses any drawing created after it, the drawings in progress are ended, and the
process exits within STOP_S at most after that cleanup (the places still taken are given up), without
waiting for the reads in flight (up to ENGINE_S), which TimeoutStopSec would end a SIGKILL. No drawing
container is left."""
d = tempfile.TemporaryDirectory(prefix="ocr-sigterm-body-")
self.addCleanup(d.cleanup)
root = pathlib.Path(d.name)
prompts = root / "prompts"
prompts.mkdir()
for f in ("document_structured", "document_markdown", "plain_ocr", "formula_recognition", "kie_fields"):
(prompts / f"{f}.txt").write_text("prompt")
drawer = root / "drawer.py"
drawer.write_text(DRAWER_HOLD)
pidfile = root / "drawer.pid"
proc, port = localports.spawn(lambda p: subprocess.Popen(
[sys.executable, "-I", str(REPO / "ocr-server.py"), "--host", "127.0.0.1", "--port", str(p),
"--engine", f"http://127.0.0.1:{self.eng.server_address[1]}", "--model-id", str(root),
"--recipe", "ovis", "--render-cmd", json.dumps([sys.executable, "-I", str(drawer)])],
env={**os.environ, "DRAWER_PID": str(pidfile)}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
drawer_pid = None
hold = threading.Event()
Engine.hold = hold
seen0 = len(Engine.seen)
try:
for _ in range(100): # the front comes up
try:
c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
c.request("GET", "/health")
ok = c.getresponse().status == 200
c.close()
if ok:
break
except OSError:
time.sleep(0.05)
else:
self.fail("the front did not come up")
def post_to(port, body): # a document being read: its pages drawn, its reads held at the engine
c = http.client.HTTPConnection("127.0.0.1", port, timeout=60)
try:
c.request("POST", "/v1/ocr", body=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
c.getresponse().read()
except (OSError, http.client.HTTPException):
pass # the front exits at once on SIGTERM, mid-answer
finally:
c.close()
threading.Thread(target=post_to, args=(port, self.doc()), daemon=True).start()
for _ in range(100): # its pages were sent to the engine
if len(Engine.seen) >= seen0 + 2:
break
time.sleep(0.05)
self.assertGreaterEqual(len(Engine.seen), seen0 + 2, "the document's pages were not read at the engine")
for _ in range(100):
if pidfile.exists():
break
time.sleep(0.05)
self.assertTrue(pidfile.exists(), "the drawing container did not start")
drawer_pid = int(pidfile.read_text())
os.kill(drawer_pid, 0) # it runs
# a second request, holding a place, still reading its body
sock = socket.create_connection(("127.0.0.1", port), timeout=10)
body = json.dumps(self.doc()).encode()
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body) + 4096).encode() + b"\r\n\r\n" + body) # 4096 bytes announced, not sent
time.sleep(0.3)
t0 = time.monotonic()
proc.send_signal(signal.SIGTERM)
rc = proc.wait(timeout=15) # the reads in flight must not hold the exit
took = time.monotonic() - t0
self.assertEqual(rc, 0)
self.assertLess(took, 10, f"the front exited {took:.1f} s after SIGTERM: it waited for the reads in flight")
sock.close()
alive = True
for _ in range(50): # no drawing container was left behind
try:
os.kill(drawer_pid, 0)
except OSError:
alive = False
break
time.sleep(0.1)
self.assertFalse(alive, "the drawing container was still alive after the front's exit")
finally:
hold.set()
Engine.hold = None
if proc.poll() is None:
proc.kill()
if drawer_pid is not None:
try:
os.kill(drawer_pid, signal.SIGKILL)
except OSError:
pass
def test_sigterm_lets_a_stream_in_progress_send_its_error_before_the_exit(self):
"""SIGTERM: past the flag, the main thread ends the drawings in progress in a loop (the list re-read
each turn) until no place is taken any more, or STOP_S at most, so a request in flight sends its last
event (a stream's error event, or its done with its errors) before the os._exit(0): the client does
not see a bare cut. The process exits in less than 10 s and leaves no drawing."""
d = tempfile.TemporaryDirectory(prefix="ocr-sigterm-stream-")
self.addCleanup(d.cleanup)
root = pathlib.Path(d.name)
prompts = root / "prompts"
prompts.mkdir()
for f in ("document_structured", "document_markdown", "plain_ocr", "formula_recognition", "kie_fields"):
(prompts / f"{f}.txt").write_text("prompt")
drawer = root / "drawer.py"
drawer.write_text(DRAWER_HOLD) # it draws the pages, writes its pid, then sleeps
pidfile = root / "drawer.pid"
proc, port = localports.spawn(lambda p: subprocess.Popen(
[sys.executable, "-I", str(REPO / "ocr-server.py"), "--host", "127.0.0.1", "--port", str(p),
"--engine", f"http://127.0.0.1:{self.eng.server_address[1]}", "--model-id", str(root),
"--recipe", "ovis", "--render-cmd", json.dumps([sys.executable, "-I", str(drawer)])],
env={**os.environ, "DRAWER_PID": str(pidfile)}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
drawer_pid = None
Engine.slow = 2.0 # the pages drawn are read slowly: the error can only be sent after those reads
try:
for _ in range(100): # the front comes up
try:
c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
c.request("GET", "/health")
ok = c.getresponse().status == 200
c.close()
if ok:
break
except OSError:
time.sleep(0.05)
else:
self.fail("the front did not come up")
sock = socket.create_connection(("127.0.0.1", port), timeout=30)
try:
body = json.dumps(self.doc(stream=True)).encode() # a stream whose drawing never ends
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
for _ in range(100):
if pidfile.exists():
break
time.sleep(0.05)
self.assertTrue(pidfile.exists(), "the drawing container did not start")
drawer_pid = int(pidfile.read_text())
os.kill(drawer_pid, 0) # it runs
proc.send_signal(signal.SIGTERM)
got = b""
sock.settimeout(15)
try:
while True:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
except (socket.timeout, ConnectionError):
pass
self.assertEqual(proc.wait(timeout=10), 0, "the front did not exit 0 in less than 10 s on SIGTERM")
self.assertTrue(b'"type": "error"' in got or b'"type": "done"' in got,
"the stream was cut without its last event")
finally:
sock.close()
alive = True
for _ in range(50): # no drawing container was left behind
try:
os.kill(drawer_pid, 0)
except OSError:
alive = False
break
time.sleep(0.1)
self.assertFalse(alive, "the drawing container was still alive after the front's exit")
finally:
Engine.slow = 0.0
if proc.poll() is None:
proc.kill()
if drawer_pid is not None:
try:
os.kill(drawer_pid, signal.SIGKILL)
except OSError:
pass
def test_a_drawing_container_that_gives_nothing_is_stopped(self):
had, was = hasattr(S, "DRAW_S"), getattr(S, "DRAW_S", None)
S.DRAW_S = 1 # a short delay for the test; the lane's is 2 x PAGE_S
try:
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
body = json.dumps(self.doc(b"%PDF-1.7\nHANG" + bytes(200))).encode()
t0 = time.monotonic()
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
took = time.monotonic() - t0
finally:
if had:
S.DRAW_S = was
else:
del S.DRAW_S
d = json.loads(raw)
self.assertEqual(r.status, 500, raw)
self.assertIn("a page was not drawn in 1 s", d["error"]["message"], raw)
self.assertLess(took, 15, "the front waited on a drawing container that gave nothing")
def test_health_and_models(self):
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
c.request("GET", "/health")
self.assertEqual(c.getresponse().status, 200)
c.close()
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
c.request("GET", "/v1/models")
d = json.loads(c.getresponse().read())
c.close()
self.assertEqual(d["data"][0]["id"], "ovisocr3")
self.assertEqual(d["data"][0]["modes"], ["document", "markdown", "text", "formula", "fields"])
class TheRefusals(unittest.TestCase):
"""The early refusals of do_POST (404, 411, 413, 429, 503): what is read before answering, what is
answered, and whether the connection is kept: never an octet of an unread body taken for the next
request (a request smuggled in a refused body)."""
@classmethod
def setUpClass(cls):
cls.dir = tempfile.TemporaryDirectory(prefix="ocr-refuse-")
cls.front, cls.eng = lane(cls.dir.name)
cls.port = cls.front.server_address[1]
@classmethod
def tearDownClass(cls):
for srv in (cls.front, cls.eng):
srv.shutdown()
srv.server_close()
cls.dir.cleanup()
def raw(self, timeout=30):
return socket.create_connection(("127.0.0.1", self.port), timeout=timeout)
def read_response(self, sock):
"""One HTTP response off the socket: (status line, headers, body); a cut connection ends the reads."""
got = b""
try:
while b"\r\n\r\n" not in got:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
head, _, rest = got.partition(b"\r\n\r\n")
n = next((int(l.split(b":", 1)[1]) for l in head.split(b"\r\n")[1:] if l.lower().startswith(b"content-length:")), 0)
while len(rest) < n:
chunk = sock.recv(65536)
if not chunk:
break
rest += chunk
except (socket.timeout, ConnectionError):
head, _, rest = got.partition(b"\r\n\r\n")
lines = head.split(b"\r\n")
headers = {}
for l in lines[1:]:
k, _, v = l.partition(b":")
headers[k.strip().lower()] = v.strip()
return (lines[0] if lines else b""), headers, rest
def after(self, sock, seconds=3):
"""What the front sends after the first response: b"" when it closed the connection."""
sock.settimeout(seconds)
out = b""
try:
while True:
chunk = sock.recv(65536)
if not chunk:
break
out += chunk
except (socket.timeout, ConnectionError):
pass
return out
def test_a_body_over_max_body_gets_a_413_without_any_read_and_the_connection_closed(self):
"""A Content-Length over MAX_BODY is a 413 with Connection: close, nothing read, the connection
closed: the rest of the announced body is never taken for the next request."""
had, was = hasattr(S, "MAX_BODY"), getattr(S, "MAX_BODY", None)
S.MAX_BODY = 1024
try:
sock = self.raw()
try:
smuggled = b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n"
body = bytes(2048) # announced 2048, over MAX_BODY 1024; its tail smuggles a request
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: 2048\r\n\r\n"
+ body + smuggled)
line, headers, _ = self.read_response(sock)
self.assertIn(b" 413 ", line, line)
self.assertEqual(headers.get(b"connection"), b"close", headers)
self.assertEqual(self.after(sock), b"", "the front answered a request out of the refused body")
finally:
sock.close()
finally:
if had:
S.MAX_BODY = was
else:
del S.MAX_BODY
def test_a_transfer_encoding_is_refused_before_any_read_even_on_an_unknown_route(self):
"""A request that carries a Transfer-Encoding is refused (411) before any read, with Connection:
close and the connection closed: on an unknown route too, where the Content-Length used to be read
first and the tail of the chunked body taken for the next request."""
sock = self.raw()
try:
smuggled = b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n"
head = (b"POST /nope HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
b"Content-Length: 10\r\nTransfer-Encoding: chunked\r\n\r\n")
sock.sendall(head + b"a\r\n0123456789\r\n" + smuggled) # 10 bytes announced; the rest is the chunked tail
line, headers, _ = self.read_response(sock)
self.assertIn(b" 411 ", line, line) # not a 404: nothing was read
self.assertEqual(headers.get(b"connection"), b"close", headers)
self.assertEqual(self.after(sock), b"", "the tail of the chunked body was taken for a request")
finally:
sock.close()
def test_a_refused_body_is_drained_in_at_most_drain_s_in_all(self):
"""The announced body a refusal reads and throws away is bounded twice: BODY_S without a byte, and
DRAIN_S in all: a client that sends a byte every BODY_S - 1 holds no thread for ever. The connection
is kept only if the body was read whole."""
had_b, was_b = hasattr(S, "BODY_S"), getattr(S, "BODY_S", None)
had_d, was_d = hasattr(S, "DRAIN_S"), getattr(S, "DRAIN_S", None)
S.BODY_S = 1
S.DRAIN_S = 2
try:
sock = self.raw(timeout=10)
try:
sock.sendall(b"POST /nope HTTP/1.1\r\nHost: x\r\nContent-Length: 100000\r\n\r\n")
t0 = time.monotonic()
stop = threading.Event()
th = threading.Thread(target=self._trickle, args=(sock, stop), daemon=True)
th.start()
try:
line, headers, _ = self.read_response(sock)
except socket.timeout:
self.fail("no refusal in 10 s: the drain of a refused body had no total bound")
took = time.monotonic() - t0
stop.set()
th.join(2)
self.assertIn(b" 404 ", line, line)
self.assertLess(took, 6, f"the refusal came after {took:.1f} s: the drain had no total bound")
self.assertEqual(headers.get(b"connection"), b"close",
"the body was not read whole: the connection must be closed")
finally:
stop.set()
sock.close()
finally:
if had_b:
S.BODY_S = was_b
else:
del S.BODY_S
if had_d:
S.DRAIN_S = was_d
else:
del S.DRAIN_S
@staticmethod
def _trickle(sock, stop):
try:
while not stop.is_set():
sock.sendall(b"x")
time.sleep(0.3) # a byte every 0.3 s: no inactivity delay (BODY_S = 1 s)
except OSError:
pass
class TheDrawingContainer(unittest.TestCase):
def test_a_drawing_in_progress_is_registered_and_ended(self):
"""The front keeps the drawings in progress, to end them when it stops (SIGTERM): their containers go with them."""
d = S.Drawing([sys.executable, "-I", "-c", "import time; time.sleep(60)"], b"x", None)
try:
self.assertIn(d, S.Drawing.live)
finally:
d.end()
self.assertNotIn(d, S.Drawing.live)
self.assertIsNotNone(d.proc.poll(), "the drawing's process was not stopped")
def test_the_sigterm_handler_takes_no_lock(self):
"""A Python signal handler runs on the main thread, which takes Drawing.live_lock while stopping:
the handler must take no lock itself, or a second SIGTERM (a stop sent twice) waits on itself until
the SIGKILL. It sets the stopping flag and starts the server's shutdown, and returns at once."""
on_sigterm = getattr(S, "on_sigterm", None)
if on_sigterm is None:
self.fail("no module-level on_sigterm: the handler main() installs cannot be called here, and it "
"takes Drawing.live_lock inside itself")
class Srv:
shut = False
def shutdown(self):
Srv.shut = True
S.Drawing.live_lock.acquire() # the main thread holds the lock, as it does while stopping
unblocked, done = [], threading.Event()
def watchdog():
if not done.wait(2) and S.Drawing.live_lock.locked():
unblocked.append(True)
S.Drawing.live_lock.release() # let a handler waiting on the lock return, to measure it
threading.Thread(target=watchdog, daemon=True).start()
try:
t0 = time.monotonic()
on_sigterm(Srv(), signal.SIGTERM, None)
took = time.monotonic() - t0
self.assertFalse(unblocked, "the SIGTERM handler waited on Drawing.live_lock")
self.assertLess(took, 1.0, f"the handler took {took:.2f} s with the lock held by its own thread")
self.assertTrue(Srv.shut, "the handler did not start the server's shutdown")
self.assertTrue(S.Drawing.stopping.is_set(), "the handler did not set the stopping flag")
finally:
done.set()
S.Drawing.stopping.clear()
if S.Drawing.live_lock.locked():
S.Drawing.live_lock.release()
def test_the_drawing_container_is_launched_outside_the_live_lock(self):
"""subprocess.Popen (a fork/exec) must not run under Drawing.live_lock: no drawing's start, no end
and no stop waits behind it. While Popen runs, the lock is free."""
real = subprocess.Popen
free = []
def probe(*a, **k):
free.append(not S.Drawing.live_lock.locked())
time.sleep(0.3) # a long fork/exec window
return real(*a, **k)
S.subprocess.Popen = probe
try:
d = S.Drawing([sys.executable, "-I", "-c", "import time; time.sleep(30)"], b"x", None)
finally:
S.subprocess.Popen = real
try:
self.assertEqual(free, [True], "Popen ran under Drawing.live_lock")
self.assertIn(d, S.Drawing.live)
finally:
d.end()
self.assertNotIn(d, S.Drawing.live)
def test_a_drawing_launched_while_stopping_is_ended_at_once(self):
"""Popen is out of the lock, so a stop can land between the launch and the registration: under the
lock the process just launched is then ended at once, and the drawing is refused (a 503)."""
real = subprocess.Popen
launched = []
def recording(*a, **k):
p = real(*a, **k)
launched.append(p)
return p
S.subprocess.Popen = recording
S.Drawing.stopping.set()
try:
with self.assertRaises(S.Bad) as got:
S.Drawing([sys.executable, "-I", "-c", "import time; time.sleep(60)"], b"x", None)
self.assertIn("stopping", str(got.exception))
self.assertEqual(len(launched), 1, "the container was not launched (Popen must run out of the lock)")
p = launched[0]
for _ in range(50):
if p.poll() is not None:
break
time.sleep(0.1)
self.assertIsNotNone(p.poll(), "the process launched while stopping was not ended at once")
finally:
S.Drawing.stopping.clear()
S.subprocess.Popen = real
for p in launched:
if p.poll() is None:
p.kill()
def test_it_has_no_network_and_no_rights(self):
a = type("A", (), {"render_cmd": "", "render_cpus": "0-4,10-14", "pdf_lib": "/x/pdf", "pages_code": "/x/ocr_pages.py",
"render_image": "img@sha256:abc"})()
argv = S.render_argv(a)
for flags in (["--network", "none"], ["--read-only"], ["--cap-drop", "ALL"], ["--security-opt", "no-new-privileges"],
["--user", "65534:65534"], ["--memory", "3g", "--memory-swap", "3g"], ["-v", "/x/pdf:/pdf:ro"]):
self.assertIn(flags, [argv[i:i + len(flags)] for i in range(len(argv))], flags)
self.assertNotIn("--gpus", argv)
self.assertEqual(argv[argv.index("--name") + 1], "{name}")
def test_what_a_file_is_is_read_in_its_bytes(self):
for head, want in ((b"%PDF-1.4", "pdf"), (b"\n\n%PDF-1.7", "pdf"), (b"\x89PNG\r\n\x1a\nrest", "png"), (b"\xff\xd8\xff\xe1", "jpeg"),
(b"RIFF\0\0\0\0WEBPVP8 ", "webp"), (b"II*\0", "tiff"), (b"MM\0*", "tiff"), (b"GIF89a", None), (b"PK\3\4", None),
(b"ftypheic", None)):
self.assertEqual(P.kind(head), want, head)
def test_each_frame_of_a_tiff_is_refused_before_it_is_decoded(self):
"""A TIFF's second frame can declare 40000 x 40000: it is refused with the documented words, like the first
image, before anything is decoded (Pillow's own check at seek is not relied on)."""
import io
import struct
from PIL import Image
a, b = Image.new("L", (4, 4), 1), Image.new("L", (4, 4), 2)
buf = io.BytesIO()
a.save(buf, "TIFF", save_all=True, append_images=[b])
data = bytearray(buf.getvalue())
ifd0 = struct.unpack("<I", data[4:8])[0]
n = struct.unpack("<H", data[ifd0:ifd0 + 2])[0]
nxt = struct.unpack("<I", data[ifd0 + 2 + 12 * n:ifd0 + 2 + 12 * n + 4])[0]
m = struct.unpack("<H", data[nxt:nxt + 2])[0]
for i in range(m):
e = nxt + 2 + 12 * i
tag, typ, cnt = struct.unpack("<HHI", bytes(data[e:e + 8]))
if tag in (256, 257): # the second frame says 13000 x 13000: 169 million pixels
struct.pack_into("<I", data, e + 8, 13000)
ask = {"dpi": 200, "side": 2880, "pixels": 8_294_400, "view": 1400}
pic = P.Picture(bytes(data))
self.assertEqual(pic.count, 2)
with self.assertRaises(P.Unreadable) as got:
pic.page(1, ask)
self.assertIn("150 million pixels", str(got.exception), "not the documented refusal")
im, dpi = pic.page(0, ask) # the first frame still draws
self.assertEqual(im.size, (4, 4))
def test_a_page_is_drawn_within_what_the_model_reads(self):
# an A4 page in points at 200 dpi: 1654 x 2339, under 2880 and 8.3 million pixels
s = P.scale(595.2, 841.8, 200 / 72, 2880, 8_294_400)
self.assertAlmostEqual(s, 200 / 72)
# a poster of 3 m: the longest side caps it
s = P.scale(8504, 2835, 200 / 72, 2880, 8_294_400)
self.assertLessEqual(8504 * s, 2880.001)
# a square of 2 m: the area does
s = P.scale(5669, 5669, 200 / 72, 2880, 8_294_400)
self.assertLessEqual(5669 * 5669 * s * s, 8_294_400 * 1.0001)
def test_the_pages_asked(self):
self.assertEqual(P.wanted_pages(None, 3), [0, 1, 2])
self.assertEqual(P.wanted_pages([2, 0, 2, 9], 3), [2, 0])
with self.assertRaises(P.Unreadable):
P.wanted_pages([5], 3)
with self.assertRaises(P.Unreadable):
P.wanted_pages(None, P.MAX_PAGES + 1)
with self.assertRaises(P.Unreadable):
P.wanted_pages(None, 0)
class TheRecipes(unittest.TestCase):
def test_a_json_cut_short_gives_the_blocks_that_parse(self):
text = '[{"bbox": [1, 2, 3, 4], "category": "text", "content": "a \\"b\\" {c}"}, {"bbox": [1, 2, 3, 4], "category": "ta'
self.assertEqual([b["content"] for b in M.blocks_of(text)], ['a "b" {c}'])
self.assertEqual(M.blocks_of("```json\n[]\n```"), [])
self.assertEqual(M.blocks_of("no JSON here"), [])
def test_markdown_from_blocks(self):
md = M.markdown_of([{"type": "title", "category": "doc_title", "content": "T"}, {"type": "equation", "category": "display_formula", "content": "x^2"},
{"type": "text", "category": "text", "content": " "}, {"type": "image", "category": "image", "content": ""},
{"type": "title", "category": "paragraph_title", "content": "## S"}])
self.assertEqual(md, "# T\n\n$$\nx^2\n$$\n\n![img-0.jpeg](img-0.jpeg)\n\n## S")
def test_a_table_spanning_cells_stays_html(self):
self.assertIsNone(M.table_markdown('<table><tr><td colspan="2">a</td></tr></table>'))
self.assertEqual(M.table_markdown("<table><tr><td>a|b</td><td>&amp;</td></tr></table>"), "| a\\|b | & |\n| --- | --- |")
def test_its_prompts_are_read_from_the_models_files(self):
text = (REPO / "ocr_models.py").read_text()
self.assertNotIn("natural reading order", text, "a prompt of the model's repository is copied here")
self.assertIn('self.folder / "prompts"', text)
if __name__ == "__main__":
unittest.main()