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_budget.py197 lines, 8.2 KiBHistoryRawDownload
1"""#79 (EXP-010/OPS-05) — maliyet tavanı, ENGELLEYİCİ.
2
3ÖLÇÜLEN DURUM: `costlog.record()` yalnız **yazıyordu**; hiçbir çağıran dönüş
4değerine bakıp reddetmiyordu. Kullanıcı kotası, günlük USD tavanı yoktu.
5Ölçülen sömürü yolları:
6 * `/rag/questions n=100000` → şema kabul etti, handler'a 100000 olarak ulaştı
7 * `/rag/chat options={"top_n":100000,"candidate_n":100000}` → HTTP 200
8 * **tek istekte yüzlerce LLM çağrısı:** `scope.pages=[1..187]` özet
9İlk ikisi #48'de Pydantic sınırlarıyla kapandı; burası kalan iki katman.
10"""
11import unittest
12
13from src.budget import (BudgetGate, check_request_size, estimate_llm_calls)
14
15
16class CallEstimateTests(unittest.TestCase):
17 """Özyinelemeli hiyerarşik özet kaç çağrı yapar — İSTEK KABUL EDİLMEDEN."""
18
19 def test_small_scope_is_one_call(self):
20 for n in (1, 5, 12):
21 self.assertEqual(estimate_llm_calls(n), 1, n)
22
23 def test_just_over_the_group_size_needs_a_merge(self):
24 # 13 birim -> 2 ara-özet + 1 birleştirme
25 self.assertEqual(estimate_llm_calls(13), 3)
26
27 def test_the_measured_exploit_is_quantified(self):
28 """Denetimde ölçülen `scope.pages=[1..187]` senaryosu.
29
30 DİKKAT: 187 SAYFA, 187 birim değil. İlk testimde bunları karıştırıp
31 187'yi birim sanmıştım. Gerçek kitapla ölçüldü: 194 sayfa = 2.740
32 birim → **252 LLM çağrısı** ("onlarca-yüzlerce" iddiası doğrulandı)."""
33 self.assertEqual(estimate_llm_calls(2740), 252)
34 self.assertEqual(estimate_llm_calls(187), 19) # 187 BİRİM olsaydı
35
36 def test_empty_scope_is_zero(self):
37 self.assertEqual(estimate_llm_calls(0), 0)
38 self.assertEqual(estimate_llm_calls(-5), 0)
39
40 def test_group_size_changes_the_count(self):
41 self.assertGreater(estimate_llm_calls(100, 4), estimate_llm_calls(100, 12))
42
43
44class RequestSizeGateTests(unittest.TestCase):
45 def test_whole_book_is_rejected(self):
46 """Denetimdeki sömürü GERÇEK KİTAPLA ölçüldü: 194 sayfa = 2.740 birim,
47 58.649 token, **252 LLM çağrısı**."""
48 k = check_request_size(2740, n_tokens=58649)
49 self.assertFalse(k.allowed)
50 self.assertEqual(k.reason, "scope_too_large")
51
52 def test_normal_scope_passes(self):
53 self.assertTrue(check_request_size(12).allowed)
54 self.assertTrue(check_request_size(40).allowed)
55
56 def test_real_chapter_summaries_must_pass(self):
57 """REGRESYON KORUMASI — bu hatayı GERÇEKTEN yaptım.
58
59 İlk sürümde `MAX_UNITS_PER_REQUEST=60` idi çünkü "birim"i chunk
60 sanmıştım; oysa birim bir METİN BLOĞU (~11,6 blok/sayfa), yani 60
61 birim ≈ **5 sayfa**. Ürün gösteriminde **6 sayfalık normal bir özet
62 bile reddedildi** — çekirdek bir özelliği kırmıştım ve bunu ancak
63 gerçek koşumda gördüm.
64
65 Ölçülen gerçek değerler (10-biyoloji):
66 12 sayfa → 141 birim / 1.812 token / 13 çağrı
67 30 sayfa → 363 birim / 7.132 token / 35 çağrı
68 """
69 for sayfa, birim, token in ((6, 41, 796), (12, 141, 1812), (30, 363, 7132)):
70 with self.subTest(sayfa=sayfa):
71 k = check_request_size(birim, n_tokens=token)
72 self.assertTrue(k.allowed,
73 f"{sayfa} sayfalık normal özet reddedildi")
74
75 def test_token_ceiling_is_the_primary_measure(self):
76 """Para token'da harcanıyor; birim ve çağrı ucuz ön-elemedir."""
77 k = check_request_size(10, n_tokens=99_999)
78 self.assertFalse(k.allowed)
79 self.assertEqual(k.spent_usd, 99_999)
80
81 def test_token_check_is_skipped_when_not_provided(self):
82 self.assertTrue(check_request_size(10).allowed)
83
84 def test_unit_ceiling_is_enforced_separately_from_calls(self):
85 """İki ayrı tavan: birim sayısı VE çağrı sayısı. Biri diğerini
86 kapsamaz — küçük gruplarla az birim de çok çağrı üretebilir."""
87 k = check_request_size(30, max_units=20, max_calls=999)
88 self.assertFalse(k.allowed)
89 k2 = check_request_size(30, max_units=999, max_calls=2,
90 max_units_per_group=4)
91 self.assertFalse(k2.allowed)
92
93 def test_zero_disables_a_ceiling(self):
94 self.assertTrue(check_request_size(10_000, max_units=0, max_calls=0).allowed)
95
96
97class BudgetGateTests(unittest.TestCase):
98 def setUp(self):
99 self.g = BudgetGate(user_daily_usd=1.0, tenant_monthly_usd=10.0,
100 soft_ratio=0.8)
101
102 def test_empty_budget_allows(self):
103 self.assertTrue(self.g.check(user="u1").allowed)
104
105 def test_soft_threshold_warns_but_allows(self):
106 """Tek eşik yetmez: %80'de uyarmak operatöre zaman kazandırır,
107 %100'de reddetmek ürünü korur."""
108 self.g.record(0.85, user="u1")
109 k = self.g.check(user="u1")
110 self.assertTrue(k.allowed)
111 self.assertTrue(k.soft)
112
113 def test_hard_ceiling_denies(self):
114 self.g.record(1.05, user="u1")
115 k = self.g.check(user="u1")
116 self.assertFalse(k.allowed)
117 self.assertEqual(k.reason, "budget_exceeded")
118 self.assertEqual(k.scope, "user")
119
120 def test_one_user_does_not_block_another(self):
121 self.g.record(5.0, user="u1")
122 self.assertFalse(self.g.check(user="u1").allowed)
123 self.assertTrue(self.g.check(user="u2").allowed)
124
125 def test_tenant_ceiling_is_separate(self):
126 self.g.record(11.0, tenant="okul1")
127 self.assertFalse(self.g.check(tenant="okul1").allowed)
128 self.assertTrue(self.g.check(user="u1").allowed)
129
130 def test_daily_counter_resets_next_day(self):
131 import time
132 simdi = time.time()
133 self.g.record(2.0, user="u1", ts=simdi)
134 self.assertFalse(self.g.check(user="u1", ts=simdi).allowed)
135 self.assertTrue(self.g.check(user="u1", ts=simdi + 86400 * 2).allowed)
136
137 def test_zero_limit_means_disabled(self):
138 g = BudgetGate(user_daily_usd=0.0, tenant_monthly_usd=0.0)
139 g.record(999.0, user="u1")
140 self.assertTrue(g.check(user="u1").allowed)
141
142 def test_anonymous_request_is_not_charged(self):
143 """Kullanıcı kimliği yoksa sayaç tutulamaz; istek geçer. Bu bilinçli:
144 tavan bir GÜVENLİK kontrolü değil, maliyet kontrolüdür."""
145 self.g.record(5.0)
146 self.assertTrue(self.g.check().allowed)
147
148 def test_negative_and_zero_cost_ignored(self):
149 self.g.record(0.0, user="u1")
150 self.g.record(-3.0, user="u1")
151 self.assertEqual(self.g.spent(user="u1"), 0.0)
152
153
154class ServiceIntegrationTests(unittest.TestCase):
155 class _Gen:
156 def answer(self, *a, **kw):
157 class _A:
158 text = "cevap [1]"
159 citations = [{"n": 1, "chunk_id": "c1", "span_ids": ["s1"],
160 "pages": [1], "ders": "biyoloji"}]
161 used_source_ids = ["c1"]
162 invalid_citations = []
163 abstained = False
164 reason = ""
165 cost_usd = 0.60
166 cache_hit = False
167 return _A()
168
169 def _svc(self, **kw):
170 from src.service.handler import RagService
171 return RagService(self._Gen(), budget=BudgetGate(**kw))
172
173 def test_chat_is_denied_after_the_ceiling(self):
174 s = self._svc(user_daily_usd=1.0)
175 self.assertFalse(s.chat({"query": "q", "user": "u1"})["abstained"])
176 self.assertFalse(s.chat({"query": "q", "user": "u1"})["abstained"])
177 ucuncu = s.chat({"query": "q", "user": "u1"}) # 1.20 > 1.00
178 self.assertTrue(ucuncu["abstained"])
179 self.assertEqual(ucuncu["reason"], "budget_exceeded")
180
181 def test_denial_message_is_turkish_and_contract_shaped(self):
182 s = self._svc(user_daily_usd=0.01)
183 s.chat({"query": "q", "user": "u1"})
184 out = s.chat({"query": "q", "user": "u1"})
185 self.assertTrue(out["text"].strip())
186 self.assertEqual(out["cost_usd"], 0.0)
187 for alan in ("citations", "used_source_ids", "cache_hit"):
188 self.assertIn(alan, out)
189
190 def test_spend_is_recorded_only_after_a_real_answer(self):
191 s = self._svc(user_daily_usd=10.0)
192 s.chat({"query": "q", "user": "u1"})
193 self.assertAlmostEqual(s.budget.spent(user="u1"), 0.60)
194
195
196if __name__ == "__main__":
197 unittest.main()