🔧 geçit 2xx gövdesindeki sağlayıcı hatası yeniden denemeye giriyor
Browse files at this commit3036cdec49c5eec08ea4f5f2b72c69d38a22c4c9Parent: 112d7df- fix
- 🔧 geçit 2xx gövdesindeki sağlayıcı hatası yeniden denemeye giriyor
2 changed files +152 -0
service/src/segment/provider.pymodified+64 -0
| @@ -77,6 +77,48 @@ class ProviderError(RuntimeError): | |||
| 77 | """Saglayici cagrisi kalici olarak basarisiz.""" | 77 | """Saglayici cagrisi kalici olarak basarisiz.""" |
| 78 | 78 | ||
| 79 | 79 | ||
| 80 | +class ProviderRejection(ProviderError): | ||
| 81 | + """Saglayicinin KALICI reddi (2xx govdesindeki terminal kod). | ||
| 82 | + | ||
| 83 | + NEDEN AYRI TIP: `BaseProvider.chat` HER istisnayi yeniden dener. Kalici bir | ||
| 84 | + reddi (or. `400 invalid model`) dort kez denemek yalniz kota yakar ve kosuyu | ||
| 85 | + geciktirir; bu tip deneme dongusunden ANINDA cikar. | ||
| 86 | + """ | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +#: Yeniden denenebilir saglayici kodlari. Gecit yuk altinda HTTP 200 ile | ||
| 90 | +#: `{"error":{"code":503}}` dondurur; 5xx ve 429 GECICI, 4xx KALICI sayilir. | ||
| 91 | +RETRY_STATUS = (408, 409, 425, 429, 500, 502, 503, 504) | ||
| 92 | +#: Govdeden tasinan saglayici mesajinin kirpma siniri. | ||
| 93 | +BODY_SNIPPET = 200 | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def provider_error_from_body(data: object) -> tuple[str, int | None] | None: | ||
| 97 | + """2xx GOVDESINDEKI saglayici hatasini cikarir. | ||
| 98 | + | ||
| 99 | + Kilo/OpenRouter tipi gecitler yuk altinda HTTP **200** ile | ||
| 100 | + `{"error":{"message":"Upstream error from Nvidia: Service temporarily | ||
| 101 | + overloaded","code":503}}` donduruyor. Yalniz durum koduna bakan istemci bunu | ||
| 102 | + basari sayar; `choices` bos gelince sema dogrulamasi anlasilmaz bir hatayla | ||
| 103 | + duser ve YENIDEN DENEME hic olmaz. Bu yardimci gercek nedeni yukari tasir. | ||
| 104 | + """ | ||
| 105 | + if not isinstance(data, dict): | ||
| 106 | + return None | ||
| 107 | + hata = data.get("error") | ||
| 108 | + if isinstance(hata, str) and hata.strip(): | ||
| 109 | + return f"LLM saglayici hatasi: {hata.strip()[:BODY_SNIPPET]}", None | ||
| 110 | + if not isinstance(hata, dict): | ||
| 111 | + return None | ||
| 112 | + kod = hata.get("code") | ||
| 113 | + durum = kod if isinstance(kod, int) and not isinstance(kod, bool) else None | ||
| 114 | + mesaj = hata.get("message") | ||
| 115 | + ayrinti = (mesaj.strip() if isinstance(mesaj, str) and mesaj.strip() | ||
| 116 | + else json.dumps(hata, ensure_ascii=False)) | ||
| 117 | + onek = (f"LLM saglayici hatasi (HTTP {durum})" if durum is not None | ||
| 118 | + else "LLM saglayici hatasi") | ||
| 119 | + return f"{onek}: {ayrinti[:BODY_SNIPPET]}", durum | ||
| 120 | + | ||
| 121 | + | ||
| 80 | @dataclass | 122 | @dataclass |
| 81 | class Usage: | 123 | class Usage: |
| 82 | """Bir cagrinin token kullanimi (OpenAI-uyumlu `usage` alanindan).""" | 124 | """Bir cagrinin token kullanimi (OpenAI-uyumlu `usage` alanindan).""" |
| @@ -356,6 +398,10 @@ class BaseProvider: | |||
| 356 | kind=kind, role=role, **kw) | 398 | kind=kind, role=role, **kw) |
| 357 | except BudgetExceeded: | 399 | except BudgetExceeded: |
| 358 | raise | 400 | raise |
| 401 | + except ProviderRejection: | ||
| 402 | + # KALICI red: yeniden denemek yalniz kota yakar ve kosuyu | ||
| 403 | + # geciktirir. Saglayicinin KENDI mesajiyla aninda biter. | ||
| 404 | + raise | ||
| 359 | except Exception as exc: # noqa: BLE001 | 405 | except Exception as exc: # noqa: BLE001 |
| 360 | last = exc | 406 | last = exc |
| 361 | # Ustel geri cekilme: 0.5s, 1s, 2s, 4s ... | 407 | # Ustel geri cekilme: 0.5s, 1s, 2s, 4s ... |
| @@ -397,6 +443,11 @@ class DeepSeekProvider(BaseProvider): | |||
| 397 | Anahtar ortamdan (`LLM_API_KEY`). Anahtar yokken de ORNEKLENEBILIR; | 443 | Anahtar ortamdan (`LLM_API_KEY`). Anahtar yokken de ORNEKLENEBILIR; |
| 398 | hata yalnizca gercek cagri aninda yukselir — boylece tum boru hatti | 444 | hata yalnizca gercek cagri aninda yukselir — boylece tum boru hatti |
| 399 | anahtarsiz ithal edilebilir. | 445 | anahtarsiz ithal edilebilir. |
| 446 | + | ||
| 447 | + GECIT GOVDE HATASI: Kilo/OpenRouter tipi gecitler yuk altinda HTTP 200 ile | ||
| 448 | + `{"error":{"code":503,...}}` dondurur. `_call` bunu `provider_error_from_body` | ||
| 449 | + ile yakalar: kod geciciyse yeniden denenir (`ProviderError`), kalici ise ILK | ||
| 450 | + denemede saglayicinin mesajiyla biter (`ProviderRejection`). | ||
| 400 | """ | 451 | """ |
| 401 | 452 | ||
| 402 | name = "deepseek" | 453 | name = "deepseek" |
| @@ -458,6 +509,19 @@ class DeepSeekProvider(BaseProvider): | |||
| 458 | except urllib.error.HTTPError as exc: | 509 | except urllib.error.HTTPError as exc: |
| 459 | body = exc.read().decode("utf-8", "replace")[:300] | 510 | body = exc.read().decode("utf-8", "replace")[:300] |
| 460 | raise ProviderError(f"HTTP {exc.code}: {body}") from exc | 511 | raise ProviderError(f"HTTP {exc.code}: {body}") from exc |
| 512 | + # GECIT 2xx GOVDESINDE HATA DONDUREBILIR (Kilo/OpenRouter, yuk altinda | ||
| 513 | + # HTTP 200 + `{"error":{"code":503,...}}`). Eskiden bu yanit `choices`siz | ||
| 514 | + # bir ChatResult uretiyor, sema dogrulamasi ANLASILMAZ bir hatayla | ||
| 515 | + # dusuyor ve yeniden deneme HIC olmuyordu -- gecici bir yuk, kosuyu | ||
| 516 | + # aciklanamayan bir hatayla bitiriyordu. | ||
| 517 | + hata = provider_error_from_body(data) | ||
| 518 | + if hata is not None: | ||
| 519 | + mesaj, durum = hata | ||
| 520 | + # Kalici kod (4xx): ILK denemede, saglayicinin kendi mesajiyla biter. | ||
| 521 | + if durum is not None and durum not in RETRY_STATUS: | ||
| 522 | + raise ProviderRejection(mesaj) | ||
| 523 | + # Gecici kod (5xx/429) ya da kodsuz hata: `chat` dongusu yeniden dener. | ||
| 524 | + raise ProviderError(mesaj) | ||
| 461 | latency = time.time() - t0 | 525 | latency = time.time() - t0 |
| 462 | choices = data.get("choices") or [{}] | 526 | choices = data.get("choices") or [{}] |
| 463 | message = choices[0].get("message", {}) or {} | 527 | message = choices[0].get("message", {}) or {} |
service/tests/test_segment_provider.pymodified+88 -0
| @@ -8,6 +8,7 @@ import json | |||
| 8 | import tempfile | 8 | import tempfile |
| 9 | import unittest | 9 | import unittest |
| 10 | from pathlib import Path | 10 | from pathlib import Path |
| 11 | +from unittest import mock | ||
| 11 | 12 | ||
| 12 | from src.segment.cache import NullCache, ResponseCache | 13 | from src.segment.cache import NullCache, ResponseCache |
| 13 | from src.segment.config import ( | 14 | from src.segment.config import ( |
| @@ -32,6 +33,7 @@ from src.segment.provider import ( | |||
| 32 | cost_usd, | 33 | cost_usd, |
| 33 | parse_item_from_prompt, | 34 | parse_item_from_prompt, |
| 34 | ) | 35 | ) |
| 36 | +from src.segment import provider as provider_mod | ||
| 35 | from src.segment.schema import parse_label_json | 37 | from src.segment.schema import parse_label_json |
| 36 | 38 | ||
| 37 | # Gercek altin ciftlerden biri (Kalitim) — sozel ikiz sik ornegi. | 39 | # Gercek altin ciftlerden biri (Kalitim) — sozel ikiz sik ornegi. |
| @@ -463,6 +465,92 @@ class TestDeepSeekProvider(unittest.TestCase): | |||
| 463 | self.assertEqual(p.name, "deepseek") | 465 | self.assertEqual(p.name, "deepseek") |
| 464 | 466 | ||
| 465 | 467 | ||
| 468 | +def _yanit(payload): | ||
| 469 | + """2xx govdeli `urlopen` taklidi.""" | ||
| 470 | + class _R: | ||
| 471 | + def read(self_inner): | ||
| 472 | + return json.dumps(payload).encode() | ||
| 473 | + | ||
| 474 | + def __enter__(self_inner): | ||
| 475 | + return self_inner | ||
| 476 | + | ||
| 477 | + def __exit__(self_inner, *a): | ||
| 478 | + return False | ||
| 479 | + | ||
| 480 | + return _R() | ||
| 481 | + | ||
| 482 | + | ||
| 483 | +class TestGatewayBodyError(unittest.TestCase): | ||
| 484 | + """GECIT 2xx GOVDESINDE HATA DONDUREBILIR (Kilo/OpenRouter tipi gecitler yuk | ||
| 485 | + altinda HTTP 200 + `{"error":{"code":503,...}}` dondurur). | ||
| 486 | + | ||
| 487 | + Durum koduna bakan istemci bunu basari sayar; `choices` bos gelince sema | ||
| 488 | + dogrulamasi ANLASILMAZ bir hatayla duser ve yeniden deneme HIC olmaz -- | ||
| 489 | + gecici bir yuk, kosuyu aciklanamayan bir hatayla bitirir. | ||
| 490 | + """ | ||
| 491 | + | ||
| 492 | + _SECENEK = {"choices": [{"message": {"content": "{\"etiket\": \"dogru\"}"}}], | ||
| 493 | + "usage": {}} | ||
| 494 | + | ||
| 495 | + def _provider(self, yanitlar, **over): | ||
| 496 | + cagri = {"n": 0} | ||
| 497 | + | ||
| 498 | + def _say(req, timeout=None): | ||
| 499 | + cagri["n"] += 1 | ||
| 500 | + yanit = yanitlar[cagri["n"] - 1] | ||
| 501 | + if isinstance(yanit, BaseException): | ||
| 502 | + raise yanit | ||
| 503 | + return yanit | ||
| 504 | + | ||
| 505 | + c = cfg(api_key="sahte-anahtar", **over) | ||
| 506 | + p = DeepSeekProvider(c, budget=BudgetGuard(10.0), sleep=lambda _s: None) | ||
| 507 | + return p, cagri, mock.patch("src.segment.provider.urllib.request.urlopen", | ||
| 508 | + side_effect=_say) | ||
| 509 | + | ||
| 510 | + def test_govdede_gecici_hata_yeniden_denenir(self): | ||
| 511 | + """503 = yuk; ilk yanit 200 ama govdede hata -> ikinci deneme basarili.""" | ||
| 512 | + yanitlar = [_yanit({"error": {"message": "Upstream error from Nvidia: " | ||
| 513 | + "Service temporarily overloaded", | ||
| 514 | + "code": 503}}), | ||
| 515 | + _yanit(self._SECENEK)] | ||
| 516 | + p, cagri, yama = self._provider(yanitlar) | ||
| 517 | + with yama: | ||
| 518 | + res = p.chat("x") | ||
| 519 | + self.assertEqual(cagri["n"], 2) | ||
| 520 | + self.assertIn("dogru", res.text) | ||
| 521 | + | ||
| 522 | + def test_govdede_kalici_hata_ilk_denemede_saglayicinin_mesajiyla_biter(self): | ||
| 523 | + """400 = istek yanlis; tekrar denemek yalniz kota yakar.""" | ||
| 524 | + yanitlar = [_yanit({"error": {"message": "model bulunamadi", "code": 400}})] | ||
| 525 | + p, cagri, yama = self._provider(yanitlar, max_retry=4) | ||
| 526 | + # `ProviderRejection` duzeltmeyle geldi; duzeltme ONCESI dosyada yoktur, | ||
| 527 | + # yani fail-pre-fix kaniti DAVRANISSAL olsun (ImportError degil). | ||
| 528 | + beklenen = getattr(provider_mod, "ProviderRejection", ProviderError) | ||
| 529 | + with yama: | ||
| 530 | + with self.assertRaises(beklenen) as ctx: | ||
| 531 | + p.chat("x") | ||
| 532 | + self.assertEqual(cagri["n"], 1) | ||
| 533 | + self.assertIn("model bulunamadi", str(ctx.exception)) | ||
| 534 | + | ||
| 535 | + def test_govdede_dizge_bicimi_hata_gecici_sayilir(self): | ||
| 536 | + yanitlar = [_yanit({"error": "temporary upstream failure"}), | ||
| 537 | + _yanit(self._SECENEK)] | ||
| 538 | + p, cagri, yama = self._provider(yanitlar) | ||
| 539 | + with yama: | ||
| 540 | + p.chat("x") | ||
| 541 | + self.assertEqual(cagri["n"], 2) | ||
| 542 | + | ||
| 543 | + def test_gercek_http_5xx_hala_yeniden_denenir(self): | ||
| 544 | + """Govde denetimi eklenirken tasima yolu BOZULMAMALI.""" | ||
| 545 | + import urllib.error | ||
| 546 | + yanitlar = [urllib.error.HTTPError("u", 503, "m", {}, None), | ||
| 547 | + _yanit(self._SECENEK)] | ||
| 548 | + p, cagri, yama = self._provider(yanitlar) | ||
| 549 | + with yama: | ||
| 550 | + p.chat("x") | ||
| 551 | + self.assertEqual(cagri["n"], 2) | ||
| 552 | + | ||
| 553 | + | ||
| 466 | class TestConfig(unittest.TestCase): | 554 | class TestConfig(unittest.TestCase): |
| 467 | 555 | ||
| 468 | def test_gecersiz_butce_reddedilir(self): | 556 | def test_gecersiz_butce_reddedilir(self): |