test_translator_failure_semantics.py 17.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
import logging

import pytest

from translation.cache import TranslationCache
from translation.logging_utils import (
    TranslationRequestFilter,
    bind_translation_request_id,
    reset_translation_request_id,
)
from translation.service import TranslationService
from translation.settings import build_translation_config, translation_cache_probe_models


class _FakeCache:
    def __init__(self):
        self.available = True
        self.storage = {}
        self.get_calls = []
        self.set_calls = []

    def get(self, *, model, target_lang, source_text, log_lookup=True):
        del log_lookup
        self.get_calls.append((model, target_lang, source_text))
        return self.storage.get((model, target_lang, source_text))

    def set(self, *, model, target_lang, source_text, translated_text):
        self.set_calls.append((model, target_lang, source_text, translated_text))
        self.storage[(model, target_lang, source_text)] = translated_text


def test_translation_cache_key_format(monkeypatch):
    monkeypatch.setattr(TranslationCache, "_init_redis_client", staticmethod(lambda: None))
    cache = TranslationCache({"ttl_seconds": 60, "sliding_expiration": True})
    key = cache.build_key(model="llm", target_lang="en", source_text="商品标题")
    assert key.startswith("trans:llm:en:商品标题")
    assert len(key) == len("trans:llm:en:商品标题") + 64


def test_service_caches_all_capabilities(monkeypatch):
    monkeypatch.setattr(TranslationCache, "_init_redis_client", staticmethod(lambda: None))
    created = {}

    def _fake_create_backend(self, *, name, backend_type, cfg):
        del self, backend_type, cfg

        class _Backend:
            model = name

            @property
            def supports_batch(self):
                return True

            def translate(self, text, target_lang, source_lang=None, scene=None):
                del target_lang, source_lang, scene
                if isinstance(text, list):
                    return [f"{name}:{item}" for item in text]
                return f"{name}:{text}"

        backend = _Backend()
        created[name] = backend
        return backend

    monkeypatch.setattr(TranslationService, "_create_backend", _fake_create_backend)
    config = {
        "service_url": "http://127.0.0.1:6006",
        "timeout_sec": 10.0,
        "default_model": "llm",
        "default_scene": "general",
        "capabilities": {
            "llm": {
                "enabled": True,
                "backend": "llm",
                "model": "dummy-llm",
                "base_url": "https://example.com",
                "timeout_sec": 10.0,
                "use_cache": True,
            },
            "opus-mt-zh-en": {
                "enabled": True,
                "backend": "local_marian",
                "model_id": "dummy",
                "model_dir": "dummy",
                "device": "cpu",
                "torch_dtype": "float32",
                "batch_size": 8,
                "max_input_length": 16,
                "max_new_tokens": 16,
                "num_beams": 1,
                "use_cache": True,
            },
        },
        "cache": {
            "ttl_seconds": 60,
            "sliding_expiration": True,
        },
    }

    service = TranslationService(config)
    fake_cache = _FakeCache()
    service._translation_cache = fake_cache

    first = service.translate("商品标题", target_lang="en", source_lang="zh", model="llm")
    second = service.translate("商品标题", target_lang="en", source_lang="zh", model="llm")
    batch = service.translate(["连衣裙", "衬衫"], target_lang="en", source_lang="zh", model="opus-mt-zh-en")

    assert first == "llm:商品标题"
    assert second == "llm:商品标题"
    assert batch == ["opus-mt-zh-en:连衣裙", "opus-mt-zh-en:衬衫"]
    assert fake_cache.get_calls == [
        ("llm", "en", "商品标题"),
        ("llm", "en", "商品标题"),
        ("opus-mt-zh-en", "en", "连衣裙"),
        ("opus-mt-zh-en", "en", "衬衫"),
    ]
    assert fake_cache.set_calls == [
        ("llm", "en", "商品标题", "llm:商品标题"),
        ("opus-mt-zh-en", "en", "连衣裙", "opus-mt-zh-en:连衣裙"),
        ("opus-mt-zh-en", "en", "衬衫", "opus-mt-zh-en:衬衫"),
    ]


