| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | import json |
| 13 | import os |
| 14 | import unittest |
| 15 | import urllib.error |
| 16 | from unittest import mock |
| 17 | |
| 18 | from src.providers.llm import DEFAULT_TIMEOUT, LLMClient, _is_retryable |
| 19 | from src.providers.resilience import (BREAKER_THRESHOLD, CircuitBreaker, |
| 20 | LlmUnavailable, backoff_delay, |
| 21 | call_with_retry) |
| 22 | |
| 23 | |
| 24 | def _http(code): |
| 25 | return urllib.error.HTTPError("u", code, "m", {}, None) |
| 26 | |
| 27 | |
| 28 | def _yanit(payload): |
| 29 | |
| 30 | class _R: |
| 31 | def read(self_inner): |
| 32 | return json.dumps(payload).encode() |
| 33 | |
| 34 | def __enter__(self_inner): |
| 35 | return self_inner |
| 36 | |
| 37 | def __exit__(self_inner, *a): |
| 38 | return False |
| 39 | |
| 40 | return _R() |
| 41 | |
| 42 | |
| 43 | class RetryClassificationTests(unittest.TestCase): |
| 44 | def test_transient_statuses_are_retried(self): |
| 45 | for kod in (408, 429, 500, 502, 503, 504): |
| 46 | with self.subTest(kod): |
| 47 | self.assertTrue(_is_retryable(_http(kod))[0]) |
| 48 | |
| 49 | def test_client_errors_are_not_retried(self): |
| 50 | |
| 51 | for kod in (400, 401, 403, 404, 422): |
| 52 | with self.subTest(kod): |
| 53 | self.assertFalse(_is_retryable(_http(kod))[0]) |
| 54 | |
| 55 | def test_network_errors_are_retried(self): |
| 56 | for exc in (urllib.error.URLError("kapali"), TimeoutError(), |
| 57 | ConnectionResetError()): |
| 58 | with self.subTest(type(exc).__name__): |
| 59 | self.assertTrue(_is_retryable(exc)[0]) |
| 60 | |
| 61 | def test_unknown_exception_is_not_retried(self): |
| 62 | self.assertFalse(_is_retryable(ValueError("bozuk json"))[0]) |
| 63 | |
| 64 | |
| 65 | class BackoffTests(unittest.TestCase): |
| 66 | def test_exponential_with_cap(self): |
| 67 | v = [backoff_delay(i, rng=lambda: 1.0) for i in range(1, 7)] |
| 68 | self.assertEqual(v[:5], [0.5, 1.0, 2.0, 4.0, 8.0]) |
| 69 | self.assertEqual(v[5], 8.0) |
| 70 | |
| 71 | def test_jitter_is_between_half_and_full(self): |
| 72 | |
| 73 | |
| 74 | |
| 75 | tam = backoff_delay(3, rng=lambda: 1.0) |
| 76 | yari = backoff_delay(3, rng=lambda: 0.0) |
| 77 | self.assertAlmostEqual(tam, 2.0) |
| 78 | self.assertAlmostEqual(yari, 1.0) |
| 79 | |
| 80 | |
| 81 | class RetryLoopTests(unittest.TestCase): |
| 82 | def setUp(self): |
| 83 | self.uyku = [] |
| 84 | |
| 85 | def _sleep(self, s): |
| 86 | self.uyku.append(s) |
| 87 | |
| 88 | def test_succeeds_after_transient_failures(self): |
| 89 | deneme = {"n": 0} |
| 90 | |
| 91 | def fn(): |
| 92 | deneme["n"] += 1 |
| 93 | if deneme["n"] < 3: |
| 94 | raise _http(429) |
| 95 | return "ok" |
| 96 | |
| 97 | out = call_with_retry(fn, is_retryable=_is_retryable, max_attempts=3, |
| 98 | sleep=self._sleep, rng=lambda: 1.0) |
| 99 | self.assertEqual(out, "ok") |
| 100 | self.assertEqual(deneme["n"], 3) |
| 101 | self.assertEqual(len(self.uyku), 2) |
| 102 | |
| 103 | def test_non_retryable_fails_immediately(self): |
| 104 | deneme = {"n": 0} |
| 105 | |
| 106 | def fn(): |
| 107 | deneme["n"] += 1 |
| 108 | raise _http(401) |
| 109 | |
| 110 | with self.assertRaises(LlmUnavailable): |
| 111 | call_with_retry(fn, is_retryable=_is_retryable, max_attempts=5, |
| 112 | sleep=self._sleep) |
| 113 | self.assertEqual(deneme["n"], 1) |
| 114 | self.assertEqual(self.uyku, []) |
| 115 | |
| 116 | def test_budget_stops_waiting(self): |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | saat = {"t": 0.0} |
| 124 | |
| 125 | def clock(): |
| 126 | saat["t"] += 20.0 |
| 127 | return saat["t"] |
| 128 | |
| 129 | with self.assertRaises(LlmUnavailable): |
| 130 | call_with_retry(lambda: (_ for _ in ()).throw(_http(503)), |
| 131 | is_retryable=_is_retryable, max_attempts=5, |
| 132 | budget_s=30.0, sleep=self._sleep, clock=clock, |
| 133 | rng=lambda: 1.0) |
| 134 | self.assertEqual(len(self.uyku), 1, "bütçe aşıldığı hâlde beklendi") |
| 135 | self.assertLess(sum(self.uyku), 30.0) |
| 136 | |
| 137 | def test_budget_zero_never_waits(self): |
| 138 | with self.assertRaises(LlmUnavailable): |
| 139 | call_with_retry(lambda: (_ for _ in ()).throw(_http(503)), |
| 140 | is_retryable=_is_retryable, max_attempts=5, |
| 141 | budget_s=0.0, sleep=self._sleep, rng=lambda: 1.0) |
| 142 | self.assertEqual(self.uyku, []) |
| 143 | |
| 144 | def test_error_is_typed_and_carries_status(self): |
| 145 | with self.assertRaises(LlmUnavailable) as ctx: |
| 146 | call_with_retry(lambda: (_ for _ in ()).throw(_http(429)), |
| 147 | is_retryable=_is_retryable, max_attempts=2, |
| 148 | sleep=self._sleep, rng=lambda: 1.0) |
| 149 | self.assertEqual(ctx.exception.status, 429) |
| 150 | self.assertEqual(ctx.exception.attempts, 2) |
| 151 | |
| 152 | |
| 153 | class CircuitBreakerTests(unittest.TestCase): |
| 154 | |
| 155 | |
| 156 | |
| 157 | def setUp(self): |
| 158 | self.t = [0.0] |
| 159 | self.b = CircuitBreaker(threshold=2, cooldown_s=10, |
| 160 | clock=lambda: self.t[0]) |
| 161 | |
| 162 | def test_opens_after_threshold(self): |
| 163 | self.assertEqual(self.b.state, "closed") |
| 164 | self.b.record_failure() |
| 165 | self.assertEqual(self.b.state, "closed") |
| 166 | self.b.record_failure() |
| 167 | self.assertEqual(self.b.state, "open") |
| 168 | self.assertFalse(self.b.allow()) |
| 169 | |
| 170 | def test_open_breaker_fails_fast(self): |
| 171 | self.b.record_failure(); self.b.record_failure() |
| 172 | cagri = {"n": 0} |
| 173 | |
| 174 | def fn(): |
| 175 | cagri["n"] += 1 |
| 176 | return "ok" |
| 177 | |
| 178 | with self.assertRaises(LlmUnavailable): |
| 179 | call_with_retry(fn, is_retryable=_is_retryable, breaker=self.b) |
| 180 | self.assertEqual(cagri["n"], 0, "kesici açıkken sağlayıcı çağrıldı") |
| 181 | |
| 182 | def test_half_open_allows_exactly_one_probe(self): |
| 183 | self.b.record_failure(); self.b.record_failure() |
| 184 | self.t[0] = 11 |
| 185 | self.assertEqual(self.b.state, "half_open") |
| 186 | self.assertTrue(self.b.allow()) |
| 187 | self.assertFalse(self.b.allow(), "ikinci deneme de geçti") |
| 188 | |
| 189 | def test_success_closes_the_breaker(self): |
| 190 | self.b.record_failure(); self.b.record_failure() |
| 191 | self.t[0] = 11 |
| 192 | self.b.allow() |
| 193 | self.b.record_success() |
| 194 | self.assertEqual(self.b.state, "closed") |
| 195 | self.assertTrue(self.b.allow()) |
| 196 | |
| 197 | def test_failure_in_half_open_reopens(self): |
| 198 | self.b.record_failure(); self.b.record_failure() |
| 199 | self.t[0] = 11 |
| 200 | self.b.allow() |
| 201 | self.b.record_failure() |
| 202 | self.assertEqual(self.b.state, "open") |
| 203 | |
| 204 | def test_snapshot_exposes_state_for_readiness(self): |
| 205 | s = self.b.snapshot() |
| 206 | self.assertEqual(s["state"], "closed") |
| 207 | self.assertIn("threshold", s) |
| 208 | |
| 209 | |
| 210 | class TimeoutDefaultTests(unittest.TestCase): |
| 211 | def test_default_timeout_is_not_120(self): |
| 212 | |
| 213 | |
| 214 | self.assertLessEqual(DEFAULT_TIMEOUT, 60.0) |
| 215 | self.assertGreaterEqual(DEFAULT_TIMEOUT, 10.0) |
| 216 | |
| 217 | def test_breaker_threshold_is_sane(self): |
| 218 | self.assertGreaterEqual(BREAKER_THRESHOLD, 2) |
| 219 | |
| 220 | |
| 221 | class ServiceContractTests(unittest.TestCase): |
| 222 | |
| 223 | |
| 224 | |
| 225 | class _PatlayanGenerator: |
| 226 | def answer(self, *a, **kw): |
| 227 | raise LlmUnavailable("saglayici yok", status=429, attempts=3) |
| 228 | |
| 229 | def _service(self): |
| 230 | from src.service.handler import RagService |
| 231 | return RagService(self._PatlayanGenerator()) |
| 232 | |
| 233 | def test_chat_returns_typed_refusal_not_an_exception(self): |
| 234 | out = self._service().chat({"query": "DNA nedir?"}) |
| 235 | self.assertTrue(out["abstained"]) |
| 236 | self.assertEqual(out["reason"], "llm_unavailable") |
| 237 | self.assertEqual(out["citations"], []) |
| 238 | self.assertEqual(out["cost_usd"], 0.0) |
| 239 | |
| 240 | def test_user_message_is_turkish_and_actionable(self): |
| 241 | metin = self._service().chat({"query": "q"})["text"] |
| 242 | self.assertTrue(metin.strip()) |
| 243 | self.assertNotIn("Internal Server Error", metin) |
| 244 | self.assertIn("tekrar", metin.lower()) |
| 245 | |
| 246 | def test_contract_fields_are_all_present(self): |
| 247 | out = self._service().chat({"query": "q"}) |
| 248 | for alan in ("text", "abstained", "reason", "citations", |
| 249 | "used_source_ids", "cost_usd", "cache_hit"): |
| 250 | self.assertIn(alan, out, alan) |
| 251 | |
| 252 | |
| 253 | class GatewayBodyErrorTests(unittest.TestCase): |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | _SECENEK = {"choices": [{"message": {"content": "cevap"}}], "usage": {}} |
| 263 | |
| 264 | def _istemci(self, **kw): |
| 265 | with mock.patch.dict(os.environ, {"DEEPSEEK_API_KEY": "", |
| 266 | "NVIDIA_API_KEY": ""}): |
| 267 | return LLMClient(base_url="https://gecit/v1", api_key="k", |
| 268 | timeout=1.0, **kw) |
| 269 | |
| 270 | def _yama(self, yanitlar): |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | cagri = {"n": 0} |
| 277 | |
| 278 | def _say(req, timeout=None): |
| 279 | cagri["n"] += 1 |
| 280 | yanit = yanitlar[cagri["n"] - 1] |
| 281 | if isinstance(yanit, BaseException): |
| 282 | raise yanit |
| 283 | return yanit |
| 284 | |
| 285 | return (mock.patch("urllib.request.urlopen", side_effect=_say), |
| 286 | mock.patch("src.providers.resilience.backoff_delay", |
| 287 | return_value=0.0), cagri) |
| 288 | |
| 289 | def test_govdede_gecici_hata_yeniden_denenir(self): |
| 290 | |
| 291 | yanitlar = [_yanit({"error": {"message": "Upstream error from Nvidia: " |
| 292 | "Service temporarily overloaded", |
| 293 | "code": 503}}), |
| 294 | _yanit(self._SECENEK)] |
| 295 | p1, p2, cagri = self._yama(yanitlar) |
| 296 | with p1, p2: |
| 297 | self.assertEqual(self._istemci(max_attempts=3).chat("soru").text, "cevap") |
| 298 | self.assertEqual(cagri["n"], 2) |
| 299 | |
| 300 | def test_govdede_kalici_hata_ilk_denemede_biter(self): |
| 301 | |
| 302 | |
| 303 | yanitlar = [_yanit({"error": {"message": "model bulunamadi", "code": 400}})] |
| 304 | p1, p2, cagri = self._yama(yanitlar) |
| 305 | with p1, p2: |
| 306 | with self.assertRaises(LlmUnavailable) as ctx: |
| 307 | self._istemci(max_attempts=3).chat("soru") |
| 308 | self.assertEqual(cagri["n"], 1) |
| 309 | self.assertIn("model bulunamadi", str(ctx.exception)) |
| 310 | |
| 311 | def test_govdede_dizge_bicimi_hata_gecici_sayilir(self): |
| 312 | |
| 313 | yanitlar = [_yanit({"error": "temporary upstream failure"}), |
| 314 | _yanit(self._SECENEK)] |
| 315 | p1, p2, cagri = self._yama(yanitlar) |
| 316 | with p1, p2: |
| 317 | self.assertEqual(self._istemci(max_attempts=3).chat("soru").text, "cevap") |
| 318 | self.assertEqual(cagri["n"], 2) |
| 319 | |
| 320 | def test_gercek_http_5xx_hala_yeniden_denenir(self): |
| 321 | |
| 322 | yanitlar = [_http(503), _yanit(self._SECENEK)] |
| 323 | p1, p2, cagri = self._yama(yanitlar) |
| 324 | with p1, p2: |
| 325 | self.assertEqual(self._istemci(max_attempts=3).chat("soru").text, "cevap") |
| 326 | self.assertEqual(cagri["n"], 2) |
| 327 | |
| 328 | |
| 329 | if __name__ == "__main__": |
| 330 | unittest.main() |