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_summarize.py455 lines, 19.1 KiBHistoryRawDownload
1"""Özet ÇIKARMA mimarisi birim testleri (src/summarize/) — soru-cevaptan AYRI.
2
3Model/ağ GEREKMEZ: DeepSeek STUB'lanır (gerçek DeepSeek/costlog dosyasına ASLA
4yazılmaz). Odak: (1) `resolve_scope` sayfa/span_id kapsamını DETERMİNİSTİK
5çözüyor + retrieval_disi hariç tutuyor, (2) prompt numaralı kaynak blokları +
6detay/atıf talimatı içeriyor, (3) FAIL-CLOSED (boş kapsamda LLM HİÇ çağrılmıyor),
7(4) tek-geçiş atıf eşleme, (5) hiyerarşik (RAPTOR-benzeri) akış + atıf taşıma,
8(6) cost_recorder'a doğru module ile çağrı yapıldığı.
9"""
10from __future__ import annotations
11
12import unittest
13from dataclasses import dataclass, field
14
15from src.providers.llm import ChatResult
16from src.pricing import Usage
17from src.summarize import GroundedSummary, Summarizer, build_summary_prompt, resolve_scope
18from src.summarize.prompt import NO_CONTENT_SENTENCE
19
20
21# --------------------------------------------------------------------------- stub'lar
22
23@dataclass
24class _Unit:
25 """CanonicalUnit'in resolve_scope/summarizer için gereken minimum arayüzü.
26 Gerçek `build_canonical` ÇALIŞTIRILMAZ — saf, elle kurulan stub."""
27 span_id: str
28 page: int
29 text: str
30 retrieval_disi: bool = False
31
32 @property
33 def retrievable(self) -> bool:
34 return not self.retrieval_disi
35
36
37@dataclass
38class _Doc:
39 """CanonicalDoc'un resolve_scope için gereken minimum arayüzü (yalnız `.units`)."""
40 units: list = field(default_factory=list)
41
42
43class _StubLLMClient:
44 """chat() sabit metin (veya çağrı-sırasına göre metin listesi) + sabit Usage
45 döndürür; çağrı sayacı + gönderilen promptları tutar."""
46
47 def __init__(self, text="Özet [1].", texts=None, model="deepseek-chat"):
48 self.text = text
49 self._texts = list(texts) if texts is not None else None
50 self.model = model
51 self.calls = 0
52 self.last_prompt = None
53 self.last_system = None
54 self.prompts: list[str] = []
55
56 def chat(self, prompt, system=None, *, temperature=0.3, max_tokens=None, extra=None):
57 self.calls += 1
58 self.last_prompt = prompt
59 self.last_system = system
60 self.prompts.append(prompt)
61 if self._texts is not None:
62 text = self._texts[min(self.calls - 1, len(self._texts) - 1)]
63 else:
64 text = self.text
65 return ChatResult(text=text, usage=Usage(input_cache_hit=0, input_cache_miss=10,
66 output=5, reasoning=0),
67 model=self.model, latency_s=0.001)
68
69
70def _noop_recorder(**kwargs):
71 """costlog.record yerine geçer — gerçek Obsidian deftere YAZMAZ (yalnız birim test)."""
72 return {"cost_usd": 0.0}
73
74
75def _five_units():
76 return [
77 _Unit("s1", 1, "metin1"),
78 _Unit("s2", 2, "metin2"),
79 _Unit("s3", 3, "metin3"),
80 _Unit("s4", 4, "metin4"),
81 _Unit("s5", 5, "metin5"),
82 ]
83
84
85# --------------------------------------------------------------------------- resolve_scope
86
87class ResolveScopeTests(unittest.TestCase):
88 def _doc(self):
89 units = [
90 _Unit("s1", 1, "metin1"),
91 _Unit("s2", 2, "metin2"),
92 _Unit("s3", 3, "metin3"),
93 _Unit("s3b", 3, "gizli-metin", retrieval_disi=True), # indekse/özete girmez
94 _Unit("s4", 4, "metin4"),
95 _Unit("s5", 5, "metin5"),
96 ]
97 return _Doc(units=units)
98
99 def test_page_range_returns_matching_units_in_read_order(self):
100 doc = self._doc()
101 out = resolve_scope(doc, pages=[2, 3])
102 self.assertEqual([u.span_id for u in out], ["s2", "s3"]) # s3b (retrieval_disi) HARİÇ
103
104 def test_span_ids_returns_matching_units_in_read_order(self):
105 doc = self._doc()
106 out = resolve_scope(doc, span_ids=["s5", "s1"]) # sırasız verilse de okuma sırası korunur
107 self.assertEqual([u.span_id for u in out], ["s1", "s5"])
108
109 def test_pages_and_span_ids_combined_are_union(self):
110 doc = self._doc()
111 out = resolve_scope(doc, pages=[1], span_ids=["s4"])
112 self.assertEqual([u.span_id for u in out], ["s1", "s4"])
113
114 def test_retrieval_disi_unit_excluded_even_if_page_matches(self):
115 doc = self._doc()
116 out = resolve_scope(doc, pages=[3])
117 self.assertEqual([u.span_id for u in out], ["s3"])
118 self.assertNotIn("s3b", [u.span_id for u in out])
119
120 def test_no_scope_given_returns_empty_list(self):
121 doc = self._doc()
122 self.assertEqual(resolve_scope(doc), [])
123 self.assertEqual(resolve_scope(doc, pages=None, span_ids=None), [])
124
125 def test_empty_scope_args_return_empty_list(self):
126 doc = self._doc()
127 self.assertEqual(resolve_scope(doc, pages=[], span_ids=[]), [])
128
129 def test_scope_matching_nothing_returns_empty_list(self):
130 doc = self._doc()
131 self.assertEqual(resolve_scope(doc, pages=[999]), [])
132
133
134# --------------------------------------------------------------------------- prompt
135
136class BuildSummaryPromptTests(unittest.TestCase):
137 def test_sources_numbered_with_pages_and_detail_citation_instructions(self):
138 blocks = [
139 {"n": 1, "page": 10, "text": "DNA çift sarmaldır."},
140 {"n": 2, "page": 25, "text": "Fotosentez ışığa bağlıdır."},
141 ]
142 system, user = build_summary_prompt(blocks, scope_label="s.10-25")
143
144 self.assertIn("[Kaynak 1 | s.10]", user)
145 self.assertIn("DNA çift sarmaldır.", user)
146 self.assertIn("[Kaynak 2 | s.25]", user)
147 self.assertIn("Fotosentez ışığa bağlıdır.", user)
148 self.assertIn("KAPSAM: s.10-25", user)
149
150 # sistem promptu: detay talimatı + [N] atıf formatı + içerik-yok cümlesi
151 self.assertIn("DETAYLI", system)
152 self.assertIn("[N]", system)
153 self.assertIn(NO_CONTENT_SENTENCE, system)
154
155 def test_missing_page_falls_back_to_placeholder(self):
156 blocks = [{"n": 1, "page": None, "text": "metin"}]
157 _, user = build_summary_prompt(blocks)
158 self.assertIn("[Kaynak 1 | s.?]", user)
159
160 def test_no_scope_label_omits_kapsam_line(self):
161 blocks = [{"n": 1, "page": 1, "text": "metin"}]
162 _, user = build_summary_prompt(blocks)
163 self.assertNotIn("KAPSAM:", user)
164
165
166# --------------------------------------------------------------------------- summarize: FAIL-CLOSED
167
168class FailClosedTests(unittest.TestCase):
169 def test_empty_units_abstains_without_calling_llm(self):
170 ds = _StubLLMClient()
171 summarizer = Summarizer(ds, cost_recorder=_noop_recorder)
172
173 result = summarizer.summarize([])
174
175 self.assertIsInstance(result, GroundedSummary)
176 self.assertTrue(result.abstained)
177 self.assertEqual(result.reason, "empty_scope")
178 self.assertEqual(result.text, NO_CONTENT_SENTENCE)
179 self.assertEqual(result.cost_usd, 0.0)
180 self.assertEqual(result.citations, [])
181 self.assertEqual(result.n_source_units, 0)
182 self.assertFalse(result.hierarchical)
183 self.assertEqual(ds.calls, 0, "LLM ÇAĞRILMAMALI (boş kapsam)")
184
185 def test_cost_recorder_not_called_on_empty_scope(self):
186 calls = []
187
188 def spy(**kwargs):
189 calls.append(kwargs)
190 return {"cost_usd": 0.0}
191
192 ds = _StubLLMClient()
193 summarizer = Summarizer(ds, cost_recorder=spy)
194 summarizer.summarize([])
195
196 self.assertEqual(calls, [])
197
198
199# --------------------------------------------------------------------------- summarize: tek geçiş
200
201class SinglePassTests(unittest.TestCase):
202 def test_single_pass_citations_map_to_correct_span_and_page(self):
203 units = [
204 _Unit("s1", 10, "DNA çift sarmal yapıya sahiptir."),
205 _Unit("s2", 25, "Fotosentez ışığa bağlı bir tepkimedir."),
206 ]
207 ds = _StubLLMClient(text="DNA hakkında özet [1]. Fotosentez hakkında özet [2].")
208 summarizer = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=12)
209
210 result = summarizer.summarize(units, scope_label="s.10-25")
211
212 self.assertFalse(result.abstained)
213 self.assertFalse(result.hierarchical)
214 self.assertEqual(ds.calls, 1)
215 self.assertEqual(result.n_source_units, 2)
216 self.assertEqual(result.scope_pages, [10, 25])
217
218 c_by_n = {c["n"]: c for c in result.citations}
219 self.assertEqual(len(c_by_n), 2)
220 self.assertEqual(c_by_n[1]["span_ids"], ["s1"])
221 self.assertEqual(c_by_n[1]["pages"], [10])
222 self.assertEqual(c_by_n[2]["span_ids"], ["s2"])
223 self.assertEqual(c_by_n[2]["pages"], [25])
224
225 self.assertGreater(result.cost_usd, 0.0)
226 self.assertIsNotNone(result.usage)
227 self.assertIn("[Kaynak 1 | s.10]", ds.last_prompt)
228 self.assertIn("[Kaynak 2 | s.25]", ds.last_prompt)
229
230 def test_phantom_citation_silently_dropped_without_crashing(self):
231 units = [_Unit("s1", 1, "metin1")]
232 ds = _StubLLMClient(text="Bir özet [1] ve hayali [9].")
233 summarizer = Summarizer(ds, cost_recorder=_noop_recorder)
234
235 result = summarizer.summarize(units)
236
237 self.assertFalse(result.abstained)
238 self.assertEqual(len(result.citations), 1)
239 self.assertEqual(result.citations[0]["n"], 1)
240
241 def test_comma_and_adjacent_bracket_citation_forms_parsed(self):
242 units = [_Unit("s1", 1, "m1"), _Unit("s2", 2, "m2"),
243 _Unit("s3", 3, "m3"), _Unit("s4", 4, "m4")]
244 ds = _StubLLMClient(text="X [1, 2]. Y [3][4].")
245 summarizer = Summarizer(ds, cost_recorder=_noop_recorder)
246
247 result = summarizer.summarize(units)
248
249 self.assertEqual({c["n"] for c in result.citations}, {1, 2, 3, 4})
250
251
252# --------------------------------------------------------------------------- summarize: hiyerarşik
253
254class HierarchicalTests(unittest.TestCase):
255 def test_hierarchical_triggered_above_max_units_per_group(self):
256 units = _five_units()
257 texts = [
258 "Grup1 özeti [1][2].", # group 1: units s1,s2
259 "Grup2 özeti [1].", # group 2: units s3,s4 -> yalnız ilkine (s3) atıf
260 "Grup3 özeti [1].", # group 3: unit s5
261 "Nihai özet [1][2][3].", # birleştirme: 3 ara-özete atıf
262 ]
263 ds = _StubLLMClient(texts=texts)
264 summarizer = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=2)
265
266 result = summarizer.summarize(units)
267
268 self.assertTrue(result.hierarchical)
269 self.assertFalse(result.abstained)
270 self.assertEqual(result.n_source_units, 5)
271 self.assertEqual(result.scope_pages, [1, 2, 3, 4, 5])
272 # AUDIT EXP-007 #30 (RAPTOR-proper): max_units_per_group=2 iken 3 ara-özet 2'yi
273 # aştığından ÖZYİNELEMELİ birleştirme olur (tek merge DEĞİL) → çağrı sayısı
274 # artar; sabit 4 varsaymıyoruz. INVARIANT'ları test ediyoruz:
275 self.assertGreaterEqual(ds.calls, 4) # en az 3 leaf + 1 merge; özyinelemede daha çok
276
277 # ATIF BÜTÜNLÜĞÜ: tüm atıflı span'lar leaf span'lardan olmalı (uydurma YOK),
278 # gerçekten atıflanan s1,s2,s3,s5; s4 (hiç atıflanmadı) ve hayalet span YOK.
279 cited = {sid for c in result.citations for sid in c["span_ids"]}
280 self.assertTrue(result.citations)
281 self.assertTrue(cited)
282 self.assertTrue(cited <= {"s1", "s2", "s3", "s5"}) # leaf-anchored, s4/hayalet yok
283 self.assertNotIn("s4", cited)
284
285 self.assertGreater(result.cost_usd, 0.0)
286 self.assertIsNotNone(result.usage)
287 # birleşik usage: TÜM gerçek çağrıların toplamı (her biri output=5)
288 self.assertEqual(result.usage.output, ds.calls * 5)
289
290 def test_hierarchical_drops_group_with_no_valid_citation(self):
291 # KANITLI ÖZET bütünlüğü: bir grup kendi biriminde HİÇ atıf yapmazsa nihai
292 # atıf listesine EKLENMEZ (boş atıf = sahte/anlamsız kanıt; v1 testinde 143
293 # birim için 2 atıftan biri boş çıkmıştı).
294 #
295 # DÜZELTME (#55, 2026-09-11): bu testin eski açıklaması "atıf listesi =
296 # özetin dayandığı TÜM kanıt grupları (yalnız merge-LLM'in [N]'lediği
297 # değil)" diyordu — o cümle HATANIN KENDİSİNİ sözleşme olarak kaydediyordu.
298 # Artık kural tek-geçiş yolundakiyle aynı: yalnız modelin GERÇEKTEN
299 # atıfladığı [N]'ler çıktıya girer. Bu test o kuralla da geçer çünkü
300 # merge yalnız [2]'yi atıflıyor.
301 units = [_Unit("s1", 1, "m1"), _Unit("s2", 2, "m2"), _Unit("s3", 3, "m3")]
302 texts = [
303 NO_CONTENT_SENTENCE, # grup1 (s1,s2): atıf yok -> ATLANIR
304 "Grup2 özeti [1].", # grup2 (s3): atıflı -> KALIR
305 "Nihai özet [2].", # birleştirme
306 ]
307 ds = _StubLLMClient(texts=texts)
308 summarizer = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=2)
309
310 result = summarizer.summarize(units)
311
312 self.assertTrue(result.hierarchical)
313 c_by_n = {c["n"]: c for c in result.citations}
314 self.assertNotIn(1, c_by_n) # boş-kanıtlı grup1 atlandı
315 self.assertEqual(c_by_n[2]["span_ids"], ["s3"]) # kanıtlı grup2 kaldı
316 self.assertEqual(c_by_n[2]["pages"], [3])
317
318
319class HierarchicalCitationFabricationTests(unittest.TestCase):
320 """#55 (EXP-010/ACC-01) — hiyerarşik özet MODELİN YAPMADIĞI atıfları döndürüyordu.
321
322 `_merge_summaries` nihai metni alıyor ama `_parse_citation_ns(result.text)`
323 ÇAĞIRMIYORDU; `citations` doğrudan `merge_lookup.items()`'tan, yani *kanıtı
324 olan TÜM ara-özetlerden* üretiliyordu. Docstring "merge yeni span/sayfa
325 uydurmaz" diyordu — doğru, ama **kod uyduruyordu**. Özet yüzeyinde atıf
326 precision'ı yapısal olarak `1/grup_sayısı`'na düşüyordu.
327
328 Kapı **A-08** (%100): dönen her atıf modelin metinde yazdığı bir `[N]`
329 olmalı.
330 """
331
332 def _kos(self, texts, units, mupg=3):
333 ds = _StubLLMClient(texts=texts)
334 s = Summarizer(ds, cost_recorder=_noop_recorder, max_units_per_group=mupg)
335 return s.summarize(units), ds
336
337 def _dokuz(self):
338 return [_Unit(f"s{i}", i, f"metin{i}") for i in range(1, 10)]
339
340 def test_denetimde_kosulan_senaryo_tek_atif_tek_citation(self):
341 """Denetimin kanıtı: 9 birim / mupg=3 → 3 ara-özet; model nihai metinde
342 YALNIZ [1] atıfladı ama çıktı 3 atıf (s.1, s.4, s.7) döndürüyordu."""
343 texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai özet [1]."]
344 res, _ = self._kos(texts, self._dokuz())
345 self.assertEqual([c["n"] for c in res.citations], [1])
346 self.assertEqual(res.citations[0]["pages"], [1])
347 sayfalar = {p for c in res.citations for p in c["pages"]}
348 self.assertNotIn(4, sayfalar) # modelin YAPMADIĞI atıflar
349 self.assertNotIn(7, sayfalar)
350
351 def test_iki_atif_iki_citation(self):
352 texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai [1][3]."]
353 res, _ = self._kos(texts, self._dokuz())
354 self.assertEqual([c["n"] for c in res.citations], [1, 3])
355 self.assertEqual({p for c in res.citations for p in c["pages"]}, {1, 7})
356
357 def test_hic_atif_yoksa_citation_da_yok(self):
358 """Dayanaksız özet sessizce kanıtlı görünmemeli."""
359 texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai özet, atıf yok."]
360 res, _ = self._kos(texts, self._dokuz())
361 self.assertEqual(res.citations, [])
362
363 def test_hayalet_atif_sessizce_elenir(self):
364 """Kaynak sayısını aşan [N] patlamaya değil sessiz elemeye yol açar
365 (generator.py ile TUTARLI)."""
366 texts = ["Grup1 [1].", "Grup2 [1].", "Grup3 [1].", "Nihai [1][9]."]
367 res, _ = self._kos(texts, self._dokuz())
368 self.assertEqual([c["n"] for c in res.citations], [1])
369
370 def test_her_donen_atif_metinde_gercekten_yaziyor(self):
371 """Kapı A-08 değişmezi: citations ⊆ metindeki [N]'ler."""
372 import re
373 texts = ["G1 [1].", "G2 [1].", "G3 [1].", "Nihai [2] ve ayrıca [3]."]
374 res, _ = self._kos(texts, self._dokuz())
375 metindeki = {int(n) for n in re.findall(r"\[(\d+)\]", res.text)}
376 self.assertTrue({c["n"] for c in res.citations} <= metindeki)
377 self.assertEqual({c["n"] for c in res.citations}, {2, 3})
378
379 def test_merge_cekimser_olursa_abstained_true(self):
380 """İkinci yarı: `abstained=False` SABİTTİ → nihai merge 'içerik yok'
381 dönse bile 'gerçek özet' işaretleniyordu."""
382 texts = ["G1 [1].", "G2 [1].", "G3 [1].", NO_CONTENT_SENTENCE]
383 res, _ = self._kos(texts, self._dokuz())
384 self.assertTrue(res.abstained)
385 self.assertEqual(res.reason, "llm_no_content")
386 self.assertEqual(res.citations, [])
387
388 def test_cekimser_olmayan_merge_abstained_false_kalir(self):
389 texts = ["G1 [1].", "G2 [1].", "G3 [1].", "Nihai özet [1]."]
390 res, _ = self._kos(texts, self._dokuz())
391 self.assertFalse(res.abstained)
392 self.assertEqual(res.reason, "")
393
394 def test_ozyinelemeli_seviyede_de_gecerli(self):
395 """mupg=2 ile 9 birim → 5 ara-özet → 3 merge → 2 merge → 1: ara
396 seviyelerde de yalnız atıflanan N taşınmalı."""
397 texts = ["G [1]." for _ in range(5)] + ["M [1]." for _ in range(10)]
398 res, ds = self._kos(texts, self._dokuz(), mupg=2)
399 self.assertGreater(ds.calls, 6)
400 self.assertEqual(len(res.citations), 1)
401 self.assertEqual(res.citations[0]["pages"], [1])
402
403 def test_maliyet_hala_tum_seviyelerin_toplami(self):
404 """Atıf kırpma maliyeti SIFIRLAMAMALI — LLM gerçekten çağrıldı."""
405 texts = ["G1 [1].", "G2 [1].", "G3 [1].", "Nihai, atıf yok."]
406 res, ds = self._kos(texts, self._dokuz())
407 self.assertGreater(res.cost_usd, 0.0)
408 self.assertEqual(res.usage.output, ds.calls * 5)
409
410
411# --------------------------------------------------------------------------- cost_recorder spy
412
413class CostRecorderSpyTests(unittest.TestCase):
414 def test_cost_recorder_called_with_ozet_module_single_pass(self):
415 calls = []
416
417 def spy(**kwargs):
418 calls.append(kwargs)
419 return {"cost_usd": 0.0}
420
421 units = [_Unit("s1", 1, "m1")]
422 ds = _StubLLMClient(text="Özet [1].")
423 summarizer = Summarizer(ds, module="ozet", cost_recorder=spy)
424
425 result = summarizer.summarize(units)
426
427 self.assertFalse(result.abstained)
428 self.assertEqual(len(calls), 1)
429 call = calls[0]
430 self.assertEqual(call["module"], "ozet")
431 self.assertEqual(call["model"], "deepseek-chat")
432 self.assertIs(call["usage"], result.usage)
433 self.assertEqual(call["items"], 1)
434
435 def test_cost_recorder_called_once_per_real_llm_call_hierarchical(self):
436 calls = []
437
438 def spy(**kwargs):
439 calls.append(kwargs)
440 return {"cost_usd": 0.0}
441
442 units = _five_units()
443 texts = ["Grup1 [1][2].", "Grup2 [1].", "Grup3 [1].", "Nihai [1][2][3]."]
444 ds = _StubLLMClient(texts=texts)
445 summarizer = Summarizer(ds, module="ozet", cost_recorder=spy, max_units_per_group=2)
446
447 summarizer.summarize(units)
448
449 # INVARIANT (recursion-agnostic): her GERÇEK LLM çağrısı için TAM 1 costlog kaydı.
450 self.assertEqual(len(calls), ds.calls)
451 self.assertTrue(all(c["module"] == "ozet" for c in calls))
452
453
454if __name__ == "__main__":
455 unittest.main()