def test_translation_request_filter_injects_reqid():
    reqid, token = bind_translation_request_id("req-test-1234567890")
    try:
        record = logging.LogRecord(
            name="translation.service",
            level=logging.INFO,
            pathname=__file__,
            lineno=1,
            msg="hello",
            args=(),
            exc_info=None,
        )
        TranslationRequestFilter().filter(record)

        assert reqid == "req-test-1234567890"
        assert record.reqid == "req-test-1234567890"
    finally:
        reset_translation_request_id(token)


def test_translation_route_log_focuses_on_routing_decision(monkeypatch, caplog):
    monkeypatch.setattr(TranslationCache, "_init_redis_client", staticmethod(lambda: None))

    def _fake_create_backend(self, *, name, backend_type, cfg):
        del self, backend_type, cfg

        class _Backend:
            model = name

            @property
            def supports_batch(self):
                return True

            def translate(self, text, target_lang, source_lang=None, scene=None):
                del target_lang, source_lang, scene
                return text

        return _Backend()

    monkeypatch.setattr(TranslationService, "_create_backend", _fake_create_backend)
    service = TranslationService(
        {
            "service_url": "http://127.0.0.1:6006",
            "timeout_sec": 10.0,
            "default_model": "llm",
            "default_scene": "general",
            "capabilities": {
                "llm": {
                    "enabled": True,
                    "backend": "llm",
                    "model": "dummy-llm",
                    "base_url": "https://example.com",
                    "timeout_sec": 10.0,
                    "use_cache": True,
                }
            },
            "cache": {
                "ttl_seconds": 60,
                "sliding_expiration": True,
            },
        }
    )

    with caplog.at_level(logging.INFO):
        service.translate("商品标题", target_lang="en", source_lang="zh", model="llm")

    route_messages = [
        record.getMessage()
        for record in caplog.records
        if record.name == "translation.service" and record.getMessage().startswith("Translation route |")
    ]

    assert route_messages == [
        "Translation route | backend=llm request_type=single use_cache=True cache_available=False"
    ]


def test_service_skips_failed_backend_but_keeps_healthy_capabilities(monkeypatch):
    monkeypatch.setattr(TranslationCache, "_init_redis_client", staticmethod(lambda: None))

    def _fake_create_backend(self, *, name, backend_type, cfg):
        del self, backend_type, cfg
        if name == "broken-nllb":
            raise RuntimeError("broken model dir")

        class _Backend:
            model = name

            @property
            def supports_batch(self):
                return True

            def translate(self, text, target_lang, source_lang=None, scene=None):
                del target_lang, source_lang, scene
                return text

        return _Backend()

    monkeypatch.setattr(TranslationService, "_create_backend", _fake_create_backend)
    service = TranslationService(
        {
            "service_url": "http://127.0.0.1:6006",
            "timeout_sec": 10.0,
            "default_model": "llm",
            "default_scene": "general",
            "capabilities": {
                "llm": {
                    "enabled": True,
                    "backend": "llm",
                    "model": "dummy-llm",
                    "base_url": "https://example.com",
                    "timeout_sec": 10.0,
                    "use_cache": True,
                },
                "broken-nllb": {
                    "enabled": True,
                    "backend": "local_nllb",
                    "model_id": "dummy",
                    "model_dir": "dummy",
                    "device": "cpu",
                    "torch_dtype": "float32",
                    "batch_size": 8,
                    "max_input_length": 16,
                    "max_new_tokens": 16,
                    "num_beams": 1,
                    "use_cache": True,
                },
            },
            "cache": {
                "ttl_seconds": 60,
                "sliding_expiration": True,
            },
        }
    )

    assert service.available_models == ["llm", "broken-nllb"]
    assert service.loaded_models == ["llm"]
    assert service.failed_models == ["broken-nllb"]
    assert service.backend_errors["broken-nllb"] == "broken model dir"

    with pytest.raises(RuntimeError, match="failed to initialize"):
        service.get_backend("broken-nllb")


def test_translation_cache_probe_models_order():
    cfg = {"cache": {"model_quality_tiers": {"low": 10, "high": 50, "mid": 30}}}
    assert translation_cache_probe_models(cfg, "low") == ["high", "mid", "low"]
    assert translation_cache_probe_models(cfg, "mid") == ["high", "mid"]
    assert translation_cache_probe_models(cfg, "high") == ["high"]
    assert translation_cache_probe_models(cfg, "unknown") == ["unknown"]


