mirror of
https://github.com/Crosstalk-Solutions/project-nomad.git
synced 2026-12-04 03:58:13 +00:00
fix(translate): stop crash-looping on CPUs without AVX (#1512)
The bergamot wheel needs AVX. On a CPU without it (Celeron N5105, N100-class
mini PCs) importing it dies with SIGILL, which killed the whole proxy on the
first translated page; Docker restarted it and the /viewer healthcheck kept
reporting healthy.
At startup the proxy now tries the import once in a child process. If the
child dies, no language is offered, the library is forwarded untranslated,
and the reason ("this CPU lacks the AVX instructions ...") is logged and shown
in the page's translate bar.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0118UBk31k7JCzTSuktPuqVi
This commit is contained in:
1 parent
c922d98c01
commit
69bb17e468
5 files changed
+205
-15
No files matched your search
@@ -18,7 +18,7 @@ FROM python:3.10-slim
|
||||
RUN pip install --no-cache-dir bergamot==0.4.5
|
||||
|
||||
WORKDIR /app
|
||||
COPY blocks.py proxy.py fetch_models.py entrypoint.sh /app/
|
||||
COPY blocks.py proxy.py fetch_models.py engine_check.py entrypoint.sh /app/
|
||||
RUN chmod +x /app/entrypoint.sh
|
||||
|
||||
# Models are a mounted volume, not baked in: at ~37 MB per direction the image
|
||||
|
||||
@@ -31,12 +31,15 @@ Reimplementing or wrapping the Kiwix reading view is explicitly out of scope.
|
||||
| `proxy.py` | The proxy, the language control, and the rewrite step |
|
||||
| `blocks.py` | Finds translatable blocks; decides HTML mode versus plain text |
|
||||
| `fetch_models.py` | Pulls models from Firefox Remote Settings on first start |
|
||||
| `engine_check.py` | Checks at startup that this CPU can load Bergamot at all |
|
||||
| `test_blocks.py` | Tests for the block planner. No Bergamot, no network |
|
||||
| `test_fetch_models.py` | Tests for which model files get downloaded. No network |
|
||||
| `test_engine_check.py` | Tests for the startup CPU check. No Bergamot |
|
||||
| `entrypoint.sh` | Fetch models, then serve. Fetch failure is non-fatal |
|
||||
|
||||
Run the tests with `python3 install/nomad-translate/test_blocks.py` and
|
||||
`python3 install/nomad-translate/test_fetch_models.py`.
|
||||
Run the tests with `python3 install/nomad-translate/test_blocks.py`,
|
||||
`python3 install/nomad-translate/test_fetch_models.py` and
|
||||
`python3 install/nomad-translate/test_engine_check.py`.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -73,6 +76,16 @@ aarch64 wheel; ARM would need marian's `ruy` path. The build workflow pins
|
||||
`linux/amd64` so this fails at build time rather than producing an image that
|
||||
pulls cleanly on ARM and dies at start.
|
||||
|
||||
## CPUs without AVX
|
||||
|
||||
The `bergamot` wheel needs AVX. On a CPU without it (Celeron N5105, N100-class
|
||||
mini PCs) importing it dies with `Illegal instruction` (exit 132), which used to
|
||||
crash-loop the container on every translated page
|
||||
([#1512](https://github.com/Crosstalk-Solutions/project-nomad/issues/1512)).
|
||||
At startup the proxy now tries the import once in a child process; if that
|
||||
fails it offers no languages, forwards the library untranslated, and shows
|
||||
"translation unavailable" with the reason in the bar and the container log.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- **Tables are not translated.** Excluded wholesale to avoid a nesting problem,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Can this CPU run the Bergamot translation engine?
|
||||
|
||||
The bergamot 0.4.5 wheel is compiled for CPUs with AVX. On one without it
|
||||
(Celeron N5105, N100-class mini PCs, #1512) merely importing the module dies
|
||||
with SIGILL, which takes the whole proxy down with it: Docker restarts the
|
||||
container, the healthcheck (which only polls /viewer) still reads healthy, and
|
||||
the next translated page kills it again.
|
||||
|
||||
A signal cannot be caught from Python, so the import is tried once in a child
|
||||
process at startup. If the child dies, the proxy keeps forwarding the library
|
||||
untranslated and says why, instead of crash-looping.
|
||||
"""
|
||||
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
PROBE = [sys.executable, "-c", "import bergamot"]
|
||||
|
||||
NO_AVX_REASON = "this CPU lacks the AVX instructions the translation engine needs"
|
||||
|
||||
|
||||
def cpu_flags(cpuinfo: str) -> set[str]:
|
||||
"""The CPU feature flags listed in /proc/cpuinfo text."""
|
||||
for line in cpuinfo.splitlines():
|
||||
key, _, value = line.partition(":")
|
||||
if key.strip() == "flags":
|
||||
return set(value.split())
|
||||
return set()
|
||||
|
||||
|
||||
def reason_for(returncode: int, flags: set[str]) -> str | None:
|
||||
"""None when the probe passed, otherwise why translation is unavailable."""
|
||||
if returncode == 0:
|
||||
return None
|
||||
if returncode == -signal.SIGILL or returncode == 128 + signal.SIGILL:
|
||||
if flags and "avx" not in flags:
|
||||
return NO_AVX_REASON
|
||||
return "this CPU lacks instructions the translation engine needs"
|
||||
return f"the translation engine failed to load (exit {returncode})"
|
||||
|
||||
|
||||
def check_engine(run=subprocess.run, cpuinfo_path: str = "/proc/cpuinfo") -> str | None:
|
||||
"""Probe the engine in a child process. None means translation can be used."""
|
||||
try:
|
||||
returncode = run(PROBE, capture_output=True, timeout=120).returncode
|
||||
except Exception as exc: # timeout, missing interpreter, ...
|
||||
return f"the translation engine could not be checked ({exc})"
|
||||
try:
|
||||
with open(cpuinfo_path, encoding="utf-8", errors="ignore") as handle:
|
||||
flags = cpu_flags(handle.read())
|
||||
except OSError:
|
||||
flags = set()
|
||||
return reason_for(returncode, flags)
|
||||
@@ -29,6 +29,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import blocks
|
||||
import engine_check
|
||||
|
||||
UPSTREAM = os.environ.get("KIWIX", "http://localhost:8090").rstrip("/")
|
||||
MODELS = Path(os.environ.get("MODELS", "/models"))
|
||||
@@ -100,6 +101,12 @@ def available_languages() -> dict[str, str]:
|
||||
|
||||
|
||||
LANGS = available_languages()
|
||||
|
||||
# Why translation is off on this box, or None. Set at startup by the engine
|
||||
# probe: on a CPU that cannot run Bergamot (no AVX, #1512) the import would kill
|
||||
# the proxy, so no language is offered and the library is forwarded untranslated.
|
||||
UNAVAILABLE: str | None = None
|
||||
|
||||
# Part of every translated page's ETag, so a cached page from before a language
|
||||
# was added can never revalidate as unchanged.
|
||||
LANGS_TAG = "".join(sorted(LANGS)) or "none"
|
||||
@@ -181,7 +188,7 @@ def build_bar(lang: str, status: str) -> str:
|
||||
|
||||
def rewrite(body: str, lang: str) -> str:
|
||||
"""Translate block text in place and inject the control."""
|
||||
status = "not translated"
|
||||
status = f"translation unavailable: {UNAVAILABLE}" if UNAVAILABLE else "not translated"
|
||||
|
||||
if lang:
|
||||
started = time.time()
|
||||
@@ -325,17 +332,30 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
if __name__ == "__main__":
|
||||
if LANGS:
|
||||
print(
|
||||
f"nomad-translate: {len(LANGS)} languages available "
|
||||
f"({', '.join(sorted(LANGS))})",
|
||||
flush=True,
|
||||
)
|
||||
else:
|
||||
print(
|
||||
"nomad-translate: no models found, forwarding the library untranslated",
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
UNAVAILABLE = engine_check.check_engine()
|
||||
if UNAVAILABLE:
|
||||
LANGS = {}
|
||||
LANGS_TAG = "none"
|
||||
print(
|
||||
f"nomad-translate: translation disabled, {UNAVAILABLE}; "
|
||||
"forwarding the library untranslated",
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
|
||||
if not UNAVAILABLE:
|
||||
if LANGS:
|
||||
print(
|
||||
f"nomad-translate: {len(LANGS)} languages available "
|
||||
f"({', '.join(sorted(LANGS))})",
|
||||
flush=True,
|
||||
)
|
||||
else:
|
||||
print(
|
||||
"nomad-translate: no models found, forwarding the library untranslated",
|
||||
file=sys.stderr,
|
||||
flush=True,
|
||||
)
|
||||
|
||||
print(f"nomad-translate: listening on 0.0.0.0:{PORT} -> {UPSTREAM}", flush=True)
|
||||
ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests for the startup check that keeps a non-AVX CPU from crash-looping.
|
||||
|
||||
Pure functions only, no Bergamot and no network, so this runs anywhere:
|
||||
|
||||
python3 install/nomad-translate/test_engine_check.py
|
||||
|
||||
The failing case is #1512: on a Celeron N5105 (no AVX) `import bergamot` dies
|
||||
with SIGILL, exit code 132 from a shell, -4 from subprocess.
|
||||
"""
|
||||
|
||||
import signal
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
import engine_check # noqa: E402
|
||||
|
||||
failures: list[str] = []
|
||||
|
||||
|
||||
def check(name: str, got, want):
|
||||
if got != want:
|
||||
failures.append(f"{name}\n expected: {want!r}\n got: {got!r}")
|
||||
|
||||
|
||||
N5105 = "processor\t: 0\nflags\t\t: fpu vme sse sse2 ssse3 sse4_1 sse4_2 popcnt aes\n"
|
||||
ZEN = "processor\t: 0\nflags\t\t: fpu sse4_2 avx avx2 fma\n"
|
||||
|
||||
check("flags parsed", engine_check.cpu_flags(ZEN), {"fpu", "sse4_2", "avx", "avx2", "fma"})
|
||||
check("no flags line", engine_check.cpu_flags("processor : 0\n"), set())
|
||||
|
||||
check("probe passed", engine_check.reason_for(0, engine_check.cpu_flags(N5105)), None)
|
||||
check(
|
||||
"SIGILL without avx names AVX",
|
||||
engine_check.reason_for(-signal.SIGILL, engine_check.cpu_flags(N5105)),
|
||||
engine_check.NO_AVX_REASON,
|
||||
)
|
||||
check(
|
||||
"exit 132 (shell form of SIGILL) without avx names AVX",
|
||||
engine_check.reason_for(132, engine_check.cpu_flags(N5105)),
|
||||
engine_check.NO_AVX_REASON,
|
||||
)
|
||||
check(
|
||||
"SIGILL with avx does not blame AVX",
|
||||
engine_check.reason_for(-signal.SIGILL, engine_check.cpu_flags(ZEN)),
|
||||
"this CPU lacks instructions the translation engine needs",
|
||||
)
|
||||
check(
|
||||
"SIGILL with unreadable cpuinfo does not blame AVX",
|
||||
engine_check.reason_for(-signal.SIGILL, set()),
|
||||
"this CPU lacks instructions the translation engine needs",
|
||||
)
|
||||
check(
|
||||
"other failure reports the exit code",
|
||||
engine_check.reason_for(1, set()),
|
||||
"the translation engine failed to load (exit 1)",
|
||||
)
|
||||
|
||||
|
||||
def fake_run(returncode):
|
||||
return lambda *args, **kwargs: SimpleNamespace(returncode=returncode)
|
||||
|
||||
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".cpuinfo", delete=False) as handle:
|
||||
handle.write(N5105)
|
||||
n5105_path = handle.name
|
||||
|
||||
check("check_engine: working engine", engine_check.check_engine(fake_run(0), n5105_path), None)
|
||||
check(
|
||||
"check_engine: N5105 crash",
|
||||
engine_check.check_engine(fake_run(-signal.SIGILL), n5105_path),
|
||||
engine_check.NO_AVX_REASON,
|
||||
)
|
||||
check(
|
||||
"check_engine: missing cpuinfo still answers",
|
||||
engine_check.check_engine(fake_run(-signal.SIGILL), "/nonexistent/cpuinfo"),
|
||||
"this CPU lacks instructions the translation engine needs",
|
||||
)
|
||||
|
||||
|
||||
def raising_run(*args, **kwargs):
|
||||
raise TimeoutError("timed out")
|
||||
|
||||
|
||||
check(
|
||||
"check_engine: probe that cannot run",
|
||||
engine_check.check_engine(raising_run, n5105_path),
|
||||
"the translation engine could not be checked (timed out)",
|
||||
)
|
||||
|
||||
Path(n5105_path).unlink()
|
||||
|
||||
if failures:
|
||||
print(f"FAIL: {len(failures)} of the checks above did not hold\n")
|
||||
for failure in failures:
|
||||
print(f" {failure}\n")
|
||||
sys.exit(1)
|
||||
|
||||
print("ok: all engine check checks passed")
|
||||
Reference in new issue
Block a user