Merge pull request #2919 from infinito-nexus/fix/web-svc-libretranslate/worker-exit-hang

fix(web-svc-libretranslate): end a recycled gunicorn worker without the shutdown hang
This commit is contained in:
kevinveenbirkenbach authored and GitHub committed 2026-11-25 12:01:40 +01:00
commit 76e3a49cf3
6 files changed
+154 -6

No files matched your search

@@ -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
@@ -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();
@@ -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);
}
}
@@ -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)
@@ -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
@@ -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()