def test_translation_cache_probe_models_respects_enable_switch():
    cfg = {
        "cache": {
            "enable_model_quality_tier_cache": False,
            "model_quality_tiers": {"peer-a": 50, "peer-b": 50, "top": 100},
        }
    }
    assert translation_cache_probe_models(cfg, "peer-a") == ["peer-a"]


def test_translation_cache_probe_models_same_tier_included():
    """Same numeric tier: all peers are probed (higher tier first, then name order)."""
    cfg = {"cache": {"model_quality_tiers": {"peer-a": 50, "peer-b": 50, "top": 100}}}
    assert translation_cache_probe_models(cfg, "peer-a") == ["top", "peer-a", "peer-b"]
    assert translation_cache_probe_models(cfg, "peer-b") == ["top", "peer-b", "peer-a"]


def test_model_quality_tiers_unknown_capability_raises():
    with pytest.raises(ValueError, match="unknown capability"):
        build_translation_config(
            {
                "service_url": "http://127.0.0.1:6006",
                "timeout_sec": 10.0,
                "default_model": "llm",
                "default_scene": "general",
                "cache": {
                    "ttl_seconds": 60,
                    "sliding_expiration": True,
                    "model_quality_tiers": {"ghost": 1},
                },
                "capabilities": {
                    "llm": {
                        "enabled": True,
                        "backend": "llm",
                        "model": "dummy-llm",
                        "base_url": "https://example.com",
                        "timeout_sec": 10.0,
                        "use_cache": True,
                    }
                },
            }
        )


def test_tiered_cache_reuses_higher_tier_entry(monkeypatch):
    monkeypatch.setattr(TranslationCache, "_init_redis_client", staticmethod(lambda: None))
    translate_calls = []

    def _fake_create_backend(self, *, name, backend_type, cfg):
        del self, backend_type, cfg

        class _Backend:
            model = name

            @property
            def supports_batch(self):
                return True

            def translate(self, text, target_lang, source_lang=None, scene=None):
                del target_lang, source_lang, scene
                translate_calls.append((name, text))
                if isinstance(text, list):
                    return [f"{name}:{item}" for item in text]
                return f"{name}:{text}"

        return _Backend()

    monkeypatch.setattr(TranslationService, "_create_backend", _fake_create_backend)
    config = {
        "service_url": "http://127.0.0.1:6006",
        "timeout_sec": 10.0,
        "default_model": "opus-mt-zh-en",
        "default_scene": "general",
        "capabilities": {
            "deepl": {
                "enabled": True,
                "backend": "deepl",
                "api_url": "https://api.deepl.com/v2/translate",
                "timeout_sec": 10.0,
                "use_cache": True,
            },
            "opus-mt-zh-en": {
                "enabled": True,
                "backend": "local_marian",
                "model_id": "dummy",
                "model_dir": "dummy",
                "device": "cpu",
                "torch_dtype": "float32",
                "batch_size": 8,
                "max_input_length": 16,
                "max_new_tokens": 16,
                "num_beams": 1,
                "use_cache": True,
            },
        },
        "cache": {
            "ttl_seconds": 60,
            "sliding_expiration": True,
            "model_quality_tiers": {"deepl": 100, "opus-mt-zh-en": 40},
        },
    }

    service = TranslationService(config)
    fake_cache = _FakeCache()
    fake_cache.storage[("deepl", "en", "商品标题")] = "from-deepl"
    service._translation_cache = fake_cache

    out = service.translate("商品标题", target_lang="en", source_lang="zh", model="opus-mt-zh-en")
    assert out == "from-deepl"
    assert translate_calls == []
    assert fake_cache.get_calls == [("deepl", "en", "商品标题")]


