From dc26b941c13ded2e2fc1617ef8fa11859984f517 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 25 Oct 2026 09:56:06 +0100 Subject: [PATCH] fix(web-svc-translate): answer a batch per string instead of failing it whole One string that every engine refused or mangled raised out of the batch route's gather, so the gateway answered the whole batch with a 422 and the client lost the other nineteen translations. Gateway.translate_each now owns the bounded fan-out; with partial=true it answers (None, None) for a string that ran into a GatewayError and keeps the rest. Non-gateway exceptions still raise, and a NoBackendError on every string still fails the batch as the outage it is. The i18n client asks for partial batches and counts a null answer as a refused entry with its reason, so the re-ask and damage checks continue per string. A caller that does not send the flag gets the old behaviour. Co-Authored-By: Claude Opus 5.5 --- .../files/python/translate_gateway/app.py | 19 +++--- .../files/python/translate_gateway/gateway.py | 60 +++++++++++++++++++ .../files/translate_gateway/test_gateway.py | 51 ++++++++++++++++ .../python/utils/i18n/test_libretranslate.py | 18 ++++++ utils/i18n/client.py | 10 +++- 5 files changed, 147 insertions(+), 11 deletions(-) diff --git a/roles/web-svc-translate/files/python/translate_gateway/app.py b/roles/web-svc-translate/files/python/translate_gateway/app.py index d706b946e8..4f16c48947 100644 --- a/roles/web-svc-translate/files/python/translate_gateway/app.py +++ b/roles/web-svc-translate/files/python/translate_gateway/app.py @@ -106,16 +106,15 @@ def create_app(gateway, engines, *, detector=None): per_item = [tuple(entry) for entry in protected] else: per_item = [protected] * len(text) - limit = asyncio.Semaphore(BATCH_CONCURRENCY) - - async def _one(item, terms): - async with limit: - return await gateway.translate( - source, target, item, fmt=fmt, protected=terms, exclude=exclude - ) - - answered = await asyncio.gather( - *(_one(item, terms) for item, terms in zip(text, per_item, strict=True)) + answered = await gateway.translate_each( + source, + target, + text, + per_item, + concurrency=BATCH_CONCURRENCY, + fmt=fmt, + exclude=exclude, + partial=bool(body.get("partial")), ) return JSONResponse( content={ diff --git a/roles/web-svc-translate/files/python/translate_gateway/gateway.py b/roles/web-svc-translate/files/python/translate_gateway/gateway.py index 1c660f5b5d..6e7942c3bf 100644 --- a/roles/web-svc-translate/files/python/translate_gateway/gateway.py +++ b/roles/web-svc-translate/files/python/translate_gateway/gateway.py @@ -4,6 +4,8 @@ from __future__ import annotations import asyncio +from translate_gateway.errors import GatewayError, NoBackendError + REVIEWED = "weblate" @@ -83,3 +85,61 @@ class Gateway: return await self._router.translate( source, target, text, protected=terms, fmt=fmt, exclude=exclude ) + + async def translate_each( + self, + source, + target, + texts, + protected, + *, + concurrency, + fmt="text", + exclude=(), + partial=False, + ): + """Translate every string of a batch, at most *concurrency* at a time. + + Args: + source: source language code, or None for auto-detection. + target: target language code. + texts: the strings to translate. + protected: one tuple of spans per string, in the order of *texts*. + concurrency: how many strings are in flight at once. + fmt: the payload format, ``text`` or ``html``. + exclude: engines the caller already rejected for these strings. + partial: answer ``(None, None)`` for a string every engine refused + or mangled and keep the rest, instead of failing the batch. + + Returns: + ``(origin, translation)`` per string, in the order of *texts*. + + Raises: + GatewayError: the first failure without *partial*; with it, only a + NoBackendError every string ran into. + """ + limit = asyncio.Semaphore(concurrency) + + async def _one(text, terms): + async with limit: + return await self.translate( + source, target, text, fmt=fmt, protected=terms, exclude=exclude + ) + + answered = await asyncio.gather( + *(_one(text, terms) for text, terms in zip(texts, protected, strict=True)), + return_exceptions=partial, + ) + if not partial: + return list(answered) + for answer in answered: + if isinstance(answer, BaseException) and not isinstance( + answer, GatewayError + ): + raise answer + if answered and all(isinstance(answer, NoBackendError) for answer in answered): + raise answered[0] + return [ + (None, None) if isinstance(answer, GatewayError) else answer + for answer in answered + ] diff --git a/tests/unit/python/roles/web-svc-translate/files/translate_gateway/test_gateway.py b/tests/unit/python/roles/web-svc-translate/files/translate_gateway/test_gateway.py index eed672bbfc..5f538e3394 100644 --- a/tests/unit/python/roles/web-svc-translate/files/translate_gateway/test_gateway.py +++ b/tests/unit/python/roles/web-svc-translate/files/translate_gateway/test_gateway.py @@ -153,6 +153,57 @@ class GlossaryTestCase(unittest.TestCase): ) +class FailingStringsRouter: + def __init__(self, failures): + self.failures = failures + + async def translate( + self, source, target, text, *, protected=(), fmt="text", exclude=() + ): + if text in self.failures: + raise self.failures[text] + return "alpha", text.upper() + + +class BatchTestCase(unittest.TestCase): + """One string every engine mangles must not cost the rest of its batch.""" + + TEXTS = ("House", "Tree", "Garden") + + def _each(self, failures, *, partial): + gateway = Gateway(FailingStringsRouter(failures)) + return run( + gateway.translate_each( + "en", "de", self.TEXTS, [()] * 3, concurrency=2, partial=partial + ) + ) + + def test_a_partial_batch_answers_the_strings_that_survived(self) -> None: + answered = self._each( + {"Tree": MangledTermError("alpha dropped X")}, partial=True + ) + + self.assertEqual( + answered, [("alpha", "HOUSE"), (None, None), ("alpha", "GARDEN")] + ) + + def test_a_batch_without_partial_fails_on_its_first_refusal(self) -> None: + with self.assertRaises(MangledTermError): + self._each({"Tree": MangledTermError("alpha dropped X")}, partial=False) + + def test_a_partial_batch_no_engine_could_serve_still_fails(self) -> None: + failures = { + text: NoBackendError("no engine serves en to xx") for text in self.TEXTS + } + + with self.assertRaises(NoBackendError): + self._each(failures, partial=True) + + def test_an_unexpected_error_is_never_swallowed(self) -> None: + with self.assertRaises(RuntimeError): + self._each({"Tree": RuntimeError("bug")}, partial=True) + + class LoudFailureTestCase(unittest.TestCase): def test_a_router_failure_reaches_the_caller(self) -> None: gateway = Gateway( diff --git a/tests/unit/python/utils/i18n/test_libretranslate.py b/tests/unit/python/utils/i18n/test_libretranslate.py index 65d7bb09c2..32345827dc 100644 --- a/tests/unit/python/utils/i18n/test_libretranslate.py +++ b/tests/unit/python/utils/i18n/test_libretranslate.py @@ -119,6 +119,24 @@ class TestTranslateFailures(unittest.TestCase): ) +class TestPartialBatches(unittest.TestCase): + """The gateway answers null for one string it refused and keeps the rest.""" + + def setUp(self) -> None: + self.client = LibreTranslate("http://libretranslate", 1) + + def test_a_null_answer_discards_only_its_own_string(self) -> None: + answer = {"translatedText": ["Hallo", None], "engine": ["alpha", None]} + with mock.patch.object(self.client, "_call", return_value=answer) as call: + outcome = self.client.translate(["Hello", "Tree house"], "de") + + self.assertEqual(outcome.values, ["Hallo", None]) + self.assertEqual(outcome.refused, 1) + self.assertEqual(outcome.engines, ("alpha", "")) + self.assertIn("null", outcome.refusal) + self.assertTrue(call.call_args.args[1]["partial"]) + + class TestRefusalsAreRetried(unittest.TestCase): """A server that buckles under the lanes must not cost entries for good.""" diff --git a/utils/i18n/client.py b/utils/i18n/client.py index 41e3972ecc..b23b2e9055 100644 --- a/utils/i18n/client.py +++ b/utils/i18n/client.py @@ -201,6 +201,7 @@ class LibreTranslate: "format": "html", "protected": [mask_tokens(item) for item in masked], "exclude": list(exclude), + "partial": True, }, ) result = body["translatedText"] @@ -232,9 +233,16 @@ class LibreTranslate: return Outcome([None], refused, 0, refusal, ("",)) return merge(self._batch([text], target, exclude) for text in texts) values = [ - unmask(translated, item, text, target) + None if translated is None else unmask(translated, item, text, target) for translated, item, text in zip(result, masked, texts, strict=True) ] + if None in result: + refused += result.count(None) + refusal = ( + refusal + or "the gateway answered null: every engine refused or mangled it" + ) + engines = [engine or "" for engine in engines] retried, names = self._reask(texts, target, values, engines, exclude) damaged = sum(1 for text in retried if isinstance(text, Rejected)) return Outcome(retried, refused, damaged, refusal, tuple(names))