From 69f00693fa0f830e0435ee84547e0a57ea53fca7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 25 Nov 2026 09:57:08 +0000 Subject: [PATCH] fix(web-svc-libretranslate): end a recycled gunicorn worker without the shutdown hang MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gunicorn --max-requests 250 recycles the LibreTranslate worker, whose interpreter shutdown then hangs until the arbiter reaps it after --timeout. PR 2876 LibreTranslate#0 rescue log, containers/libretranslate.log: 'Autorestarting worker after current request' at 06:38:26, 'WORKER TIMEOUT (pid:35)' at 07:18:27. files/python/gunicorn_worker_exit.py holds a worker_exit hook that, in the worker's own pid, flushes stdout and stderr and calls os._exit with the pending SystemExit code. The role stages it into the build context and the Dockerfile appends it to scripts/gunicorn_conf.py. The Playwright spec now crosses one recycle (251 requests), and test-design visit() skips the second goto when login already landed on the target. The hook is a workaround until LibreTranslate/LibreTranslate#1041 ships; removal is tracked in #2918. 🎯 Fix: 85 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 81 🚦 Gate: ⛔ fix 85 % < 90 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/web-svc-libretranslate/files/Dockerfile | 4 + .../files/playwright/playwright.spec.js | 12 +- .../files/playwright/test-design.js | 5 +- .../files/python/gunicorn_worker_exit.py | 19 +++ .../web-svc-libretranslate/tasks/00_core.yml | 9 +- .../files/test_gunicorn_worker_exit.py | 111 ++++++++++++++++++ 6 files changed, 154 insertions(+), 6 deletions(-) create mode 100644 roles/web-svc-libretranslate/files/python/gunicorn_worker_exit.py create mode 100644 tests/unit/python/roles/web-svc-libretranslate/files/test_gunicorn_worker_exit.py diff --git a/roles/web-svc-libretranslate/files/Dockerfile b/roles/web-svc-libretranslate/files/Dockerfile index c12551be07..71b89f59a5 100644 --- a/roles/web-svc-libretranslate/files/Dockerfile +++ b/roles/web-svc-libretranslate/files/Dockerfile @@ -8,6 +8,10 @@ USER root COPY package-frontend-ca.crt /opt/package-frontend-ca.crt COPY package-frontend-ca.sh /usr/local/bin/package-frontend-ca.sh RUN /usr/local/bin/package-frontend-ca.sh +COPY gunicorn_worker_exit.py /tmp/gunicorn_worker_exit.py +RUN test -f scripts/gunicorn_conf.py \ + && { echo; cat /tmp/gunicorn_worker_exit.py; } >> scripts/gunicorn_conf.py \ + && rm /tmp/gunicorn_worker_exit.py USER ${APP_USER} COPY prefetch_models.py scripts/prefetch_models.py diff --git a/roles/web-svc-libretranslate/files/playwright/playwright.spec.js b/roles/web-svc-libretranslate/files/playwright/playwright.spec.js index 234d560dda..01c4588d1c 100644 --- a/roles/web-svc-libretranslate/files/playwright/playwright.spec.js +++ b/roles/web-svc-libretranslate/files/playwright/playwright.spec.js @@ -2,9 +2,11 @@ const { test, expect } = require("@playwright/test"); const { resolveTimeout } = require("./timeouts"); const { skipUnlessServiceEnabled } = require("./service-gating"); -const { decodeDotenvQuotedValue, gotoOnion, normalizeBaseUrl, performKeycloakLoginForm, runBiberFlow, runGuestFlow } = require("./personas"); +const { apiGetOnion, decodeDotenvQuotedValue, gotoOnion, normalizeBaseUrl, performKeycloakLoginForm, runBiberFlow, runGuestFlow } = require("./personas"); test.use({ ignoreHTTPSErrors: true }); +const GUNICORN_MAX_REQUESTS = 250; + require("./test-mcp-guest").register(); require("./test-design").register(); @@ -35,6 +37,14 @@ test("libretranslate /languages API stays reachable without auth", async ({ requ ).toBe(true); }); +test("libretranslate keeps answering across a gunicorn worker recycle", async ({ request }) => { + test.setTimeout(resolveTimeout(120_000)); + for (let sent = 1; sent <= GUNICORN_MAX_REQUESTS + 1; sent += 1) { + const response = await apiGetOnion(request, `${baseUrl}/languages`, { timeout: resolveTimeout(15_000) }); + expect(response.status(), `libretranslate /languages request ${sent} must answer 200 across the worker recycle`).toBe(200); + } +}); + test("administrator: oauth2-proxy gates the LibreTranslate UI through Keycloak", async ({ page }) => { skipUnlessServiceEnabled("sso"); expect(oidcIssuerUrl, "OIDC_ISSUER_URL must be set when OIDC is enabled").toBeTruthy(); diff --git a/roles/web-svc-libretranslate/files/playwright/test-design.js b/roles/web-svc-libretranslate/files/playwright/test-design.js index a262f07c3f..2ca0172fad 100644 --- a/roles/web-svc-libretranslate/files/playwright/test-design.js +++ b/roles/web-svc-libretranslate/files/playwright/test-design.js @@ -86,7 +86,8 @@ async function fresh(page) { * path: route below the base URL, with its query string. */ async function visit(page, path) { - await gotoOnion(page, `${base()}${path}`); + const target = `${base()}${path}`; + await gotoOnion(page, target); if (page.url().includes("openid-connect/auth")) { await performKeycloakLoginForm( page, @@ -94,7 +95,7 @@ async function visit(page, path) { decodeDotenvQuotedValue(process.env.ADMIN_PASSWORD), ); await expect.poll(() => page.url(), { timeout: resolveTimeout(60_000) }).toContain(base()); - await gotoOnion(page, `${base()}${path}`); + if (page.url() !== target) await gotoOnion(page, target); } } diff --git a/roles/web-svc-libretranslate/files/python/gunicorn_worker_exit.py b/roles/web-svc-libretranslate/files/python/gunicorn_worker_exit.py new file mode 100644 index 0000000000..263e60722a --- /dev/null +++ b/roles/web-svc-libretranslate/files/python/gunicorn_worker_exit.py @@ -0,0 +1,19 @@ +import os +import sys + + +def worker_exit(server, worker): + """ + Args: + server: the gunicorn arbiter. + worker: the worker that leaves; the hook ends its process with the + code of the SystemExit gunicorn is raising. + """ + if os.getpid() != worker.pid: + return + sys.stdout.flush() + sys.stderr.flush() + pending = sys.exc_info()[1] + if isinstance(pending, SystemExit) and isinstance(pending.code, int): + os._exit(pending.code) + os._exit(1) diff --git a/roles/web-svc-libretranslate/tasks/00_core.yml b/roles/web-svc-libretranslate/tasks/00_core.yml index 3975e6a20b..fa3a4307fa 100644 --- a/roles/web-svc-libretranslate/tasks/00_core.yml +++ b/roles/web-svc-libretranslate/tasks/00_core.yml @@ -10,11 +10,14 @@ include_role: name: sys-stk-full -- name: "📦 Stage the model prefetch of {{ application_id }}" +- name: "📦 Stage the model prefetch and the gunicorn worker-exit hook of {{ application_id }}" stack_host_copy: - src: python/prefetch_models.py - dest: "{{ [lookup('container', application_id, 'directories.instance'), 'prefetch_models.py'] | path_join }}" + src: "python/{{ item }}" + dest: "{{ [lookup('container', application_id, 'directories.instance'), item] | path_join }}" mode: "0644" + loop: + - prefetch_models.py + - gunicorn_worker_exit.py notify: - compose-build - compose-up diff --git a/tests/unit/python/roles/web-svc-libretranslate/files/test_gunicorn_worker_exit.py b/tests/unit/python/roles/web-svc-libretranslate/files/test_gunicorn_worker_exit.py new file mode 100644 index 0000000000..82bafe984e --- /dev/null +++ b/tests/unit/python/roles/web-svc-libretranslate/files/test_gunicorn_worker_exit.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import re +import subprocess +import sys +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any + +ROLE = PROJECT_ROOT / "roles" / "web-svc-libretranslate" +HOOK = ROLE / "files" / "python" / "gunicorn_worker_exit.py" +DOCKERFILE = ROLE / "files" / "Dockerfile" +CORE = ROLE / "tasks" / "00_core.yml" +LOAD_HOOK = """ +import importlib.util +import os +import sys +import threading +import types + +spec = importlib.util.spec_from_file_location("gunicorn_worker_exit", sys.argv[1]) +hook = importlib.util.module_from_spec(spec) +spec.loader.exec_module(hook) +""" +RECYCLED_WORKER = ( + LOAD_HOOK + + """ +threading.Thread(target=threading.Event().wait).start() +try: + sys.exit(3) +finally: + if sys.argv[2] == "hook": + hook.worker_exit(None, types.SimpleNamespace(pid=os.getpid())) +""" +) +ARBITER = ( + LOAD_HOOK + + """ +hook.worker_exit(None, types.SimpleNamespace(pid=os.getpid() + 1)) +print("alive") +""" +) + + +def _run(script: str, *args: str, timeout: float) -> subprocess.CompletedProcess: + """ + Args: + script: Python source run in a fresh interpreter. + args: arguments after the hook path. + timeout: seconds before the interpreter counts as hung. + + Returns: + The finished process. + """ + return subprocess.run( + [sys.executable, "-c", script, str(HOOK), *args], + check=False, + capture_output=True, + text=True, + timeout=timeout, + ) + + +class TestWorkerExit(unittest.TestCase): + def test_a_recycled_worker_leaves_with_its_exit_code_past_a_thread_that_never_ends( + self, + ) -> None: + result = _run(RECYCLED_WORKER, "hook", timeout=60) + self.assertEqual(result.returncode, 3, result.stderr) + + def test_without_the_hook_the_same_worker_hangs_in_interpreter_shutdown( + self, + ) -> None: + with self.assertRaises(subprocess.TimeoutExpired): + _run(RECYCLED_WORKER, "bare", timeout=3) + + def test_the_arbiter_keeps_running_when_the_hook_names_a_vanished_worker( + self, + ) -> None: + result = _run(ARBITER, timeout=60) + self.assertEqual( + (result.returncode, result.stdout.strip()), (0, "alive"), result.stderr + ) + + +class TestImageWiring(unittest.TestCase): + def test_the_image_appends_the_hook_to_the_gunicorn_config_of_the_entrypoint( + self, + ) -> None: + dockerfile = read_text(str(DOCKERFILE)) + self.assertIn(f"COPY {HOOK.name} /tmp/{HOOK.name}\n", dockerfile) + self.assertIn("RUN test -f scripts/gunicorn_conf.py \\\n", dockerfile) + self.assertRegex( + dockerfile, + rf"cat /tmp/{re.escape(HOOK.name)}; }} >> scripts/gunicorn_conf\.py", + ) + + def test_the_build_context_receives_the_hook(self) -> None: + staged = [ + task + for task in load_yaml_any(str(CORE), default_if_missing=[]) + if "stack_host_copy" in task and HOOK.name in task.get("loop", []) + ] + self.assertEqual( + [task["stack_host_copy"]["src"] for task in staged], ["python/{{ item }}"] + ) + + +if __name__ == "__main__": + unittest.main()