| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | import threading |
| 18 | import unittest |
| 19 | |
| 20 | from src.budget import BudgetGate |
| 21 | from src.generate.generator import _role_cache_key |
| 22 | from src.guard.roles import Role, RoleContext |
| 23 | from src.service import RagService |
| 24 | from src.service.registry import CorpusRegistry |
| 25 | from tests.unit.test_service import _ANS, _GenStub |
| 26 | |
| 27 | |
| 28 | def _run_concurrently(fn, n=20): |
| 29 | |
| 30 | errors, lock = [], threading.Lock() |
| 31 | barrier = threading.Barrier(n) |
| 32 | |
| 33 | def wrapped(i): |
| 34 | try: |
| 35 | barrier.wait(timeout=10) |
| 36 | fn(i) |
| 37 | except Exception as e: |
| 38 | with lock: |
| 39 | errors.append(repr(e)) |
| 40 | |
| 41 | threads = [threading.Thread(target=wrapped, args=(i,)) for i in range(n)] |
| 42 | for t in threads: |
| 43 | t.start() |
| 44 | for t in threads: |
| 45 | t.join(timeout=30) |
| 46 | return errors |
| 47 | |
| 48 | |
| 49 | class BudgetCounterTests(unittest.TestCase): |
| 50 | |
| 51 | |
| 52 | def test_concurrent_records_are_not_lost(self): |
| 53 | g = BudgetGate(user_daily_usd=1e9, tenant_monthly_usd=1e9) |
| 54 | errors = _run_concurrently(lambda i: [g.record(0.001, user="ogr1") for _ in range(50)], |
| 55 | n=20) |
| 56 | self.assertEqual(errors, []) |
| 57 | self.assertAlmostEqual(g.spent(user="ogr1"), 20 * 50 * 0.001, places=6) |
| 58 | |
| 59 | def test_users_do_not_consume_each_others_budget(self): |
| 60 | g = BudgetGate(user_daily_usd=1e9, tenant_monthly_usd=1e9) |
| 61 | _run_concurrently(lambda i: [g.record(0.01, user=f"ogr{i}") for _ in range(10)], n=20) |
| 62 | for i in range(20): |
| 63 | self.assertAlmostEqual(g.spent(user=f"ogr{i}"), 0.1, places=6) |
| 64 | |
| 65 | def test_tenant_cap_is_shared_user_cap_is_not(self): |
| 66 | |
| 67 | g = BudgetGate(user_daily_usd=1e9, tenant_monthly_usd=1e9) |
| 68 | _run_concurrently(lambda i: g.record(0.05, user=f"ogr{i}", tenant="okul-A"), n=20) |
| 69 | self.assertAlmostEqual(g.spent(tenant="okul-A"), 1.0, places=6) |
| 70 | self.assertAlmostEqual(g.spent(user="ogr0"), 0.05, places=6) |
| 71 | |
| 72 | def test_no_thread_passes_once_the_cap_is_exceeded(self): |
| 73 | g = BudgetGate(user_daily_usd=0.10, tenant_monthly_usd=1e9) |
| 74 | g.record(0.10, user="ogr1") |
| 75 | decisions, lock = [], threading.Lock() |
| 76 | |
| 77 | def ask(i): |
| 78 | k = g.check(user="ogr1") |
| 79 | with lock: |
| 80 | decisions.append(k.allowed) |
| 81 | |
| 82 | self.assertEqual(_run_concurrently(ask, n=20), []) |
| 83 | self.assertEqual(decisions, [False] * 20) |
| 84 | |
| 85 | def test_cap_race_reports_the_right_reason(self): |
| 86 | g = BudgetGate(user_daily_usd=0.01, tenant_monthly_usd=1e9) |
| 87 | g.record(1.0, user="ogr1") |
| 88 | k = g.check(user="ogr1") |
| 89 | self.assertFalse(k.allowed) |
| 90 | self.assertEqual(k.reason, "budget_exceeded") |
| 91 | self.assertEqual(k.scope, "user") |
| 92 | |
| 93 | |
| 94 | class ConcurrentServiceTests(unittest.TestCase): |
| 95 | |
| 96 | |
| 97 | def test_twenty_students_at_once_see_no_error(self): |
| 98 | svc = RagService(_GenStub(_ANS), |
| 99 | budget=BudgetGate(user_daily_usd=1e9, tenant_monthly_usd=1e9)) |
| 100 | |
| 101 | def ask(i): |
| 102 | out = svc.chat({"query": f"soru {i}", "user": f"ogr{i}", |
| 103 | "school": "okul-a", |
| 104 | "role": {"role": "student", "sinif": "10", |
| 105 | "ders_list": ["biyoloji"]}}) |
| 106 | assert out["text"], "bos cevap" |
| 107 | |
| 108 | self.assertEqual(_run_concurrently(ask, n=20), []) |
| 109 | |
| 110 | def test_each_request_gets_its_own_request_id(self): |
| 111 | |
| 112 | |
| 113 | svc = RagService(_GenStub(_ANS), |
| 114 | budget=BudgetGate(user_daily_usd=1e9, tenant_monthly_usd=1e9)) |
| 115 | ids, lock = [], threading.Lock() |
| 116 | |
| 117 | def ask(i): |
| 118 | out = svc.chat({"query": f"soru {i}", "user": f"ogr{i}"}) |
| 119 | with lock: |
| 120 | ids.append(out.get("request_id")) |
| 121 | |
| 122 | self.assertEqual(_run_concurrently(ask, n=20), []) |
| 123 | self.assertEqual(len(set(ids)), 20, "request_id cakisti") |
| 124 | self.assertNotIn(None, ids) |
| 125 | |
| 126 | def test_supplied_request_id_is_preserved(self): |
| 127 | |
| 128 | svc = RagService(_GenStub(_ANS)) |
| 129 | out = svc.chat({"query": "s", "request_id": "backend-abc-123"}) |
| 130 | self.assertEqual(out["request_id"], "backend-abc-123") |
| 131 | |
| 132 | def test_budget_denial_does_not_spill_under_concurrency(self): |
| 133 | |
| 134 | svc = RagService(_GenStub(_ANS), |
| 135 | budget=BudgetGate(user_daily_usd=0.5, tenant_monthly_usd=1e9)) |
| 136 | svc.budget.record(10.0, user="dolu") |
| 137 | outcome, lock = {}, threading.Lock() |
| 138 | |
| 139 | def ask(i): |
| 140 | kim = "dolu" if i % 2 == 0 else f"ogr{i}" |
| 141 | out = svc.chat({"query": "s", "user": kim}) |
| 142 | with lock: |
| 143 | outcome.setdefault(kim, []).append(out.get("reason", "")) |
| 144 | |
| 145 | self.assertEqual(_run_concurrently(ask, n=20), []) |
| 146 | self.assertTrue(all(r == "budget_exceeded" for r in outcome["dolu"])) |
| 147 | for kim, rs in outcome.items(): |
| 148 | if kim != "dolu": |
| 149 | self.assertTrue(all(r == "" for r in rs), f"{kim} wrong reddedildi") |
| 150 | |
| 151 | |
| 152 | class CrossTenantLeakTests(unittest.TestCase): |
| 153 | |
| 154 | |
| 155 | def test_same_question_different_grade_is_a_different_key(self): |
| 156 | a = _role_cache_key(RoleContext(Role.STUDENT, "10", ["biyoloji"])) |
| 157 | b = _role_cache_key(RoleContext(Role.STUDENT, "11", ["biyoloji"])) |
| 158 | self.assertNotEqual(a, b) |
| 159 | |
| 160 | def test_registry_survives_concurrent_registration(self): |
| 161 | class _Doc: |
| 162 | def __init__(self, s, d): self.sinif, self.ders = s, d |
| 163 | |
| 164 | class _Svc: |
| 165 | def __init__(self, s, d): |
| 166 | self.school = "okul-a" |
| 167 | self.doc, self.ders = _Doc(s, d), d |
| 168 | self.generator = type("G", (), {"chunks_by_id": {}})() |
| 169 | |
| 170 | r = CorpusRegistry() |
| 171 | errors = _run_concurrently(lambda i: r.register(_Svc("10", f"ders{i}")), n=20) |
| 172 | self.assertEqual(errors, []) |
| 173 | self.assertEqual(len(r), 20) |
| 174 | |
| 175 | def test_concurrent_routing_returns_the_right_corpus(self): |
| 176 | class _Doc: |
| 177 | def __init__(self, s, d): self.sinif, self.ders = s, d |
| 178 | |
| 179 | class _Svc: |
| 180 | def __init__(self, s, d): |
| 181 | self.school = "okul-a" |
| 182 | self.doc, self.ders = _Doc(s, d), d |
| 183 | self.generator = type("G", (), {"chunks_by_id": {}})() |
| 184 | self.label = f"{s}/{d}" |
| 185 | |
| 186 | r = CorpusRegistry() |
| 187 | for i in range(10): |
| 188 | r.register(_Svc("10", f"ders{i}")) |
| 189 | wrong, lock = [], threading.Lock() |
| 190 | |
| 191 | def ask(i): |
| 192 | d = f"ders{i % 10}" |
| 193 | svc, _ = r.resolve({"school": "okul-a", "scope": {"sinif": "10", "ders": d}}) |
| 194 | if svc is None or svc.label != f"10/{d}": |
| 195 | with lock: |
| 196 | wrong.append(d) |
| 197 | |
| 198 | self.assertEqual(_run_concurrently(ask, n=20), []) |
| 199 | self.assertEqual(wrong, [], "eszamanli yonlendirme wrong korpusa gitti") |
| 200 | |
| 201 | |
| 202 | class ModelLoadRaceTests(unittest.TestCase): |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | def test_lazy_loading_behaves_consistently(self): |
| 208 | from src.service.http_app import _LazyService |
| 209 | ls = _LazyService() |
| 210 | outcome, lock = [], threading.Lock() |
| 211 | |
| 212 | def ask(i): |
| 213 | try: |
| 214 | ls.chat({"query": "s"}) |
| 215 | with lock: |
| 216 | outcome.append("ok") |
| 217 | except Exception as e: |
| 218 | with lock: |
| 219 | outcome.append(type(e).__name__) |
| 220 | |
| 221 | self.assertEqual(_run_concurrently(ask, n=20), []) |
| 222 | |
| 223 | |
| 224 | self.assertEqual(len(set(outcome)), 1, f"eszamanli davranis tutarsiz: {set(outcome)}") |
| 225 | |
| 226 | |
| 227 | if __name__ == "__main__": |
| 228 | unittest.main() |