forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

test_llm_failure_paths.py200 lines, 8.5 KiBHistoryRawDownload
1"""#M3-10 / #M4-4 (O-08, E-62, E-68) — LLM ARIZASI ÜRÜN YÜZEYİNDE.
2
3ÖLÇÜLEN DURUM (EXP-009, gerçek koşum): DeepSeek çağrılarının **%92'si HTTP
4429** döndü ve bir çağrı **300 s** sürdü. `urllib` zaman aşımı 120 s'ti —
5öğrenci iki dakika boş ekrana bakıyordu. `runner._retry` yalnız 2 deneme
6yapıyordu, backoff yoktu.
7
8`tests/unit/test_llm_resilience.py` MEKANİZMAYI ölçüyor (retry sınıflaması,
9backoff, devre kesici durum makinesi). BU DOSYA ÜRÜN YÜZEYİNİ ölçüyor:
10sağlayıcı çöktüğünde ÖĞRENCİ NE GÖRÜYOR, backend ne alıyor, maliyet ne
11oluyor. İkisi ayrı sorulardır: mekanizma doğru çalışıp yanıt yine de çıplak
12500 olarak dönebilir.
13"""
14import unittest
15
16from src.providers.resilience import CircuitBreaker, LlmUnavailable
17from src.service import RagService
18from src.service.handler import LLM_UNAVAILABLE_TEXT
19from tests.unit.test_service import _ANS, _GenStub, _doc
20
21# `_doc()` 12. sınıf / biyoloji üretir; özet ve soru uçları rol ister.
22ROLE = {"role": "student", "sinif": "12", "ders_list": ["biyoloji"]}
23
24
25class _FailingGen:
26 def __init__(self, error):
27 self.error = error
28 self.calls = 0
29
30 def answer(self, query, **kw):
31 self.calls += 1
32 raise self.error
33
34
35class _FailingSummarizer:
36 def __init__(self, error): self.error = error
37 def summarize(self, units, **kw): raise self.error
38
39
40class _FailingQuestionGen:
41 def __init__(self, error): self.error = error
42 def generate(self, units, **kw): raise self.error
43
44
45class ChatPathTests(unittest.TestCase):
46 def setUp(self):
47 self.error = LlmUnavailable("429 rate limited", status=429)
48
49 def test_response_is_contractual_not_a_raw_exception(self):
50 """Backend her durumda AYNI alanları bekler (API-CONTRACT). İstisna
51 yukarı sızarsa backend gövdeyi parse edemez ve öğrenciye teknik hata
52 metni gider."""
53 out = RagService(_FailingGen(self.error)).chat({"query": "fotosentez nedir"})
54 for field in ("text", "abstained", "reason", "citations",
55 "used_source_ids", "cost_usd", "cache_hit"):
56 self.assertIn(field, out, field)
57 self.assertTrue(out["abstained"])
58 self.assertEqual(out["reason"], "llm_unavailable")
59
60 def test_student_sees_turkish_non_technical_text(self):
61 out = RagService(_FailingGen(self.error)).chat({"query": "s"})
62 self.assertEqual(out["text"], LLM_UNAVAILABLE_TEXT)
63 for leak in ("429", "Traceback", "LlmUnavailable", "rate limited",
64 "Exception"):
65 self.assertNotIn(leak, out["text"], f"'{leak}' ogrenciye sizdi")
66
67 def test_failure_is_not_billed(self):
68 """Başarısız çağrı için para alınmaz; sayaç şişerse tavan haksız
69 yere dolar ve öğrenci ertesi gün de kullanamaz."""
70 svc = RagService(_FailingGen(self.error))
71 out = svc.chat({"query": "s", "user": "ogr1"})
72 self.assertEqual(out["cost_usd"], 0.0)
73 self.assertEqual(svc.budget.spent(user="ogr1"), 0.0)
74
75 def test_failure_invents_no_citations(self):
76 out = RagService(_FailingGen(self.error)).chat({"query": "s"})
77 self.assertEqual(out["citations"], [])
78 self.assertEqual(out["used_source_ids"], [])
79
80 def test_failure_is_not_reported_as_a_cache_hit(self):
81 out = RagService(_FailingGen(self.error)).chat({"query": "s"})
82 self.assertFalse(out["cache_hit"])
83
84 def test_timeout_takes_the_same_path(self):
85 out = RagService(_FailingGen(
86 LlmUnavailable("timeout", status=None))).chat({"query": "s"})
87 self.assertEqual(out["reason"], "llm_unavailable")
88
89 def test_unexpected_exception_is_not_swallowed(self):
90 """DÜRÜST SINIR: yalnız `LlmUnavailable` yakalanır. `KeyError` gibi
91 bir PROGRAM HATASI sessizce 'llm_unavailable' diye raporlanırsa gerçek
92 kusur gizlenir ve aylarca fark edilmez. Bu kasıtlı bir tercihtir;
93 HTTP katmanı onu 503'e çevirir."""
94 with self.assertRaises(KeyError):
95 RagService(_FailingGen(KeyError("kod hatasi"))).chat({"query": "s"})
96
97
98class SummaryAndQuestionPathTests(unittest.TestCase):
99 """Arıza yalnız `chat`'i değil her ucu vurur."""
100
101 def setUp(self):
102 self.error = LlmUnavailable("503", status=503)
103
104 def test_summary_failure_is_contractual(self):
105 svc = RagService(_GenStub(_ANS), doc=_doc(),
106 summarizer=_FailingSummarizer(self.error), ders="biyoloji")
107 out = svc.summarize({"scope": {"pages": [10]}, "role": ROLE})
108 self.assertTrue(out["abstained"])
109 self.assertEqual(out["reason"], "llm_unavailable")
110 self.assertEqual(out["citations"], [])
111 self.assertIn("scope_pages", out)
112
113 def test_question_failure_is_contractual(self):
114 svc = RagService(_GenStub(_ANS), doc=_doc(),
115 question_gen=_FailingQuestionGen(self.error), ders="biyoloji")
116 out = svc.generate_questions({"scope": {"pages": [10]}, "role": ROLE})
117 self.assertTrue(out["abstained"])
118 self.assertEqual(out["reason"], "llm_unavailable")
119 self.assertEqual(out["items"], [])
120
121 def test_missing_role_is_a_different_reason_than_a_failure(self):
122 """Yetki reddi ile sağlayıcı arızası aynı sebebi vermemeli; aksi hâlde
123 olay incelemesi yanlış yöne gider."""
124 svc = RagService(_GenStub(_ANS), doc=_doc(),
125 summarizer=_FailingSummarizer(self.error), ders="biyoloji")
126 out = svc.summarize({"scope": {"pages": [10]}})
127 self.assertEqual(out["reason"], "role_required")
128
129
130class BreakerProductEffectTests(unittest.TestCase):
131 """Sağlayıcı tamamen düştüğünde ürün BEKLEMEMELİ."""
132
133 def test_open_breaker_never_calls_the_provider(self):
134 """Kapanmış devrede her istek için 120 s beklemek, 30 öğrencilik
135 sınıfta thread havuzunu tüketir ve SAĞLAM uçlar da (health, özet)
136 cevap veremez hâle gelir."""
137 cb = CircuitBreaker(threshold=2, cooldown_s=60.0)
138 for _ in range(2):
139 cb.record_failure()
140 self.assertEqual(cb.state, "open")
141 self.assertFalse(cb.allow())
142
143 def test_half_open_allows_exactly_one_probe(self):
144 clock_t = [0.0]
145 cb = CircuitBreaker(threshold=1, cooldown_s=10.0, clock=lambda: clock_t[0])
146 cb.record_failure()
147 clock_t[0] = 11.0
148 self.assertTrue(cb.allow(), "kurtarma denemesi hic yapilmiyor")
149 self.assertFalse(cb.allow(), "yarim acikta sagligi coklu deneme sorguluyor")
150
151 def test_success_closes_the_breaker(self):
152 clock_t = [0.0]
153 cb = CircuitBreaker(threshold=1, cooldown_s=10.0, clock=lambda: clock_t[0])
154 cb.record_failure()
155 clock_t[0] = 11.0
156 cb.allow()
157 cb.record_success()
158 self.assertEqual(cb.state, "closed")
159 self.assertTrue(cb.allow())
160
161 def test_failure_while_half_open_reopens(self):
162 """Yalnız sayaç artırılsaydı bozuk sağlayıcı HER istekte yeni bir
163 deneme alırdı; devre kesici fiilen ölü olurdu."""
164 clock_t = [0.0]
165 cb = CircuitBreaker(threshold=1, cooldown_s=10.0, clock=lambda: clock_t[0])
166 cb.record_failure()
167 clock_t[0] = 11.0
168 cb.allow()
169 cb.record_failure()
170 self.assertEqual(cb.state, "open", "bekleme sayaci sifirlanmadi")
171
172 def test_state_is_exposed_for_readiness(self):
173 cb = CircuitBreaker(threshold=1, cooldown_s=60.0)
174 cb.record_failure()
175 self.assertEqual(cb.snapshot()["state"], "open")
176
177
178class PartialFailureTests(unittest.TestCase):
179 """Bazı uçlar çalışırken bazıları çökebilir."""
180
181 def test_summary_keeps_working_when_chat_is_down(self):
182 from src.summarize.summarizer import GroundedSummary
183 from tests.unit.test_service import _SumStub
184 svc = RagService(_FailingGen(LlmUnavailable("429", status=429)),
185 doc=_doc(),
186 summarizer=_SumStub(GroundedSummary(
187 text="ozet [1].", citations=[], cost_usd=0.0)),
188 ders="biyoloji")
189 self.assertTrue(svc.chat({"query": "s"})["abstained"])
190 self.assertFalse(
191 svc.summarize({"scope": {"pages": [10]}, "role": ROLE})["abstained"])
192
193 def test_missing_component_has_its_own_reason(self):
194 """'Bileşen kurulmadı' ile 'sağlayıcı çöktü' aynı şey değildir."""
195 out = RagService(_GenStub(_ANS)).summarize({"scope": {"pages": [10]}})
196 self.assertEqual(out["reason"], "summary_unavailable")
197
198
199if __name__ == "__main__":
200 unittest.main()