Istek izi uretime baglandi (#85)
Browse files at this commit08e44ece53889ddf85b6381e18fa812596cf4c4aParent: e9fd0ac- feat
- istek izi uretime baglandi (#85)
4 changed files +311 -2
- .env.example +8 -0
- src/observability/trace.py +82 -0
- src/service/handler.py +25 -2
- tests/unit/test_trace.py +196 -0
.env.examplemodified+8 -0
| @@ -121,3 +121,11 @@ RAG_CACHE_TTL_S=3600 | ||
| 121 | 121 | # Bos = iz tutulmaz; silme yine calisir ama KANITLANAMAZ. |
| 122 | 122 | # "Sildim" demek yetmez; ne zaman neyin silindigi gosterilebilmeli. |
| 123 | 123 | HEZARFEN_DELETION_LOG= |
| 124 | + | |
| 125 | +# --- Istek izi (#85, EXP-010/OPS-12) --- | |
| 126 | +# Bos = iz KAPALI. Acikken her istek JSONL'e yazilir. | |
| 127 | +# Sorgu METNI YAZILMAZ (#49/KVKK) -- yalniz uzunluk + kisa hash. | |
| 128 | +# Ornekleme yogun trafikte diski korur; CEKIMSER ve HATALI istekler | |
| 129 | +# ornekleme oraninden BAGIMSIZ olarak HER ZAMAN yazilir. | |
| 130 | +HEZARFEN_TRACE_PATH= | |
| 131 | +HEZARFEN_TRACE_SAMPLE=1.0 |
src/observability/trace.pymodified+82 -0
| @@ -10,6 +10,7 @@ None ise HİÇBİR ek maliyet yok (mevcut davranış birebir korunur). | ||
| 10 | 10 | from __future__ import annotations |
| 11 | 11 | |
| 12 | 12 | import contextlib |
| 13 | +import os | |
| 13 | 14 | import time |
| 14 | 15 | import uuid |
| 15 | 16 | from dataclasses import dataclass, field |
| @@ -64,3 +65,84 @@ class RequestTrace: | ||
| 64 | 65 | return (f"[trace {self.request_id}] {self.total_ms:.0f}ms " |
| 65 | 66 | f"decision={d.get('abstained') and 'abstain' or 'answer'} " |
| 66 | 67 | f"reason={d.get('reason','')!r} events={len(self.events)}") |
| 68 | + | |
| 69 | + | |
| 70 | +# M4-11 (#85, EXP-010/OPS-12) — TRACE URETIMDE HIC URETILMIYORDU. | |
| 71 | +# | |
| 72 | +# grep ile dogrulandi: `RequestTrace` yalniz `trace.py` ve | |
| 73 | +# `observability/__init__.py`'de geciyordu. `RagService.chat` `trace=` | |
| 74 | +# gecirmiyor -> `Generator.answer(trace=None)` -> butun `_tr()` cagrilari | |
| 75 | +# NO-OP. Sink yok, `request_id` yanita donmuyor. | |
| 76 | +# | |
| 77 | +# SONUC: YENIDEN-OYNATILABILIRLIK YOK. "Neden bu cevabi verdi?" sorusu geriye | |
| 78 | +# donuk cevaplanamiyor; kalite regresyonu ve sikayet incelemesi imkansiz. | |
| 79 | +# | |
| 80 | +# HASSAS ICERIK: #49 (KVKK) ile uyumlu olmak zorunda -- ogrencinin sorgu | |
| 81 | +# METNI ize YAZILMAZ; yalniz uzunluk + kisa hash tutulur. Sorgu metnini | |
| 82 | +# yazmak, silinmesi gereken bir kisisel veriyi ikinci bir yere kopyalamak | |
| 83 | +# demektir. | |
| 84 | + | |
| 85 | +TRACE_PATH = os.environ.get("HEZARFEN_TRACE_PATH") or "" | |
| 86 | +TRACE_SAMPLE = float(os.environ.get("HEZARFEN_TRACE_SAMPLE", "1.0")) | |
| 87 | + | |
| 88 | + | |
| 89 | +def redact(text: str | None) -> dict: | |
| 90 | + """Sorgu metnini ize yazmadan tanınabilir kılar (#49 ile uyumlu).""" | |
| 91 | + import hashlib | |
| 92 | + ham = text or "" | |
| 93 | + return {"len": len(ham), | |
| 94 | + "hash": hashlib.sha256(ham.encode("utf-8")).hexdigest()[:12]} | |
| 95 | + | |
| 96 | + | |
| 97 | +def write_trace(trace, path: str | None = None, *, sample: float | None = None, | |
| 98 | + rng=None) -> bool: | |
| 99 | + """İzi JSONL sink'e yazar. Döner: yazıldı mı. | |
| 100 | + | |
| 101 | + ÖRNEKLEME: yoğun trafikte her isteği yazmak diski doldurur. `sample=0.1` | |
| 102 | + izlerin %10'unu tutar. **Çekimser ve hatalı istekler HER ZAMAN yazılır** — | |
| 103 | + incelenmesi gereken tam olarak onlardır; örnekleme onları atarsa | |
| 104 | + izlenebilirlik en çok ihtiyaç duyulan yerde kaybolur. | |
| 105 | + | |
| 106 | + Telemetri hatası isteği ASLA düşürmez (aynı ilke: costlog, audit). | |
| 107 | + """ | |
| 108 | + import json as _json | |
| 109 | + import random as _random | |
| 110 | + hedef = path if path is not None else TRACE_PATH | |
| 111 | + if not hedef: | |
| 112 | + return False | |
| 113 | + d = trace.to_dict() if hasattr(trace, "to_dict") else dict(trace) | |
| 114 | + oran = TRACE_SAMPLE if sample is None else sample | |
| 115 | + # DIKKAT: `TraceEvent.to_dict()` meta'yi DUZLESTIRIR (ayri bir "meta" | |
| 116 | + # anahtari YOKTUR). Ilk surumde `e.get("meta", {})` yaziyordum ve bu yuzden | |
| 117 | + # ONEMLI izler hicbir zaman taninmiyor, ornekleme onlari da atiyordu -- | |
| 118 | + # yani izlenebilirlik tam ihtiyac duyulan yerde kayboluyordu. | |
| 119 | + onemli = any(e.get("abstained") or e.get("name") == "error" | |
| 120 | + for e in d.get("events", [])) | |
| 121 | + if not onemli and oran < 1.0: | |
| 122 | + r = (rng or _random.random)() | |
| 123 | + if r >= oran: | |
| 124 | + return False | |
| 125 | + try: | |
| 126 | + os.makedirs(os.path.dirname(hedef) or ".", exist_ok=True) | |
| 127 | + with open(hedef, "a", encoding="utf-8") as fh: | |
| 128 | + fh.write(_json.dumps(d, ensure_ascii=False) + "\n") | |
| 129 | + return True | |
| 130 | + except Exception: # noqa: BLE001 | |
| 131 | + return False | |
| 132 | + | |
| 133 | + | |
| 134 | +def read_traces(path: str | None = None) -> list[dict]: | |
| 135 | + import json as _json | |
| 136 | + hedef = path if path is not None else TRACE_PATH | |
| 137 | + if not hedef or not os.path.isfile(hedef): | |
| 138 | + return [] | |
| 139 | + out = [] | |
| 140 | + with open(hedef, encoding="utf-8") as fh: | |
| 141 | + for satir in fh: | |
| 142 | + satir = satir.strip() | |
| 143 | + if satir: | |
| 144 | + try: | |
| 145 | + out.append(_json.loads(satir)) | |
| 146 | + except Exception: # noqa: BLE001 | |
| 147 | + continue | |
| 148 | + return out |
src/service/handler.pymodified+25 -2
| @@ -10,6 +10,7 @@ yeniden doğrulanır (yanlış sınıf/ders → red).""" | ||
| 10 | 10 | from __future__ import annotations |
| 11 | 11 | |
| 12 | 12 | from ..budget import BudgetGate, check_request_size |
| 13 | +from ..observability.trace import RequestTrace, redact, write_trace | |
| 13 | 14 | from ..providers.resilience import LlmUnavailable |
| 14 | 15 | from ..guard.roles import RoleContext, Role, can_access |
| 15 | 16 | |
| @@ -149,19 +150,41 @@ class RagService: | ||
| 149 | 150 | if not karar.allowed: |
| 150 | 151 | return _budget_denied(karar, "chat") |
| 151 | 152 | opts = req.get("options") or {} |
| 153 | + # #85 (EXP-010/OPS-12): iz URETIMDE HIC URETILMIYORDU. `trace=` | |
| 154 | + # gecirilmedigi icin generator'daki butun `_tr()` cagrilari no-op'tu ve | |
| 155 | + # "neden bu cevabi verdi?" sorusu geriye donuk cevaplanamiyordu. | |
| 156 | + # Sorgu METNI ize YAZILMAZ (#49/KVKK) -- yalniz uzunluk + kisa hash. | |
| 157 | + trace = RequestTrace(request_id=req.get("request_id")) | |
| 158 | + trace.event("request", kind="chat", query=redact(query), | |
| 159 | + role=(role_ctx.role.value if role_ctx else None), | |
| 160 | + sinif=(role_ctx.sinif if role_ctx else None), | |
| 161 | + top_n=int(opts.get("top_n", 6)), | |
| 162 | + candidate_n=int(opts.get("candidate_n", 40))) | |
| 152 | 163 | try: |
| 153 | 164 | a = self.generator.answer( |
| 154 | 165 | query, history=req.get("history"), |
| 155 | 166 | top_n=int(opts.get("top_n", 6)), |
| 156 | 167 | candidate_n=int(opts.get("candidate_n", 40)), |
| 157 | - role_ctx=role_ctx) | |
| 168 | + role_ctx=role_ctx, trace=trace) | |
| 158 | 169 | except LlmUnavailable: |
| 170 | + trace.event("error", kind="llm_unavailable") | |
| 171 | + write_trace(trace) | |
| 159 | 172 | return _llm_unavailable("chat") |
| 160 | 173 | # Harcama GERÇEKLEŞTİ → sayaca yaz. Kapı bir sonraki istekte bakar; |
| 161 | 174 | # harcamadan sonra bakmak tavanı anlamsız kılardı. |
| 162 | 175 | self.budget.record(getattr(a, "cost_usd", 0.0) or 0.0, |
| 163 | 176 | user=req.get("user"), tenant=req.get("tenant")) |
| 164 | - return _answer_to_dict(a) | |
| 177 | + trace.event("response", abstained=bool(a.abstained), reason=a.reason or "", | |
| 178 | + n_citations=len(a.citations), | |
| 179 | + n_sentences=getattr(a, "n_sentences", 0), | |
| 180 | + n_cited_sentences=getattr(a, "n_cited_sentences", 0), | |
| 181 | + n_phantom=len(getattr(a, "invalid_citations", []) or []), | |
| 182 | + cache_hit=bool(getattr(a, "cache_hit", False)), | |
| 183 | + cost_usd=round(a.cost_usd, 6)) | |
| 184 | + write_trace(trace) | |
| 185 | + out = _answer_to_dict(a) | |
| 186 | + out["request_id"] = trace.request_id # #85: yanita KOY | |
| 187 | + return out | |
| 165 | 188 | |
| 166 | 189 | # -------------------------------------------------------------- /rag/summarize |
| 167 | 190 | def summarize(self, req: dict) -> dict: |
tests/unit/test_trace.pyadded+196 -0
| @@ -0,0 +1,196 @@ | ||
| 1 | +"""#85 (EXP-010/OPS-12) — istek izi: üretimde hiç üretilmiyordu. | |
| 2 | + | |
| 3 | +grep ile doğrulanmıştı: `RequestTrace` yalnız `trace.py` ve | |
| 4 | +`observability/__init__.py`'de geçiyordu. `RagService.chat` `trace=` | |
| 5 | +geçirmiyordu → `Generator.answer(trace=None)` → **bütün `_tr()` çağrıları | |
| 6 | +no-op**. Sink yok, `request_id` yanıta dönmüyordu. | |
| 7 | + | |
| 8 | +SONUÇ: **yeniden-oynatılabilirlik yok.** "Neden bu cevabı verdi?" sorusu | |
| 9 | +geriye dönük cevaplanamıyor; kalite regresyonu ve şikâyet incelemesi imkânsız. | |
| 10 | + | |
| 11 | +KVKK SINIRI (#49 ile uyumlu): öğrencinin **sorgu metni ize yazılmaz** — yalnız | |
| 12 | +uzunluk + kısa hash. Metni yazmak, silinmesi gereken bir kişisel veriyi ikinci | |
| 13 | +bir yere kopyalamak demektir. | |
| 14 | +""" | |
| 15 | +import os | |
| 16 | +import tempfile | |
| 17 | +import unittest | |
| 18 | + | |
| 19 | +from src.observability.trace import (RequestTrace, TRACE_PATH, read_traces, | |
| 20 | + redact, write_trace) | |
| 21 | +from src.pricing import Usage | |
| 22 | + | |
| 23 | + | |
| 24 | +class RedactionTests(unittest.TestCase): | |
| 25 | + def test_query_text_is_never_stored(self): | |
| 26 | + gizli = "Ben cok kotuyum ve kendime zarar vermek istiyorum" | |
| 27 | + d = redact(gizli) | |
| 28 | + ham = str(d) | |
| 29 | + self.assertNotIn("kotuyum", ham) | |
| 30 | + self.assertNotIn("zarar", ham) | |
| 31 | + self.assertEqual(d["len"], len(gizli)) | |
| 32 | + self.assertEqual(len(d["hash"]), 12) | |
| 33 | + | |
| 34 | + def test_same_text_same_hash(self): | |
| 35 | + """Tekrar tespiti mümkün olmalı (aynı soru kaç kez soruldu).""" | |
| 36 | + self.assertEqual(redact("ayni")["hash"], redact("ayni")["hash"]) | |
| 37 | + self.assertNotEqual(redact("a")["hash"], redact("b")["hash"]) | |
| 38 | + | |
| 39 | + def test_none_is_safe(self): | |
| 40 | + self.assertEqual(redact(None)["len"], 0) | |
| 41 | + | |
| 42 | + | |
| 43 | +class SinkTests(unittest.TestCase): | |
| 44 | + def setUp(self): | |
| 45 | + self.d = tempfile.mkdtemp() | |
| 46 | + self.yol = os.path.join(self.d, "trace.jsonl") | |
| 47 | + | |
| 48 | + def _iz(self, **meta): | |
| 49 | + t = RequestTrace() | |
| 50 | + t.event("decision", **meta) | |
| 51 | + return t | |
| 52 | + | |
| 53 | + def test_trace_is_written_and_read_back(self): | |
| 54 | + self.assertTrue(write_trace(self._iz(stage="generate"), self.yol)) | |
| 55 | + kayitlar = read_traces(self.yol) | |
| 56 | + self.assertEqual(len(kayitlar), 1) | |
| 57 | + self.assertIn("request_id", kayitlar[0]) | |
| 58 | + self.assertIn("events", kayitlar[0]) | |
| 59 | + | |
| 60 | + def test_disabled_by_default(self): | |
| 61 | + """Veri minimizasyonu: yol verilmezse hiçbir şey yazılmaz.""" | |
| 62 | + self.assertEqual(TRACE_PATH, "") | |
| 63 | + self.assertFalse(write_trace(self._iz(), "")) | |
| 64 | + | |
| 65 | + def test_failure_never_raises(self): | |
| 66 | + """Telemetri hatası bir cevabı ASLA düşürmemeli.""" | |
| 67 | + try: | |
| 68 | + ok = write_trace(self._iz(), "/dev/null/yok/trace.jsonl") | |
| 69 | + except Exception as e: # pragma: no cover | |
| 70 | + self.fail(f"telemetri hatasi istisna firlatti: {e!r}") | |
| 71 | + self.assertFalse(ok) | |
| 72 | + | |
| 73 | + def test_sampling_drops_ordinary_traces(self): | |
| 74 | + for _ in range(10): | |
| 75 | + write_trace(self._iz(stage="generate"), self.yol, | |
| 76 | + sample=0.0, rng=lambda: 0.5) | |
| 77 | + self.assertEqual(read_traces(self.yol), []) | |
| 78 | + | |
| 79 | + def test_abstained_traces_are_always_kept(self): | |
| 80 | + """Örnekleme incelenmesi GEREKEN izleri atmamalı — izlenebilirlik en | |
| 81 | + çok orada lazım.""" | |
| 82 | + write_trace(self._iz(abstained=True, reason="insufficient_data"), | |
| 83 | + self.yol, sample=0.0, rng=lambda: 0.5) | |
| 84 | + self.assertEqual(len(read_traces(self.yol)), 1) | |
| 85 | + | |
| 86 | + def test_error_traces_are_always_kept(self): | |
| 87 | + t = RequestTrace() | |
| 88 | + t.event("error", kind="llm_unavailable") | |
| 89 | + write_trace(t, self.yol, sample=0.0, rng=lambda: 0.5) | |
| 90 | + self.assertEqual(len(read_traces(self.yol)), 1) | |
| 91 | + | |
| 92 | + def test_corrupt_line_does_not_lose_the_log(self): | |
| 93 | + with open(self.yol, "w", encoding="utf-8") as fh: | |
| 94 | + fh.write("{bozuk\n") | |
| 95 | + write_trace(self._iz(), self.yol) | |
| 96 | + self.assertEqual(len(read_traces(self.yol)), 1) | |
| 97 | + | |
| 98 | + | |
| 99 | +class SpanTests(unittest.TestCase): | |
| 100 | + def test_span_records_duration(self): | |
| 101 | + t = RequestTrace() | |
| 102 | + with t.span("retrieval", top_k=20): | |
| 103 | + pass | |
| 104 | + olay = t.to_dict()["events"][-1] | |
| 105 | + self.assertEqual(olay["name"], "retrieval") | |
| 106 | + # `to_dict()` meta'yı DÜZLEŞTİRİR — ayrı bir "meta" anahtarı yoktur. | |
| 107 | + self.assertIn("dur_ms", olay) | |
| 108 | + | |
| 109 | + def test_span_records_even_on_exception(self): | |
| 110 | + t = RequestTrace() | |
| 111 | + with self.assertRaises(ValueError): | |
| 112 | + with t.span("rerank"): | |
| 113 | + raise ValueError("patladi") | |
| 114 | + self.assertEqual(t.to_dict()["events"][-1]["name"], "rerank") | |
| 115 | + | |
| 116 | + | |
| 117 | +class _Gen: | |
| 118 | + """Trace'i gerçekten kullanan minimal generator.""" | |
| 119 | + | |
| 120 | + def __init__(self): | |
| 121 | + self.gorulen_trace = None | |
| 122 | + | |
| 123 | + def answer(self, query, *, trace=None, **kw): | |
| 124 | + self.gorulen_trace = trace | |
| 125 | + if trace is not None: | |
| 126 | + trace.event("decision", stage="generate", abstained=False) | |
| 127 | + | |
| 128 | + class _A: | |
| 129 | + text = "cevap [1]" | |
| 130 | + citations = [{"n": 1, "chunk_id": "c1", "span_ids": ["s1"], | |
| 131 | + "pages": [3], "ders": "biyoloji"}] | |
| 132 | + used_source_ids = ["c1"] | |
| 133 | + invalid_citations = [] | |
| 134 | + abstained = False | |
| 135 | + reason = "" | |
| 136 | + cost_usd = 0.001 | |
| 137 | + cache_hit = False | |
| 138 | + usage = Usage() | |
| 139 | + n_sentences = 1 | |
| 140 | + n_cited_sentences = 1 | |
| 141 | + return _A() | |
| 142 | + | |
| 143 | + | |
| 144 | +class ServiceWiringTests(unittest.TestCase): | |
| 145 | + """Asıl bulgu: servis `trace=` geçirmiyordu, yani iz HİÇ üretilmiyordu.""" | |
| 146 | + | |
| 147 | + def setUp(self): | |
| 148 | + from src.service.handler import RagService | |
| 149 | + self.gen = _Gen() | |
| 150 | + self.svc = RagService(self.gen) | |
| 151 | + | |
| 152 | + def test_service_passes_a_trace_to_the_generator(self): | |
| 153 | + self.svc.chat({"query": "soru"}) | |
| 154 | + self.assertIsNotNone(self.gen.gorulen_trace, | |
| 155 | + "servis hala trace gecirmiyor") | |
| 156 | + | |
| 157 | + def test_request_id_is_returned_to_the_caller(self): | |
| 158 | + out = self.svc.chat({"query": "soru"}) | |
| 159 | + self.assertIn("request_id", out) | |
| 160 | + self.assertTrue(out["request_id"]) | |
| 161 | + | |
| 162 | + def test_caller_supplied_request_id_is_used(self): | |
| 163 | + """Uçtan uca izleme: backend kendi id'sini verirse o korunmalı.""" | |
| 164 | + out = self.svc.chat({"query": "soru", "request_id": "izlenebilir-1"}) | |
| 165 | + self.assertEqual(out["request_id"], "izlenebilir-1") | |
| 166 | + | |
| 167 | + def test_trace_records_the_decision_fields(self): | |
| 168 | + d = tempfile.mkdtemp() | |
| 169 | + yol = os.path.join(d, "t.jsonl") | |
| 170 | + from unittest import mock | |
| 171 | + from src.service import handler | |
| 172 | + with mock.patch.object(handler, "write_trace", | |
| 173 | + lambda t, *a, **k: write_trace(t, yol)): | |
| 174 | + self.svc.chat({"query": "soru"}) | |
| 175 | + kayitlar = read_traces(yol) | |
| 176 | + self.assertTrue(kayitlar) | |
| 177 | + adlar = {e["name"] for e in kayitlar[0]["events"]} | |
| 178 | + self.assertIn("request", adlar) | |
| 179 | + self.assertIn("response", adlar) | |
| 180 | + | |
| 181 | + def test_query_text_is_not_in_the_trace(self): | |
| 182 | + d = tempfile.mkdtemp() | |
| 183 | + yol = os.path.join(d, "t.jsonl") | |
| 184 | + from unittest import mock | |
| 185 | + from src.service import handler | |
| 186 | + gizli = "kendime zarar vermek istiyorum cunku" | |
| 187 | + with mock.patch.object(handler, "write_trace", | |
| 188 | + lambda t, *a, **k: write_trace(t, yol)): | |
| 189 | + self.svc.chat({"query": gizli}) | |
| 190 | + ham = open(yol, encoding="utf-8").read() | |
| 191 | + self.assertNotIn("zarar", ham) | |
| 192 | + self.assertNotIn("cunku", ham) | |
| 193 | + | |
| 194 | + | |
| 195 | +if __name__ == "__main__": | |
| 196 | + unittest.main() |