def test_tiered_cache_reuses_same_tier_peer(monkeypatch):
    """Model A may use cache written under model B when both share the same tier."""
    monkeypatch.setattr(TranslationCache, "_init_redis_client", staticmethod(lambda: None))
    translate_calls = []

    def _fake_create_backend(self, *, name, backend_type, cfg):
        del self, backend_type, cfg

        class _Backend:
            model = name

            @property
            def supports_batch(self):
                return True

            def translate(self, text, target_lang, source_lang=None, scene=None):
                del target_lang, source_lang, scene
                translate_calls.append((name, text))
                if isinstance(text, list):
                    return [f"{name}:{item}" for item in text]
                return f"{name}:{text}"

        return _Backend()

    monkeypatch.setattr(TranslationService, "_create_backend", _fake_create_backend)
    marian_cap = {
        "enabled": True,
        "backend": "local_marian",
        "model_id": "dummy",
        "model_dir": "dummy",
        "device": "cpu",
        "torch_dtype": "float32",
        "batch_size": 8,
        "max_input_length": 16,
        "max_new_tokens": 16,
        "num_beams": 1,
        "use_cache": True,
    }
    config = {
        "service_url": "http://127.0.0.1:6006",
        "timeout_sec": 10.0,
        "default_model": "opus-mt-en-zh",
        "default_scene": "general",
        "capabilities": {
            "opus-mt-zh-en": dict(marian_cap),
            "opus-mt-en-zh": dict(marian_cap),
        },
        "cache": {
            "ttl_seconds": 60,
            "sliding_expiration": True,
            "model_quality_tiers": {"opus-mt-zh-en": 50, "opus-mt-en-zh": 50},
        },
    }

    service = TranslationService(config)
    fake_cache = _FakeCache()
    fake_cache.storage[("opus-mt-zh-en", "en", "hello")] = "from-zh-en"
    service._translation_cache = fake_cache

    out = service.translate("hello", target_lang="en", source_lang="zh", model="opus-mt-en-zh")
    assert out == "from-zh-en"
    assert translate_calls == []
    assert fake_cache.get_calls == [
        ("opus-mt-en-zh", "en", "hello"),
        ("opus-mt-zh-en", "en", "hello"),
    ]


def test_tiered_cache_switch_off_uses_exact_model_only(monkeypatch):
    monkeypatch.setattr(TranslationCache, "_init_redis_client", staticmethod(lambda: None))
    translate_calls = []

    def _fake_create_backend(self, *, name, backend_type, cfg):
        del self, backend_type, cfg

        class _Backend:
            model = name

            @property
            def supports_batch(self):
                return True

            def translate(self, text, target_lang, source_lang=None, scene=None):
                del target_lang, source_lang, scene
                translate_calls.append((name, text))
                if isinstance(text, list):
                    return [f"{name}:{item}" for item in text]
                return f"{name}:{text}"

        return _Backend()

    monkeypatch.setattr(TranslationService, "_create_backend", _fake_create_backend)
    config = {
        "service_url": "http://127.0.0.1:6006",
        "timeout_sec": 10.0,
        "default_model": "opus-mt-zh-en",
        "default_scene": "general",
        "capabilities": {
            "deepl": {
                "enabled": True,
                "backend": "deepl",
                "api_url": "https://api.deepl.com/v2/translate",
                "timeout_sec": 10.0,
                "use_cache": True,
            },
            "opus-mt-zh-en": {
                "enabled": True,
                "backend": "local_marian",
                "model_id": "dummy",
                "model_dir": "dummy",
                "device": "cpu",
                "torch_dtype": "float32",
                "batch_size": 8,
                "max_input_length": 16,
                "max_new_tokens": 16,
                "num_beams": 1,
                "use_cache": True,
            },
        },
        "cache": {
            "ttl_seconds": 60,
            "sliding_expiration": True,
            "enable_model_quality_tier_cache": False,
            "model_quality_tiers": {"deepl": 100, "opus-mt-zh-en": 40},
        },
    }

    service = TranslationService(config)
    fake_cache = _FakeCache()
    fake_cache.storage[("deepl", "en", "商品标题")] = "from-deepl"
    service._translation_cache = fake_cache

    out = service.translate("商品标题", target_lang="en", source_lang="zh", model="opus-mt-zh-en")
    assert out == "opus-mt-zh-en:商品标题"
    assert translate_calls == [("opus-mt-zh-en", "商品标题")]
    assert fake_cache.get_calls == [("opus-mt-zh-en", "en", "商品标题")]