| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | import threading |
| 17 | import unittest |
| 18 | |
| 19 | from src.service.multi import (MultiCorpusService, _parse, book_path, |
| 20 | discover) |
| 21 | |
| 22 | _OKUL = "okul-a" |
| 23 | |
| 24 | |
| 25 | class _Doc: |
| 26 | def __init__(self, sinif, ders): |
| 27 | self.sinif, self.ders = sinif, ders |
| 28 | |
| 29 | |
| 30 | class _FakeService: |
| 31 | |
| 32 | |
| 33 | def __init__(self, sinif, ders): |
| 34 | self.doc = _Doc(sinif, ders) |
| 35 | self.ders = ders |
| 36 | self.generator = type("G", (), {"chunks_by_id": {"c1": 1}})() |
| 37 | self.calls = [] |
| 38 | |
| 39 | def chat(self, req): |
| 40 | self.calls.append(("chat", req)) |
| 41 | return {"text": f"{self.doc.sinif}/{self.ders}", "abstained": False, |
| 42 | "reason": "", "citations": [], "used_source_ids": [], |
| 43 | "cost_usd": 0.0, "cache_hit": False} |
| 44 | |
| 45 | def summarize(self, req): |
| 46 | return {"text": self.ders, "abstained": False, "reason": "", |
| 47 | "citations": [], "scope_pages": [], "hierarchical": False, |
| 48 | "cost_usd": 0.0} |
| 49 | |
| 50 | def generate_questions(self, req): |
| 51 | return {"items": [], "abstained": False, "reason": "", |
| 52 | "span_ids": [], "pages": [], "cost_usd": 0.0} |
| 53 | |
| 54 | |
| 55 | def _svc(specs=("10/biyoloji", "10/kimya", "10/fizik"), gecikme=0.0, |
| 56 | sayac=None): |
| 57 | |
| 58 | def _builder(yol, *, sinif, ders, shared=None, **kw): |
| 59 | if sayac is not None: |
| 60 | sayac.append((sinif, ders)) |
| 61 | if gecikme: |
| 62 | import time |
| 63 | time.sleep(gecikme) |
| 64 | return _FakeService(sinif, ders) |
| 65 | |
| 66 | s = MultiCorpusService(specs, school=_OKUL, shared=object(), |
| 67 | builder=_builder) |
| 68 | |
| 69 | s._specs = {k: __file__ for k in s._specs} |
| 70 | return s |
| 71 | |
| 72 | |
| 73 | |
| 74 | class GreetingRouteTests(unittest.TestCase): |
| 75 | def test_greeting_is_not_a_missing_corpus(self): |
| 76 | s = _svc() |
| 77 | out = s.chat({"query": "selam", "school": _OKUL, |
| 78 | "role": {"role": "admin"}, "scope": []}) |
| 79 | self.assertFalse(out["abstained"]) |
| 80 | self.assertNotEqual(out["reason"], "no_corpus") |
| 81 | self.assertNotIn("bulunamadı", out["text"]) |
| 82 | self.assertEqual(s.registry.keys(), []) |
| 83 | |
| 84 | def _bekle(s, sinif, ders, timeout=5.0): |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | import time |
| 91 | son = time.time() + timeout |
| 92 | while time.time() < son: |
| 93 | if s.registry.get(str(sinif), str(ders), school=_OKUL) is not None: |
| 94 | return True |
| 95 | if (str(sinif), str(ders)) in s._load_errors: |
| 96 | return False |
| 97 | time.sleep(0.01) |
| 98 | return False |
| 99 | |
| 100 | |
| 101 | ROL_BIO = {"role": "student", "sinif": "10", "ders_list": ["biyoloji"]} |
| 102 | ROL_COK = {"role": "student", "sinif": "10", |
| 103 | "ders_list": ["biyoloji", "kimya", "fizik"]} |
| 104 | |
| 105 | |
| 106 | class RoutingTests(unittest.TestCase): |
| 107 | def test_scope_selects_the_corpus(self): |
| 108 | s = _svc(); s.warm() |
| 109 | out = s.chat({"school": _OKUL, "query": "s", "scope": {"sinif": "10", "ders": "kimya"}, |
| 110 | "role": ROL_COK}) |
| 111 | self.assertEqual(out["text"], "10/kimya") |
| 112 | |
| 113 | def test_single_subject_role_needs_no_scope(self): |
| 114 | s = _svc(); s.warm() |
| 115 | self.assertEqual(s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO})["text"], |
| 116 | "10/biyoloji") |
| 117 | |
| 118 | def test_options_ders_is_honoured(self): |
| 119 | s = _svc(); s.warm() |
| 120 | out = s.chat({"school": _OKUL, "query": "s", "role": ROL_COK, |
| 121 | "options": {"ders": "fizik"}}) |
| 122 | self.assertEqual(out["text"], "10/fizik") |
| 123 | |
| 124 | def test_multi_subject_without_target_is_ambiguous_not_guessed(self): |
| 125 | |
| 126 | s = _svc(); s.warm() |
| 127 | out = s.chat({"school": _OKUL, "query": "s", "role": ROL_COK}) |
| 128 | self.assertTrue(out["abstained"]) |
| 129 | self.assertEqual(out["reason"], "corpus_ambiguous") |
| 130 | |
| 131 | def test_unknown_corpus_is_a_typed_refusal(self): |
| 132 | |
| 133 | s = _svc(); s.warm() |
| 134 | out = s.chat({"school": _OKUL, "query": "s", |
| 135 | "role": {"role": "student", "sinif": "10", |
| 136 | "ders_list": ["muzik"]}}) |
| 137 | self.assertEqual(out["reason"], "no_corpus") |
| 138 | |
| 139 | def test_refusal_text_is_turkish_and_actionable(self): |
| 140 | s = _svc(); s.warm() |
| 141 | for req, _ in (({"query": "s", "role": ROL_COK}, 0), |
| 142 | ({"query": "s", "role": {"sinif": "10", |
| 143 | "ders_list": ["muzik"]}}, 0)): |
| 144 | out = s.chat(req) |
| 145 | with self.subTest(reason=out["reason"]): |
| 146 | self.assertTrue(out["text"].strip()) |
| 147 | self.assertNotIn("corpus", out["text"].lower()) |
| 148 | |
| 149 | def test_refusal_has_the_full_contract(self): |
| 150 | |
| 151 | _s = _svc(); _s.warm() |
| 152 | out = _s.chat({"school": _OKUL, "query": "s", "role": ROL_COK}) |
| 153 | for alan in ("text", "abstained", "reason", "citations", |
| 154 | "used_source_ids", "cost_usd", "cache_hit"): |
| 155 | self.assertIn(alan, out, alan) |
| 156 | |
| 157 | def test_refusal_costs_nothing(self): |
| 158 | _s = _svc(); _s.warm() |
| 159 | self.assertEqual(_s.chat({"school": _OKUL, "query": "s", "role": ROL_COK})["cost_usd"], |
| 160 | 0.0) |
| 161 | |
| 162 | def test_summary_and_questions_route_too(self): |
| 163 | s = _svc(); s.warm() |
| 164 | self.assertEqual( |
| 165 | s.summarize({"school": _OKUL, "scope": {"sinif": "10", "ders": "kimya"}, |
| 166 | "role": ROL_COK})["text"], "kimya") |
| 167 | self.assertFalse( |
| 168 | s.generate_questions({"school": _OKUL, "scope": {"sinif": "10", "ders": "fizik"}, |
| 169 | "role": ROL_COK})["abstained"]) |
| 170 | |
| 171 | def test_routing_is_not_authorization(self): |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | s = _svc(); s.warm() |
| 177 | out = s.chat({"school": _OKUL, "query": "s", "scope": {"sinif": "10", "ders": "fizik"}, |
| 178 | "role": ROL_BIO}) |
| 179 | self.assertEqual(out["text"], "10/fizik", "yonlendirme kapsami izlemeli") |
| 180 | from src.guard.roles import Role, RoleContext, can_access |
| 181 | ctx = RoleContext(role=Role.STUDENT, sinif="10", ders_list=["biyoloji"]) |
| 182 | self.assertFalse(can_access(ctx, sinif="10", ders="fizik"), |
| 183 | "yetki katmani bu erisimi REDDETMELI") |
| 184 | |
| 185 | |
| 186 | class LazyLoadingTests(unittest.TestCase): |
| 187 | def test_nothing_is_built_until_asked(self): |
| 188 | |
| 189 | |
| 190 | |
| 191 | sayac = [] |
| 192 | s = _svc(sayac=sayac) |
| 193 | self.assertEqual(sayac, []) |
| 194 | self.assertEqual(s.loaded(), []) |
| 195 | |
| 196 | def test_cold_subject_answers_immediately_with_warming(self): |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | s = _svc(gecikme=0.2) |
| 202 | out = s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 203 | self.assertTrue(out["abstained"]) |
| 204 | self.assertEqual(out["reason"], "service_warming_up") |
| 205 | self.assertTrue(out["text"].strip()) |
| 206 | |
| 207 | def test_only_the_asked_corpus_is_built(self): |
| 208 | sayac, kilit = [], threading.Lock() |
| 209 | |
| 210 | def _builder(yol, *, sinif, ders, shared=None, **kw): |
| 211 | with kilit: |
| 212 | sayac.append((sinif, ders)) |
| 213 | return _FakeService(sinif, ders) |
| 214 | |
| 215 | s = _svc() |
| 216 | s._build = _builder |
| 217 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 218 | _bekle(s, "10", "biyoloji") |
| 219 | self.assertEqual(sayac, [("10", "biyoloji")]) |
| 220 | |
| 221 | def test_second_request_reuses_the_built_corpus(self): |
| 222 | sayac, kilit = [], threading.Lock() |
| 223 | |
| 224 | def _builder(yol, *, sinif, ders, shared=None, **kw): |
| 225 | with kilit: |
| 226 | sayac.append((sinif, ders)) |
| 227 | return _FakeService(sinif, ders) |
| 228 | |
| 229 | s = _svc() |
| 230 | s._build = _builder |
| 231 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 232 | self.assertTrue(_bekle(s, "10", "biyoloji")) |
| 233 | for _ in range(5): |
| 234 | out = s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 235 | self.assertEqual(len(sayac), 1) |
| 236 | self.assertFalse(out["abstained"], "kurulu korpus hala bekletiyor") |
| 237 | |
| 238 | def test_concurrent_first_requests_build_once(self): |
| 239 | |
| 240 | |
| 241 | sayac, kilit = [], threading.Lock() |
| 242 | guvenli = [] |
| 243 | |
| 244 | def _say(x): |
| 245 | with kilit: |
| 246 | guvenli.append(x) |
| 247 | |
| 248 | s = _svc(gecikme=0.05, sayac=None) |
| 249 | orj = s._build |
| 250 | |
| 251 | def _builder(yol, *, sinif, ders, shared=None, **kw): |
| 252 | _say((sinif, ders)) |
| 253 | return orj(yol, sinif=sinif, ders=ders, shared=shared, **kw) |
| 254 | |
| 255 | s._build = _builder |
| 256 | bariyer = threading.Barrier(8) |
| 257 | |
| 258 | def sor(): |
| 259 | bariyer.wait(timeout=10) |
| 260 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 261 | |
| 262 | ths = [threading.Thread(target=sor) for _ in range(8)] |
| 263 | for t in ths: |
| 264 | t.start() |
| 265 | for t in ths: |
| 266 | t.join(timeout=30) |
| 267 | _bekle(s, "10", "biyoloji") |
| 268 | self.assertEqual(len(guvenli), 1, f"korpus {len(guvenli)} kez kuruldu") |
| 269 | |
| 270 | def test_warm_builds_everything_upfront(self): |
| 271 | sayac = [] |
| 272 | s = _svc(sayac=sayac) |
| 273 | sonuc = s.warm() |
| 274 | self.assertEqual(len(sayac), 3) |
| 275 | self.assertTrue(all(sonuc.values())) |
| 276 | |
| 277 | def test_a_broken_corpus_is_not_retried_forever(self): |
| 278 | |
| 279 | |
| 280 | deneme = [] |
| 281 | |
| 282 | def _patlar(yol, *, sinif, ders, shared=None, **kw): |
| 283 | deneme.append((sinif, ders)) |
| 284 | raise RuntimeError("bozuk pdf") |
| 285 | |
| 286 | s = MultiCorpusService(["10/biyoloji"], school=_OKUL, shared=object(), |
| 287 | builder=_patlar) |
| 288 | s._specs = {k: __file__ for k in s._specs} |
| 289 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 290 | _bekle(s, "10", "biyoloji") |
| 291 | for _ in range(4): |
| 292 | out = s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 293 | self.assertEqual(len(deneme), 1, "bozuk korpus tekrar tekrar deneniyor") |
| 294 | self.assertEqual(out["reason"], "no_corpus") |
| 295 | |
| 296 | def test_missing_file_is_not_an_exception(self): |
| 297 | |
| 298 | s = MultiCorpusService(["10/olmayan-ders"], school=_OKUL, shared=object(), |
| 299 | builder=lambda *a, **k: _FakeService("10", "x")) |
| 300 | out = s.chat({"school": _OKUL, "query": "s", |
| 301 | "role": {"role": "student", "sinif": "10", |
| 302 | "ders_list": ["olmayan-ders"]}}) |
| 303 | self.assertEqual(out["reason"], "no_corpus") |
| 304 | self.assertEqual(s.building(), [], "var olmayan dosya icin thread acildi") |
| 305 | |
| 306 | def test_status_is_json_serialisable(self): |
| 307 | |
| 308 | import json |
| 309 | def _patlar(*a, **k): |
| 310 | raise RuntimeError("bozuk") |
| 311 | s = MultiCorpusService(["10/biyoloji"], school=_OKUL, shared=object(), |
| 312 | builder=_patlar) |
| 313 | s._specs = {k: __file__ for k in s._specs} |
| 314 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 315 | _bekle(s, "10", "biyoloji") |
| 316 | json.dumps(s.status()) |
| 317 | |
| 318 | |
| 319 | class StatusTests(unittest.TestCase): |
| 320 | def test_status_separates_known_from_loaded(self): |
| 321 | |
| 322 | |
| 323 | s = _svc() |
| 324 | d = s.status() |
| 325 | self.assertEqual(len(d["bilinen"]), 3) |
| 326 | self.assertEqual(d["yuklu"], []) |
| 327 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 328 | _bekle(s, "10", "biyoloji") |
| 329 | self.assertEqual(s.status()["yuklu"], [f"{_OKUL}/10/biyoloji"]) |
| 330 | |
| 331 | def test_load_errors_are_surfaced(self): |
| 332 | def _patlar(*a, **k): |
| 333 | raise RuntimeError("bozuk") |
| 334 | s = MultiCorpusService(["10/biyoloji"], school=_OKUL, shared=object(), |
| 335 | builder=_patlar) |
| 336 | s._specs = {k: __file__ for k in s._specs} |
| 337 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 338 | _bekle(s, "10", "biyoloji") |
| 339 | self.assertIn(f"{_OKUL}/10/biyoloji", s.status()["hatalar"]) |
| 340 | |
| 341 | def test_corpus_limit_is_a_deliberate_valve(self): |
| 342 | |
| 343 | |
| 344 | s = _svc() |
| 345 | s.registry.max_corpora = 1 |
| 346 | s.chat({"school": _OKUL, "query": "s", "role": ROL_BIO}) |
| 347 | _bekle(s, "10", "biyoloji") |
| 348 | s.chat({"school": _OKUL, "query": "s", "options": {"ders": "kimya"}, "role": ROL_COK}) |
| 349 | _bekle(s, "10", "kimya") |
| 350 | out = s.chat({"school": _OKUL, "query": "s", "options": {"ders": "kimya"}, |
| 351 | "role": ROL_COK}) |
| 352 | self.assertEqual(out["reason"], "no_corpus", |
| 353 | "sinir asilinca istisna sizdi (500) ya da sessizce gecti") |
| 354 | self.assertIn("limit", str(s.status()["hatalar"])) |
| 355 | |
| 356 | |
| 357 | class DiscoveryTests(unittest.TestCase): |
| 358 | def test_discover_finds_real_books(self): |
| 359 | bulunan = discover() |
| 360 | if not bulunan: |
| 361 | self.skipTest("bu makinede korpus yok") |
| 362 | self.assertTrue(all(len(x) == 2 for x in bulunan)) |
| 363 | self.assertEqual(bulunan, sorted(bulunan), "sira deterministik olmali") |
| 364 | |
| 365 | def test_book_path_shape(self): |
| 366 | yol = book_path("10", "kimya", school=_OKUL) |
| 367 | self.assertTrue(yol.endswith(f"{_OKUL}/lise/10/kimya/kitap.pdf"), yol) |
| 368 | |
| 369 | def test_bad_spec_is_refused(self): |
| 370 | for bozuk in ("bozuk", "", "10/", "/biyoloji", "Okul A/10/biyoloji", "a/b/c/d"): |
| 371 | with self.subTest(bozuk=bozuk): |
| 372 | with self.assertRaises(ValueError): |
| 373 | _parse(bozuk) |
| 374 | |
| 375 | |
| 376 | if __name__ == "__main__": |
| 377 | unittest.main() |
| 378 | |
| 379 | |
| 380 | class SharedModelsTests(unittest.TestCase): |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | def test_shared_models_resolve_their_dependencies(self): |
| 393 | from src.service.http_app import SharedModels |
| 394 | sm = SharedModels() |
| 395 | from src.embed.embedder import BGEM3Embedder |
| 396 | self.assertIsInstance(sm.embedder, BGEM3Embedder) |
| 397 | |
| 398 | def test_embedder_is_built_once(self): |
| 399 | |
| 400 | |
| 401 | from src.service.http_app import SharedModels |
| 402 | sm = SharedModels() |
| 403 | self.assertIs(sm.embedder, sm.embedder) |
| 404 | |
| 405 | def test_provider_symbols_are_module_level(self): |
| 406 | |
| 407 | |
| 408 | import src.service.http_app as m |
| 409 | for ad in ("build_embedder", "build_reranker", |
| 410 | "check_abstain_compatibility"): |
| 411 | self.assertTrue(hasattr(m, ad), f"{ad} modul seviyesinde degil") |
| 412 | |
| 413 | |
| 414 | class SerialBuildTests(unittest.TestCase): |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | |
| 426 | def test_builds_never_overlap(self): |
| 427 | import time |
| 428 | ayni_anda, en_fazla, kilit = [0], [0], threading.Lock() |
| 429 | |
| 430 | def _builder(yol, *, sinif, ders, shared=None, **kw): |
| 431 | with kilit: |
| 432 | ayni_anda[0] += 1 |
| 433 | en_fazla[0] = max(en_fazla[0], ayni_anda[0]) |
| 434 | time.sleep(0.05) |
| 435 | with kilit: |
| 436 | ayni_anda[0] -= 1 |
| 437 | return _FakeService(sinif, ders) |
| 438 | |
| 439 | s = _svc() |
| 440 | s._build = _builder |
| 441 | for ders in ("biyoloji", "kimya", "fizik"): |
| 442 | s.chat({"school": _OKUL, "query": "s", "options": {"ders": ders}, "role": ROL_COK}) |
| 443 | for ders in ("biyoloji", "kimya", "fizik"): |
| 444 | _bekle(s, "10", ders, timeout=10) |
| 445 | self.assertEqual(en_fazla[0], 1, |
| 446 | f"{en_fazla[0]} korpus AYNI ANDA kuruldu (segfault riski)") |
| 447 | self.assertEqual(len(s.loaded()), 3) |
| 448 | |
| 449 | def test_queries_are_not_blocked_by_a_build(self): |
| 450 | |
| 451 | |
| 452 | import time |
| 453 | s = _svc() |
| 454 | s.warm([("okul-a", "10", "biyoloji")]) |
| 455 | |
| 456 | def _yavas(yol, *, sinif, ders, shared=None, **kw): |
| 457 | time.sleep(0.3) |
| 458 | return _FakeService(sinif, ders) |
| 459 | |
| 460 | s._build = _yavas |
| 461 | s.chat({"school": _OKUL, "query": "s", "options": {"ders": "kimya"}, "role": ROL_COK}) |
| 462 | t0 = time.perf_counter() |
| 463 | out = s.chat({"school": _OKUL, "query": "s", "options": {"ders": "biyoloji"}, |
| 464 | "role": ROL_COK}) |
| 465 | gecen = time.perf_counter() - t0 |
| 466 | self.assertFalse(out["abstained"]) |
| 467 | self.assertLess(gecen, 0.2, "kurulum kilidi sorguyu bekletti") |
| 468 | |
| 469 | |
| 470 | class SharedModelsDeadlockTests(unittest.TestCase): |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | def test_reranker_after_embedder_does_not_deadlock(self): |
| 483 | import threading |
| 484 | |
| 485 | from src.service.http_app import SharedModels |
| 486 | sm = SharedModels() |
| 487 | sm._embedder = object() |
| 488 | sm._reranker = object() |
| 489 | |
| 490 | bitti = threading.Event() |
| 491 | |
| 492 | def _dokun(): |
| 493 | _ = sm.reranker |
| 494 | _ = sm.embedder |
| 495 | bitti.set() |
| 496 | |
| 497 | t = threading.Thread(target=_dokun, daemon=True) |
| 498 | t.start() |
| 499 | self.assertTrue(bitti.wait(timeout=5), |
| 500 | "SharedModels kilidi deadlock uretti") |
| 501 | |
| 502 | def test_lock_is_reentrant(self): |
| 503 | from src.service.http_app import SharedModels |
| 504 | sm = SharedModels() |
| 505 | with sm._lock: |
| 506 | with sm._lock: |
| 507 | pass |