From ab36893f3cc7d698cd0fa848358b5d8105a89925 Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Thu, 3 Dec 2026 18:25:26 +0100 Subject: [PATCH] ocr lane: at SIGTERM the front lets the requests in flight send their last event os._exit(0) followed at once the end of the drawings, so the request threads never sent their error (a stream's error event, a 5xx without a stream): the client saw a bare cut. Past the flag, the main thread now 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, then exits. Co-Authored-By: Claude Opus 5.5 --- ocr-server.py | 17 +++++--- tests/test_ocr_server.py | 94 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 102 insertions(+), 9 deletions(-) diff --git a/ocr-server.py b/ocr-server.py index fb45bb24..77078234 100644 --- a/ocr-server.py +++ b/ocr-server.py @@ -44,6 +44,7 @@ ENGINE_S = 600 # one page's answer from the engine NONSTREAM_S = 7200 # a document read without stream, in all: 2 h, 1000 pages at the 0.22 page/s measured beside the 27B under load take 4545 s BODY_S = 60 # the body's read: this long without a byte and the client is gone, its place given back DRAIN_S = 120 # a refused body is drained in at most this long in all, BODY_S without a byte at a time +STOP_S = 5 # at SIGTERM: this long at most to let the requests in flight end their drawings and send their error RENDER = {"dpi": 200, "side": 2880, "pixels": 8_294_400, "view": 1400} MAX_FRAME = 64 * 1024 * 1024 # one picture the drawing container hands back DOCS = 2 # documents read at a time: each draws its pages in a container of 3 GiB of the unified memory @@ -825,11 +826,17 @@ def main(): signal.signal(signal.SIGTERM, lambda *_: on_sigterm(srv)) log(f"{name} OCR front on {a.host}:{a.port}, engine {a.engine}, {a.parallel} pages at a time, modes {', '.join(recipe.modes)}") srv.serve_forever() - with Drawing.live_lock: - live = list(Drawing.live) # no drawing can be added past the flag: it is checked under this same lock - for d in live: - d.end() # the drawings in progress end with the front: their containers are removed - os._exit(0) # at once, after the cleanup: the reads in flight (up to ENGINE_S) must not hold the exit + # 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 (the requests in flight then send their error and give their place + # back) or STOP_S at most; then os._exit, so the reads in flight (up to ENGINE_S) never hold the exit + deadline = time.monotonic() + STOP_S + while handler.slots.busy > 0 and time.monotonic() < deadline: + with Drawing.live_lock: + live = list(Drawing.live) # no drawing can be added past the flag: it is checked under this same lock + for d in live: + d.end() # the drawings in progress end with the front: their containers are removed + time.sleep(0.1) + os._exit(0) if __name__ == "__main__": diff --git a/tests/test_ocr_server.py b/tests/test_ocr_server.py index 933ae19b..f9dfb899 100644 --- a/tests/test_ocr_server.py +++ b/tests/test_ocr_server.py @@ -673,8 +673,9 @@ class TheLane(unittest.TestCase): 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 at once after that cleanup, without waiting for the reads in flight (up to ENGINE_S), which - TimeoutStopSec would end a SIGKILL. No drawing container is left.""" + 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) @@ -741,10 +742,10 @@ class TheLane(unittest.TestCase): time.sleep(0.3) t0 = time.monotonic() proc.send_signal(signal.SIGTERM) - rc = proc.wait(timeout=6) # the reads in flight must not hold the exit + 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, 5, f"the front exited {took:.1f} s after SIGTERM: it waited for the reads in flight") + 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 @@ -766,6 +767,91 @@ class TheLane(unittest.TestCase): 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" + s = socket.socket() + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + proc = subprocess.Popen([sys.executable, "-I", str(REPO / "ocr-server.py"), "--host", "127.0.0.1", "--port", str(port), + "--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