diff --git a/PROJECT_STATE.md b/PROJECT_STATE.md index 67d7eb1..f526b48 100644 --- a/PROJECT_STATE.md +++ b/PROJECT_STATE.md @@ -101,7 +101,8 @@ ham veri + soru/cevap defteri: `outputs/EXP-009-model-karsilastirma/`), maliyet `.github/workflows/main.yml` (elle tetiklenen VPS deploy). Backend bu HTTP'yi ÇAĞIRMAZ; gerçek entegrasyon QUIC `hab/2` köprüsüdür ve **taşıması yazıldı** (`src/bridge/transport.py`, ¶11.4) → `rag.chat` artık telden servis edilir; - `rag.index` hâlâ TİPLİ REDDEDER (`index_path_unwired`). + `rag.index` SUNULUR (2026-09-18): not + ekler indekslenir — ek baytları kendi + blob akışıyla okunur, parçalar okulun not indeksine yazılır. Kalıcı Qdrant hâlâ yok (in-memory indeks; #75/RISK-01). ## 4. Mimari Özet @@ -114,8 +115,8 @@ ham veri + soru/cevap defteri: `outputs/EXP-009-model-karsilastirma/`), maliyet `role`; `rag.chat`/`chat.reply`), **taşıma `src/bridge/transport.py`** (dial-out, `Hello`/`Greeting`, `Request` → dağıtıcı → `Response`, PING, üstel geri çekilmeyle sonsuz yeniden bağlanma; ¶11.4). Yani `rag.chat` telden servis - edilir; eksik kalan: `rag.index` (ek dosya baytları + korpus yönlendirmesi) ve - backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`, bugün çağıranı yok). + edilir; kalan: backend'den genel OKUMA yolu (`ApiRequest`, çağıranı yok) — `rag.index` + ek baytlarını `BlobRequest` ile OKUR (2026-09-18). Girdi/çıktı sözleşmesi + kiracılık: `docs/API-CONTRACT.md` §0.3, `docs/BACKEND-INTEGRATION.md` §4/§4.1/§4.2. @@ -127,10 +128,10 @@ flowchart LR S[Öğrenci] -->|soru| FE[frontend] --> BR[backend QUIC hab/2] --> RAG --> BR --> FE --> S ``` > Diyagram NİYETİ gösterir. 2026-09-17 durumu: `S → BR → RAG → BR → FE → S` -> yolu ARTIK ÇALIŞIR (taşıma landı, `rag.chat` telden servis edilir). Kesikli -> oklar hâlâ çizilmemiştir çünkü **korpus akışı yok**: `rag.index` tipli -> reddediyor (dosya baytları `BlobRequest` ile okunmuyor), kalıcı Qdrant yok ve -> öğretmenin yüklediği not otomatik indekslenmiyor. +> yolu ARTIK ÇALIŞIR (taşıma landı, `rag.chat` telden servis edilir) ve korpus +> akışı AÇILDI (2026-09-18): `rag.index` notu + eklerini indeksler (ek baytları +> `BlobRequest` ile okunur). Kesikli oklar hâlâ çizilmemiştir çünkü **kalıcı +> Qdrant yok**: not indeksi süreç-içidir, restart'ta kaybolur. ## 5. Teknik Kararlar - **D1** — RAG kaynağı sıfırdan yükleme alanı GEREKMEZ: `course-notes` (öğretmen→kayıtlı-öğrenci, dosya ekli) doğal korpustur. **kabul edildi** (backend/frontend main'de doğrulandı 2026-08-16). ⚠️ **Çelişki düzeltmesi:** bu oturumun erken RAG cevabı "böyle bir alan yok" idi; o cevap course-notes eklenmeden önceki duruma aitti ve **artık geçersiz** — doğrulanmış gerçek: alan VAR. @@ -149,9 +150,9 @@ flowchart LR - **TASK-GOLDEN-APPROVE** — P1 — golden v1.1 (200 item) Kadir onayı → üretim ölçümü kilidi açılır. dep: Kadir. **BLOCKED**. - **TASK-CRISIS-LINE** — P1 — self-harm guardrail mesajına kriz-hattı no'su. dep: Kadir. **BLOCKED**. - **TASK-RAG-SERVICE** — P2 — HTTP servisi + `hab/2` dağıtıcısı + **QUIC taşıması - TAMAM** (2026-09-17, ¶11.4); kalan: `rag.index` yolunun yazılması (ek dosya - baytları + korpus yönlendirmesi) ve kalıcı Qdrant (sözleşme: - `docs/API-CONTRACT.md` §0.3). **KISMİ (eksik: index + kalıcı store)**. + TAMAM** (2026-09-17, ¶11.4); `rag.index` yolu da yazıldı (2026-09-18: blob okuma → parça → gömme → okulun not + indeksi); kalan: kalıcı Qdrant (sözleşme: `docs/API-CONTRACT.md` §0.3). + **KISMİ (eksik: kalıcı store)**. - **TASK-RAG-SCALE** — P3 — Faz 2 RAPTOR ölçek + çok-dersli korpus + özet-PDF/OCR (Faz 0.8). dep: Kadir yönü. **TODO**. - **TASK-REARCH** — P4 — derin yeniden-mimari (EB-KOS/layout/kalibrasyon) — "optimizasyon fazı", Kadir'e ayrıldı. **DEFERRED**. @@ -345,11 +346,13 @@ transport-bağımsız dağıtıcıya verip tek `Response` yazar. Her hatada üst `docs/BACKEND-INTEGRATION.md` §4.2). **KAPSAM DIŞI (bilinçli, yalan söylenmiyor):** -- `rag.index` hâlâ TİPLİ REDDEDER (`index_path_unwired`): dizin yazımı ek dosya - baytlarını (`BlobRequest`) ve korpus yönlendirmesini ister — yazılmadı. -- Backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`) QUIC üzerinden - bağlanmadı: bugünkü iki yetenek de onu istemiyor (`rag.chat` kapsamı - çerçevede), yani çağıranı olmayan bir yol yazılmadı. +- `rag.index` SUNULUR (2026-09-18); iki dürüst sınır: (a) not indeksi SÜREÇ-İÇİDİR + (restart'ta kaybolur; not düzenlenince backend yeniden gönderir), (b) notun + (sınıf, ders) bilgisi telde YOKTUR — not kanalı OKUL süzgeçli, kasa süzgeci + değil (`src/index/notes.py` başlığı). +- Backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden bağlanmadı: + `rag.chat` kapsamı çerçevede gelir, `rag.index` yalnız BLOB okur; çağıranı + olmayan yol yazılmadı. - **Canlı bir backend'e karşı uçtan uca koşum YAPILMADI** (bu oturumda ayakta backend yoktu): kanıt sahte sunucuyla alınan gerçek QUIC el sıkışmasıdır (kayıt, istek→dağıtım→cevap, tipli redler, kopma→yeniden kayıt, diff --git a/docs/API-CONTRACT.md b/docs/API-CONTRACT.md index 57f7ade..0100bd6 100644 --- a/docs/API-CONTRACT.md +++ b/docs/API-CONTRACT.md @@ -82,7 +82,8 @@ okulsuz okur hiçbir şey görmez. testlidir (okul eko'su, yetenek eşlemesi, `asker_role` → `role`). QUIC taşıması (`bridge/transport.py`) 2026-09-17'de eklendi: dial-out + kayıt + gelen `Request`lerin dağıtıcıya verilmesi + yeniden bağlanma. `rag.chat` böylece -telden servis edilebilir; `rag.index` hâlâ TİPLİ REDDEDER (sunulmuyor). +telden servis edilebilir; `rag.index` de SUNULUR (2026-09-18) — ek baytları +`BlobRequest` ile okunur, cevap `{course_note, chunks, files[], failed[], summary}`. HTTP yüzeyi yerel koşum/ölçüm için durur; backend onu ÇAĞIRMAZ. ## 0. Sorumluluk sınırı — kim neyi yapar (#87, 2026-09-12) diff --git a/docs/BACKEND-INTEGRATION.md b/docs/BACKEND-INTEGRATION.md index eb791aa..cb72270 100644 --- a/docs/BACKEND-INTEGRATION.md +++ b/docs/BACKEND-INTEGRATION.md @@ -24,8 +24,8 @@ RAG servisi: > artık VAR: `src/bridge/transport.py` backend'e dial-out eder, `rag.chat` + > `rag.index` ilan eder ve gelen `Request`leri `bridge/dispatch.py`'ye verir > (§4.2). `src/bridge/client.py` ise hâlâ yalnız çerçeve kurma/çözme tarafıdır: -> backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`) QUIC üzerinden -> bağlanmadı — bugünkü yetenekler onu istemiyor (§7). +> backend'den BLOB okuma yolu da LANDI: `rag.index` her eki `BlobRequest` ile +> okur (2026-09-18); yalnız genel `ApiRequest` yolunun çağıranı yok (§7). ## 2. Bugün ÇALIŞAN yol: `rag.index` @@ -170,7 +170,7 @@ denemek bırakılmaz. **Testler (ağ yok, DB yok):** `tests/unit/test_bridge_transport.py` sahte bir QUIC sunucusuyla (`tests/unit/_fake_bridge.py`, aioquic, 127.0.0.1) kaydı, okul eko'sunu, tipli redleri (`invalid_school`, okulsuz çerçevede cevapsız akış, -`index_path_unwired`), kopma sonrası yeniden kaydolmayı ve backend-yokken boot +`malformed`), blob akışından ek okumayı, kopma sonrası yeniden kaydolmayı ve backend-yokken boot politikasını koşar. ## 5. Bu tarafta yapılanlar (bu depoda) @@ -212,15 +212,14 @@ Birleştirilmeden `can_access(sinif=, ders=)` kurulamaz. artık telden servis edilir: kayıt, okul eko'su, tipli redler, kopma sonrası yeniden bağlanma ve backend-yokken boot politikası sahte bir QUIC sunucusuyla test edilir (`tests/unit/test_bridge_transport.py`). -- **`rag.index` hâlâ SUNULMUYOR** — taşıma onu taşır ama dağıtıcı tipli - reddeder (`index_path_unwired`): dizin yazımı ek dosya BAYTLARINI - (`BlobRequest`) ve korpus yönlendirmesini ister. Sahte bir "tamam" demek - yerine reddedilir; backend başarısız indekslemede eski `rag_output` satırını - korur. -- **Backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`) QUIC üzerinden - bağlanmadı.** Bugünkü iki yetenek de onu istemez (`rag.chat`'in kapsamı - çerçevede gelir; `rag.index` sunulmuyor), bu yüzden çağıranı olmayan bir yol - yazılmadı. Öğrenci bağlamı (`BridgeReader`) gerektiren bir yetenek eklenirse +- **`rag.index` SUNULUR (2026-09-18)** — gövde: `bridge/dispatch.py::_rag_index` → + `service/notes_index.py` (not + ekler → parça → gömme → okulun not indeksi). Ek + baytları `bridge/transport.py::read_blob` ile HAM okunur (başlık + tam `size` + bayt). Dürüst sınır: not indeksi süreç-içidir ve not kanalı OKUL süzgeçlidir, + kasa süzgeci değil (telde notun sınıfı/dersi yok). +- **Backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden bağlanmadı.** + `rag.chat`'in kapsamı çerçevede gelir; `rag.index` yalnız BLOB okur + (`BlobRequest`). Çağıranı olmayan `ApiRequest` yolu yazılmadı. Öğrenci bağlamı (`BridgeReader`) gerektiren bir yetenek eklenirse `client.py`'ın senkron `(gönder, al)` arayüzü ile taşımanın async akışları arasında bir uyarlama gerekir. - `rag.chat` `asker_role` → `role.role` eşlemesi dağıtıcıda YAPILIYOR diff --git a/docs/Backlog.md b/docs/Backlog.md index 248abc4..263c94b 100644 --- a/docs/Backlog.md +++ b/docs/Backlog.md @@ -164,13 +164,12 @@ Backend QUIC **sunucusudur**, AI servisleri ona dial eder. Taşıma yazıldı: **Test:** `tests/unit/test_bridge_transport.py` — sahte QUIC sunucusu (`tests/unit/_fake_bridge.py`), ağ/DB yok: kayıt, istek→dağıtım→cevap (okul eko'su), tipli redler (`invalid_school`, okulsuz çerçevede cevapsız akış, -`index_path_unwired`), kopma sonrası yeniden kaydolma, backend-yokken süreç +`malformed`), blob akışından ek okuma, kopma sonrası yeniden kaydolma, backend-yokken süreç çıkmaz + backend gelince kendiliğinden katılır. -**Kalan (bilinçli):** `rag.index` hâlâ TİPLİ REDDEDER (ek dosya baytları -`BlobRequest` + korpus yönlendirmesi ister, yazılmadı); backend'den OKUMA yolu -(`ApiRequest`/`BlobRequest`) QUIC üzerinden bağlanmadı — bugünkü yetenekler -istemediği için çağıranı olmayan yol yazılmadı. Ayrıntı: +**Kalan (bilinçli):** backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden +bağlanmadı — çağıranı yok. `rag.index` (2026-09-18) ek baytlarını `BlobRequest` +ile okur ve notu okulun not indeksine yazar (süreç-içi). Ayrıntı: `docs/BACKEND-INTEGRATION.md` §4.2 + §7. ### BL-011 — Veli (parent) görünürlüğü kurulmadı diff --git a/src/bridge/contract.py b/src/bridge/contract.py index a285714..e9507e8 100644 --- a/src/bridge/contract.py +++ b/src/bridge/contract.py @@ -346,6 +346,23 @@ class BlobRequest: return d +class BlobReadRefused(Exception): + """A blob read that did not deliver bytes. + + The backend's own refusal vocabulary (`protocol.rs::BlobResponse::Err`: + `not_found` for a file it does not have, `forbidden` for one the named + reader may not open, `module_disabled`, `unavailable`) plus the codes this + side raises before/after the wire (`too_large`, `blob_unavailable`, + `bad_header`, `unsupported_type`, `parse_failed`). Typed, never a bare + `Exception`: one refused attachment must not abort a whole index. + """ + + def __init__(self, code: str, message: str) -> None: + super().__init__(f"{code}: {message}") + self.code = code + self.message = message + + class ApiError(Exception): """Köprü düzeyinde red (yol izinli değil, kullanıcı bilinmiyor). diff --git a/src/bridge/dispatch.py b/src/bridge/dispatch.py index 09bf0cb..d0fc48f 100644 --- a/src/bridge/dispatch.py +++ b/src/bridge/dispatch.py @@ -26,18 +26,22 @@ from .contract import (AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, AI_RAG_INDEX_CAPABILITY, BridgeFrameError, BridgeRequest, BridgeResponse) -#: Bu depo `rag.index`i HENÜZ sunamaz: dizin yazımı ek dosya BAYTLARINI -#: (`BlobRequest`) ve korpus yönlendirmesini ister; taşıma yazılmadı (BL-010). -#: Sahte bir "tamam" demek yerine tipli reddedilir — backend zaten sessizlik -#: üzerine kurulu (başarısız indeksleme eski `rag_output` satırını korur). -INDEX_UNWIRED = "index_path_unwired" - - +# `rag.index` is served end to end: the payload is parsed, every attachment is +# read as bytes over its own blob stream, the note is chunked, embedded and +# written into the school's note index (`service::notes_index`), and the answer +# object goes back for the backend to store as the note's `rag_output`. class Dispatcher: """`Request` çerçevesi → servis metodu → `Response` çerçevesi.""" - def __init__(self, service, *, capabilities=None): + def __init__(self, service, *, capabilities=None, indexer=None): self.service = service + #: `rag.index`'in gövdesi (not → parça → gömme → not indeksi). Enjekte + #: edilebilir: taşıma testleri ağ/örnek istemeyen bir sahte verir; + #: üretimde `service::notes_index.index_course_note` koşar. + self.indexer = indexer + #: Blob okuyucusu — TAŞIMA takar (`transport.BridgeTransport.register`). + #: Yoksa ekler okunamaz ve notun kendi metni yine indekslenir. + self.blob_reader = None self.capabilities = tuple(capabilities or ( AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, AI_RAG_INDEX_CAPABILITY)) @@ -65,10 +69,7 @@ class Dispatcher: "`school` ZORUNLU (varsayılan/fallback yok)") if req.capability == AI_RAG_INDEX_CAPABILITY: - return BridgeResponse.err( - req, INDEX_UNWIRED, - "rag.index bu serviste henüz sunulmuyor (taşıma/BLOB yolu " - "yazılmadı) — istek reddedildi, eski çıktı korunur") + return self._rag_index(req, okul) if req.capability == AI_RAG_CHAT_CAPABILITY: return BridgeResponse.ok(req, self._rag_chat(req, okul)) if req.capability == AI_CHAT_CAPABILITY: @@ -79,6 +80,35 @@ class Dispatcher: f"{', '.join(self.capabilities)})") # -- gövde eşlemeleri (tel biçimi → servis sözlüğü) -------------------- + def _rag_index(self, req: BridgeRequest, okul: str) -> BridgeResponse: + """`rag.index` → not + ekler → not indeksi → backend'in sakladığı gövde. + + Redler TİPLİ ve küçük tutulur: backend bir hatada eski `rag_output` + satırını korur, yani "sessiz tamam" en kötü sonuçtur. Tek bir ekin + okunamaması ise red DEĞİLDİR — notun kendi metni indekslenir ve cevap + hangi ekin okunamadığını söyler (bkz. `service/notes_index.py`).""" + from .contract import RagIndexPayload + try: + payload = RagIndexPayload.from_wire(req.payload) + except (KeyError, TypeError) as exc: + return BridgeResponse.err(req, "malformed", + f"rag.index gövdesi eksik/yanlış: {exc}") + indexer = self.indexer + if indexer is None: + from ..service.notes_index import index_course_note as indexer + try: + cevap = indexer(payload, school=okul, blob_reader=self.blob_reader) + except Exception as exc: # noqa: BLE001 + import traceback + traceback.print_exc() + return BridgeResponse.err(req, "internal", + f"rag.index çalıştırılamadı: " + f"{type(exc).__name__}: {exc}") + if not isinstance(cevap, dict): + return BridgeResponse.err(req, "internal", + "rag.index bir nesne döndürmedi") + return BridgeResponse.ok(req, cevap) + def _govde(self, req: BridgeRequest, okul: str) -> dict: """Servis isteğinin ortak alanları: sorgu + ROL + okul. diff --git a/src/bridge/transport.py b/src/bridge/transport.py index 28230b3..8147690 100644 --- a/src/bridge/transport.py +++ b/src/bridge/transport.py @@ -15,17 +15,20 @@ Desen, kanıtlanmış bir istemciden alındı: `hezarfen_zeka/service/src/bridge ayrılır: 1. **İş yönü.** ZEKA `insight.*` YAZAR (backend'in açtığı akışlara cevap verir - ve kendi okuma/yazma akışlarını açar). RAG yalnız `Request`leri CEVAPLAR: - bugün açtığı istemci akışı YOKTUR, çünkü `rag.chat` cevabını hesaplamak için - okul verisi istemez (kapsamı çerçeve taşır) ve `rag.index` TİPLİ REDDEDER. + ve kendi okuma/yazma akışlarını açar). RAG `Request`leri CEVAPLAR ve + `rag.index` için kendi İSTEMCİ akışlarını açar: her ek dosyanın baytları + ayrı bir çift yönlü akışta `BlobRequest` → `BlobResponse` başlığı → tam + `size` HAM bayt olarak okunur (`read_blob`; şekil `protocol.rs:25-31`). + `rag.chat` hâlâ okul verisi istemez: kapsamı çerçeve taşır. 2. **Yetenekler.** İlan edilen küme `rag.chat` + `rag.index`tir (`ADVERTISED_CAPABILITIES`). Dispatcher `chat.reply`ı da KARŞILAR (backend yollarsa cevaplanır) ama onu İLAN ETMEYİZ: o yetenek chatbot'undur ve ilan etmek sohbet trafiğini RAG'e yönlendirmeye davetiye olurdu. 3. **Redler tiplidir.** Kayıt reddi (`unauthorized`, `unsupported_protocol`) loglanır; süreç ÇIKMAZ. -4. **`rag.index` bugün TİPLİ REDDEDER** (`dispatch.INDEX_UNWIRED`): taşıma onu - taşır ama "tamam" demez. +4. **`rag.index` SUNULUR.** Gövdesi `bridge/dispatch.py` → `service/notes_index.py`; + blob akışını bu modül açar (`_LoopBlobReader` ile executor thread'inden + köprülenir) ve not indeksi süreç-içidir (`index/notes.py`). BOOT POLİTİKASI (uygulanan; testle sabitlenen): * **Backend YOKKEN süreç DÜŞMEZ.** `run_forever` hiçbir hatada çıkmaz; üstel @@ -107,6 +110,12 @@ DEFAULT_BRIDGE_PORT = 8090 DEFAULT_BACKEND_URL = "http://hezarfen_backend:7656" CERT_FETCH_TIMEOUT_SECS = 10.0 """`GET /ai/certificate` için HTTP zaman aşımı.""" +BLOB_HEADER_TIMEOUT_SECS = 30.0 +"""Bir blob akışının BAŞLIK çerçevesi için bekleme: backend reddi ya da `ok`.""" +BLOB_BODY_TIMEOUT_SECS = 120.0 +"""Gövde için bekleme. backend gövdeyi 64 KiB'lik parçalarla akıtır +(`server.rs::write_blob_body`) ve her yazıya kendi takılma sınırını koyar; bu +sınır bizim tarafımızda, not indekslemesinin son tarihinin (120 s) altında.""" def _env_str(name: str, default: str) -> str: @@ -287,11 +296,12 @@ class BridgeTransport(QuicConnectionProtocol): """Tek bir QUIC bağlantısı: kontrol akışı + backend'in açtığı iş akışları.""" def __init__(self, *args, settings: Settings, handler, capabilities, - **kwargs) -> None: + dispatcher=None, **kwargs) -> None: super().__init__(*args, **kwargs) self._settings = settings self._handler = handler self._capabilities = tuple(capabilities) + self._dispatcher = dispatcher self._streams: dict[int, FrameStream] = {} self._control_sid: int | None = None self._ping_uid = 0 @@ -348,10 +358,54 @@ class BridgeTransport(QuicConnectionProtocol): greeting = await asyncio.wait_for(stream.read_frame(), timeout=GREETING_TIMEOUT_SECS) self.worker_id = parse_greeting(greeting) + # Blob okuma yolu BURADA takılır: `rag.index` executor thread'inde koşar + # (PING'ler durmasın) ve o thread'den QUIC akışı açmak bu köprüyü + # (`run_coroutine_threadsafe`) gerektirir. + if self._dispatcher is not None: + self._dispatcher.blob_reader = _LoopBlobReader(self) log("info", f"kayıt başarılı: worker_id={self.worker_id} " f"yetenekler={','.join(self._capabilities)}") return self.worker_id + # -- istemci başlatımlı akışlar: blob okuma -- + async def read_blob(self, request: dict, *, max_bytes: int, + header_timeout: float = BLOB_HEADER_TIMEOUT_SECS, + body_timeout: float = BLOB_BODY_TIMEOUT_SECS): + """Bir ekin baytlarını KENDİ istemci akışında oku. + + Şekil (`protocol.rs:25-31`): bir `BlobRequest` yaz, gönderme tarafını + bitir, BİR `BlobResponse` başlık çerçevesi oku; `ok` ise tam `size` + HAM bayt gelir (çerçeve DEĞİL — `AI_MAX_FRAME_BYTES` onları sınırlamaz), + sonra akış biter. Dönüş: `(header, bytes)`; red `BlobReadRefused`. + """ + from .contract import BlobReadRefused + sid = self._quic.get_next_available_stream_id() + stream = FrameStream() + self._streams[sid] = stream + try: + self._send_frame(sid, request, end=True) + header = await asyncio.wait_for(stream.read_frame(), timeout=header_timeout) + if not isinstance(header, dict): + raise BlobReadRefused("bad_header", "blob başlığı nesne değil") + if header.get("status") != "ok": + raise BlobReadRefused(str(header.get("code") or "unknown"), + str(header.get("message") or "")) + size = int(header.get("size") or 0) + if size < 0 or size > max_bytes: + raise BlobReadRefused( + "too_large", f"blob {size} bayt: sınır {max_bytes}") + body = await asyncio.wait_for(stream.read_exact(size), + timeout=body_timeout) + return header, body + except BlobReadRefused: + raise + except asyncio.TimeoutError as exc: + raise BlobReadRefused("timeout", "blob akışı zaman aşımına uğradı") from exc + except (BridgeFrameError, EOFError, ValueError) as exc: + raise BlobReadRefused("bad_header", str(exc)) from exc + finally: + self._streams.pop(sid, None) + async def keepalive(self) -> None: """QUIC PING. Uygulama düzeyinde heartbeat ÇERÇEVESİ yoktur (`ai/protocol.rs:13-14`); boşta kalma zaman aşımını bu önler.""" @@ -425,6 +479,33 @@ class BridgeTransport(QuicConnectionProtocol): self._streams.pop(sid, None) +class _LoopBlobReader: + """`rag.index`'in blob okuması için thread ↔ olay döngüsü köprüsü. + + Boru hattı (chunk + gömme) executor thread'inde koşar; QUIC akışı ise olay + döngüsünde açılır. Executor thread'inden `run_coroutine_threadsafe` ile + geçilir ve SENKRON beklenir — `rag.index` zaten arka planda, kimse + bekleyemez. + """ + + def __init__(self, protocol) -> None: + self._protocol = protocol + + def read(self, request: dict, *, max_bytes: int): + from concurrent.futures import TimeoutError as FutureTimeout + from .contract import BlobReadRefused + loop = getattr(self._protocol, "_loop", None) + if loop is None or loop.is_closed(): + raise BlobReadRefused("unavailable", "köprü olay döngüsü yok/ kapalı") + future = asyncio.run_coroutine_threadsafe( + self._protocol.read_blob(request, max_bytes=max_bytes), loop) + try: + return future.result( + timeout=BLOB_HEADER_TIMEOUT_SECS + BLOB_BODY_TIMEOUT_SECS) + except FutureTimeout as exc: + raise BlobReadRefused("timeout", "blob okuması zaman aşımına uğradı") from exc + + def _err_frame(kaynak, code: str, message: str) -> dict: """Türsüz bir hata için küçük bir `Response{status:"err"}` çerçevesi. @@ -447,7 +528,8 @@ async def run_once(settings: Settings, dispatcher: Dispatcher, log("info", f"{settings.host}:{settings.port} adresine bağlanılıyor " f"(ALPN {AI_ALPN})") create = partial(BridgeTransport, settings=settings, - handler=dispatcher.handle, capabilities=capabilities) + handler=dispatcher.handle, dispatcher=dispatcher, + capabilities=capabilities) async with connect(settings.host, settings.port, configuration=quic_config, create_protocol=create) as connection: await connection.wait_connected() diff --git a/src/generate/generator.py b/src/generate/generator.py index 6e0c13d..1b07f2f 100644 --- a/src/generate/generator.py +++ b/src/generate/generator.py @@ -306,11 +306,22 @@ class Generator: cost_recorder=None, role_ctx=None, response_cache=None, safety_classifier=None, context_packing: bool = False, context_max_tokens: int = 8000, context_reorder: bool = True, - rewriter=None, corpus_version: str = "", require_role: bool = False): + rewriter=None, corpus_version: str = "", require_role: bool = False, + note_index=None): self.retriever = retriever self.reranker = reranker - self.chunks_by_id = chunks_by_id - self.span_meta = span_meta + # Not kanalı (`rag.index`'in yazdığı indeks, bkz. src/index/notes.py). + # `chunks_by_id`/`span_meta` KORPUS KURULURKEN donar; not satırları ise + # çalışma anında gelir ve değişir — bu yüzden ikisi de canlı indekse + # bakan bir sarmalayıcıdan geçer. None ise davranış ÖNCEKİYLE AYNIDIR. + self.note_index = note_index + if note_index is not None: + from ..index.notes import NoteAwareChunks + self.chunks_by_id = NoteAwareChunks(chunks_by_id, note_index.chunk) + self.span_meta = NoteAwareChunks(span_meta, note_index.span) + else: + self.chunks_by_id = chunks_by_id + self.span_meta = span_meta self.llm = llm if llm is not None else LLMClient() self.ders = ders # PROVİZYONEL eşik — golden set (Faz 1.8) sonrası kalibre edilecek. @@ -499,6 +510,15 @@ class Generator: school=school) else: hits = self.retriever.retrieve(q, top_k=candidate_n, school=school) + # NOT KANALI (`rag.index`): okulun ders notları ders korpusunun YANINDA + # aranır. Okul süzgeci store'un kendisindedir; (sınıf, ders) kapısı not + # satırlarına UYGULANAMAZ çünkü telde notun sınıfı/dersi yoktur (bkz. + # `index/notes.py` başlığı — dürüst sınır). + if self.note_index is not None and school: + from ..index.notes import merge_hits + not_vurus = self.note_index.retrieve(q, self.retriever.embedder, + school=school, top_k=candidate_n) + hits = merge_hits(hits, not_vurus, candidate_n) contexts = rerank_select(q, hits, self.chunks_by_id, self.reranker, top_n=top_n, candidate_n=candidate_n) _tr("retrieve", n_hits=len(hits), n_contexts=len(contexts), diff --git a/src/index/notes.py b/src/index/notes.py new file mode 100644 index 0000000..174f8c5 --- /dev/null +++ b/src/index/notes.py @@ -0,0 +1,264 @@ +"""The course-note index — the retrieval channel `rag.index` fills. + +WHY IT IS ITS OWN INDEX. A textbook corpus is a file on disk +(`data/////kitap.pdf`) keyed by `(school, sinif, +ders)`. A course note names none of those on the wire: the `rag.index` payload +carries the note's `course` **uuid**, while a `rag.chat` scope pair carries a +class grade and a course **title** (derived by the backend from the asker's own +memberships) — and the backend's AI-read allowlist has no route that would let +this service resolve one to the other. There is no join, so a note cannot be +filed under a subject corpus. + +WHAT IT IS INSTEAD. One bucket per **school** — the tenant dimension every store +already filters on, by exact equality (`guard/tenant.py`). `replace_note()` swaps +a note's rows as one unit (a re-index never duplicates); `retrieve()` ranks that +bucket's rows and `rag.chat` merges the hits into the subject corpus's. + +HONEST LIMIT — the (class, subject) gate does not reach here. `can_access` +isolates class+subject for textbook chunks; a note carries neither on the wire, +so its rows cannot be checked against the asker's scope pairs. The backend still +refuses to *link* a citation the asker may not open (it stores `file: null`), +but a note's *text* from another course of the same school can be quoted. +Closing that needs the note's class+subject on the `rag.index` payload — a wire +change owned by the backend, not by this repo. + +IN-MEMORY, DERIVED, DISPOSABLE. Nothing here is a source of truth: a restart +loses it, and any note edit re-dispatches `rag.index` — the backend's own model +of a `rag_output` row ("derived data"). +""" +from __future__ import annotations + +import hashlib +import threading +from collections.abc import Mapping + +import numpy as np + +from src.index.dense import DenseIndex +from src.index.lexical import BM25Index +from src.retrieve.rrf import rrf_fuse +from src.retrieve.sparse import SparseIndex + +#: One attachment's byte ceiling — the backend's own `MAX_MAX_FILE_BYTES` +#: (`constant.rs:80`). A blob header promising more is refused before a byte of +#: the body is read. +MAX_NOTE_FILE_BYTES = 25 * 1024 * 1024 + + +def doc_id_for_bytes(data: bytes) -> str: + """Content-derived document id — the same rule the textbook path uses + (`ingest/canonical.py`: the first 12 hex of the sha256). Identical bytes + hash to one document, which is exactly what the backend's citation + resolver expects (several files may claim one doc id).""" + return hashlib.sha256(data).hexdigest()[:12] + + +class _Bucket: + """One school's note rows, plus indexes rebuilt lazily after a write.""" + + def __init__(self) -> None: + self.ids: list[str] = [] + self.texts: list[str] = [] + self.vectors: list[np.ndarray] = [] + self.sparse: list[dict] = [] + self.chunks: dict = {} # chunk_id -> Chunk + self.spans: dict = {} # span_id -> {"page", "bbox"} + self.owner: dict = {} # chunk_id -> note key + self.dense = None + self.bm25 = None + self.spar = None + self.dirty = True + + def rebuild(self, school: str) -> None: + if not self.dirty: + return + if self.ids: + self.dense = DenseIndex(dim=1024).build( + list(self.ids), np.asarray(self.vectors, dtype=np.float32), + school=school) + self.bm25 = BM25Index().build(list(self.ids), list(self.texts), + school=school) + self.spar = SparseIndex().build(list(self.ids), list(self.sparse), + school=school) + else: + self.dense = self.bm25 = self.spar = None + self.dirty = False + + +class NoteIndex: + """School-scoped course-note rows + their three retrieval indexes. + + Thread-safe: `rag.index` runs in the transport's executor thread while + `rag.chat` retrieves on request threads. + """ + + def __init__(self) -> None: + self._buckets: dict[str, _Bucket] = {} + self._lock = threading.Lock() + + # -- yazma ------------------------------------------------------------ + def replace_note(self, school: str, course_note: str, rows) -> int: + """Swap one note's rows for `rows` — the note-level unit of update. + + `rows` is `[(Chunk, dense_vector, sparse_dict), ...]`. The previous rows + of this note are dropped first, so a re-index is idempotent by + construction (chunk ids are note-scoped; nothing survives to duplicate). + """ + from src.guard.tenant import require_owner + sahip = require_owner(school) + with self._lock: + bucket = self._buckets.setdefault(sahip, _Bucket()) + self._drop_locked(bucket, course_note) + for chunk, vector, sparse in rows: + cid = chunk.chunk_id + bucket.ids.append(cid) + bucket.texts.append(chunk.text) + bucket.vectors.append(np.asarray(vector, dtype=np.float32)) + bucket.sparse.append({str(k): float(v) for k, v in dict(sparse).items()}) + bucket.chunks[cid] = chunk + bucket.owner[cid] = course_note + for sid in chunk.span_ids: + bucket.spans[sid] = {"page": chunk.page_start, + "bbox": (0.0, 0.0, 0.0, 0.0)} + bucket.dirty = True + return len(rows) + + def drop_note(self, school: str, course_note: str) -> int: + from src.guard.tenant import require_owner + sahip = require_owner(school) + with self._lock: + bucket = self._buckets.get(sahip) + if bucket is None: + return 0 + n = self._drop_locked(bucket, course_note) + bucket.dirty = True + return n + + @staticmethod + def _drop_locked(bucket: _Bucket, course_note: str) -> int: + victims = [cid for cid, owner in bucket.owner.items() if owner == course_note] + if not victims: + return 0 + drop = set(victims) + keep = [i for i, cid in enumerate(bucket.ids) if cid not in drop] + bucket.ids = [bucket.ids[i] for i in keep] + bucket.texts = [bucket.texts[i] for i in keep] + bucket.vectors = [bucket.vectors[i] for i in keep] + bucket.sparse = [bucket.sparse[i] for i in keep] + for cid in victims: + cid_chunk = bucket.chunks.pop(cid, None) + bucket.owner.pop(cid, None) + for sid in (getattr(cid_chunk, "span_ids", None) or []): + bucket.spans.pop(sid, None) + return len(victims) + + # -- okuma ------------------------------------------------------------ + def retrieve(self, query: str, embedder, *, school: str, top_k: int = 40, + rrf_k: int = 60): + """Rank this school's note rows — `[(chunk_id, rrf_score), ...]`. + + The tenant filter is the store's own (`school=` on every index search): + another school's notes, and rows with no school stamp, are never + returned (`guard/tenant.py`). + """ + if not query or not query.strip() or not school: + return [] + with self._lock: + bucket = self._buckets.get(school) + if bucket is None or not bucket.ids: + return [] + bucket.rebuild(school) + dense, bm25, spar = bucket.dense, bucket.bm25, bucket.spar + sorgu = getattr(embedder, "embed_query", None) + qv = sorgu(query)[0] if sorgu is not None else embedder.embed([query])[0] + rankings = [dense.search(qv, top_k, school=school), + bm25.search(query, top_k, school=school)] + if spar is not None: + qs = embedder.embed_sparse([query])[0] + rankings.append(spar.search(qs, top_k, school=school)) + return rrf_fuse(rankings, k=rrf_k, top_k=top_k) + + def chunk(self, chunk_id: str): + with self._lock: + for bucket in self._buckets.values(): + if chunk_id in bucket.chunks: + return bucket.chunks[chunk_id] + return None + + def span(self, span_id: str): + with self._lock: + for bucket in self._buckets.values(): + if span_id in bucket.spans: + return bucket.spans[span_id] + return None + + def stats(self) -> dict: + with self._lock: + return {school: len(bucket.ids) for school, bucket in self._buckets.items() + if bucket.ids} + + +_SHARED: NoteIndex | None = None +_SHARED_LOCK = threading.Lock() + + +def shared_note_index() -> NoteIndex: + """The process-wide note index. + + `rag.index` (transport thread) and `rag.chat` (request threads) must see the + same rows, and the service is built per corpus — so the store is a process + singleton, like `guard/tenant.py`'s rules and the provider configuration. + """ + global _SHARED + with _SHARED_LOCK: + if _SHARED is None: + _SHARED = NoteIndex() + return _SHARED + + +class NoteAwareChunks(Mapping): + """`{chunk_id: object}` that falls back to the note index. + + `Generator` holds `chunks_by_id` and `span_meta` — both built once, from a + corpus that was on disk at build time. Note rows arrive later (and are + replaced), so lookups consult the live note index first; the base mapping + answers everything else. Read-only `Mapping` is enough: the pipeline only + reads (`cid in chunks`, `chunks[cid].text`, `span_meta.get(sid)`). + """ + + def __init__(self, base, lookup) -> None: + self._base = base + self._lookup = lookup # (key) -> value | None + + def __getitem__(self, key): + found = self._lookup(key) + if found is not None: + return found + return self._base[key] + + def __iter__(self): + yield from self._base + # Live rows are not enumerated: the base keys are what a caller + # iterates for counts/aggregates, and the note rows are already found + # by id. Enumerating them here would silently change `len()` semantics. + + def __len__(self) -> int: + return len(self._base) + + def get(self, key, default=None): + found = self._lookup(key) + return found if found is not None else self._base.get(key, default) + + def __contains__(self, key) -> bool: + return self._lookup(key) is not None or key in self._base + + +def merge_hits(base_hits, extra_hits, top_k: int, *, rrf_k: int = 60): + """RRF-merge two best-first rank lists — the subject corpus's hits and the + school's note hits. Ranks (not scores) are what RRF uses, which is exactly + what two differently-calibrated indexes need.""" + if not extra_hits: + return base_hits + if not base_hits: + return extra_hits[:top_k] + return rrf_fuse([base_hits, extra_hits], k=rrf_k, top_k=top_k) diff --git a/src/service/http_app.py b/src/service/http_app.py index 78228dd..e712962 100644 --- a/src/service/http_app.py +++ b/src/service/http_app.py @@ -613,6 +613,7 @@ def build_service(book_path: str, *, school, sinif: str, ders: str, from ..ingest.canonical import build_canonical from ..chunk import chunk_document from ..index import DenseIndex, BM25Index + from ..index.notes import shared_note_index from ..retrieve import SparseIndex, HybridRetriever from ..generate import Generator, QuestionGenerator, build_span_meta from ..summarize.summarizer import Summarizer @@ -715,7 +716,11 @@ def build_service(book_path: str, *, school, sinif: str, ders: str, gen = Generator(retr, reranker, by_id, span_meta, ders=ders, safety_classifier=LLMSafetyClassifier(), context_packing=True, corpus_version=cv, require_role=True, # STRICT: rolsüz istek fail-closed - response_cache=response_cache, rewriter=rewriter) + response_cache=response_cache, rewriter=rewriter, + # Ders notları (`rag.index`) bu korpusun YANINDA aranır: + # süreç-içi tek indeks, çünkü `rag.index` korpus nesnesine + # değil okula yazar (bkz. src/index/notes.py). + note_index=shared_note_index()) return RagService(gen, doc=doc, summarizer=Summarizer(), question_gen=QuestionGenerator(), ders=ders, school=sahip) diff --git a/src/service/notes_index.py b/src/service/notes_index.py new file mode 100644 index 0000000..97a6522 --- /dev/null +++ b/src/service/notes_index.py @@ -0,0 +1,216 @@ +"""`rag.index` — the write path: note + attachments → chunks → vectors → the +note index (`src/index/notes.py`), and the answer object the backend stores. + +WHAT ONE REQUEST DOES + + 1. the note's own `title` + `content` become one document (always); + 2. each `files[]` entry is read as **bytes over its own QUIC blob stream** + (`BlobRequest` → `BlobResponse` header → exactly `size` raw bytes), then + parsed by content type — PDFs through the same canonical loader the + textbook corpus uses (`ingest/canonical.build_canonical`), plain text + decoded directly; + 3. every document is chunked (`chunk.chunk_document`) and embedded in one + pass (`embed_both`: dense + sparse, the provider configured by + `RAG_EMBED_*`); + 4. the note's rows replace whatever this note held before (one unit — a + re-index cannot duplicate); + 5. the answer echoes `files[].id` so the backend can stamp the doc id it + minted onto the attachment row, and names any attachment that failed. + +A FAILED ATTACHMENT DOES NOT ABORT THE INDEX. A blob read that refuses (missing +file, permission, unknown type) is recorded and the rest — including the note +body — is indexed: a partly indexed note beats no note. The backend keeps the +previous `rag_output` rows when the whole round trip fails, which is why a +refusal must be typed rather than answered with an empty "ok". +""" +from __future__ import annotations + +import os +import tempfile + +from ..bridge.contract import BlobReadRefused, RagIndexPayload +from ..index.notes import (MAX_NOTE_FILE_BYTES, doc_id_for_bytes, + shared_note_index) + +PDF_TYPES = ("application/pdf", "application/x-pdf") +TEXT_TYPES = ("text/plain", "text/markdown", "text/csv", "application/json") + + +def _is_pdf(name: str, content_type: str) -> bool: + return (content_type or "").lower() in PDF_TYPES or \ + (name or "").lower().endswith(".pdf") + + +def _text_units(doc, text: str, *, page: int = 1): + """`text` → canonical units (one per non-empty paragraph). + + The chunker consumes `CanonicalUnit`s, so the note's own prose rides the + exact same pipeline as a parsed PDF page — no second chunker, no second + span scheme. + """ + from ..ingest.canonical import CanonicalUnit, make_span_id + units = [] + for n, parca in enumerate(p for p in text.split("\n") if p.strip()): + units.append(CanonicalUnit( + span_id=make_span_id(doc.doc_id, page, n), doc_id=doc.doc_id, + sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu, + page=page, bbox=(0.0, 0.0, 0.0, 0.0), block_no=n, + kind="paragraph", text=parca.strip(), page_visual="low_visual", + retrieval_disi=False)) + return units + + +def _body_doc(payload: RagIndexPayload): + """The note's own title + content — doc id is the note's own record key, + so a re-index replaces rows instead of piling up new ones.""" + from ..ingest.canonical import CanonicalDoc + doc = CanonicalDoc(source_path="", doc_id=payload.course_note, + source_version=payload.course_note, sinif="", ders="", + kaynak_turu="konu_ozeti", page_count=1) + doc.units = _text_units(doc, f"{payload.title}\n{payload.content}") + return doc + + +def _plain_doc(name: str, data: bytes, *, doc_id: str): + from ..ingest.canonical import CanonicalDoc + metin = data.decode("utf-8", errors="replace") + doc = CanonicalDoc(source_path=name, doc_id=doc_id, + source_version=doc_id, sinif="", ders="", + kaynak_turu="konu_ozeti", page_count=1) + doc.units = _text_units(doc, metin) + return doc + + +def _pdf_doc(name: str, data: bytes, *, doc_id: str): + """PDF bytes → canonical document, through the corpus's own loader. + + `build_canonical` reads a path, so the bytes land in a temp file first; the + doc id is computed from the bytes here (not from the temp path) so it stays + the content hash the citation resolver expects. + """ + from ..ingest.canonical import build_canonical + fd, yol = tempfile.mkstemp(suffix=".pdf", prefix="not-eki-") + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + doc = build_canonical(yol, sinif="", ders="", kaynak_turu="konu_ozeti") + doc.source_path = name + doc.doc_id = doc_id # sha256 of the same bytes + for unit in doc.units: + unit.doc_id = doc_id + unit.span_id = unit.span_id.replace(doc.doc_id, doc_id, 0) \ + if unit.span_id.startswith(doc.doc_id) else unit.span_id + return doc + finally: + try: + os.unlink(yol) + except OSError: + pass + + +def _chunks_for(doc, course_note: str): + """Children only, note-scoped ids (two notes sharing one PDF must not + collide), no parent links (no parent rows are stored).""" + from ..chunk import chunk_document + out = [] + for chunk in chunk_document(doc): + if chunk.level != "child": + continue + chunk.chunk_id = f"{course_note}:{chunk.chunk_id}" + chunk.parent_id = None + out.append(chunk) + return out + + +def index_course_note(payload: RagIndexPayload, *, school: str, + blob_reader=None, note_index=None, embedder=None) -> dict: + """Index one course note and return the answer object the backend stores.""" + index = note_index if note_index is not None else shared_note_index() + if embedder is None: + from ..embed.provider import build_embedder + embedder = build_embedder() + + docs = [_body_doc(payload)] + indexed_files, failed_files = [], [] + + for meta in payload.files: + try: + header, data = _read_file(meta, school=school, + author=payload.author, blob_reader=blob_reader) + except BlobReadRefused as exc: + failed_files.append({"id": meta.id, "name": meta.name, + "code": exc.code, "message": exc.message}) + continue + name = str(header.get("name") or meta.name or "") + content_type = str(header.get("content_type") or meta.content_type or "") + doc_id = doc_id_for_bytes(data) + try: + if _is_pdf(name, content_type): + doc = _pdf_doc(name, data, doc_id=doc_id) + elif (content_type or "").lower() in TEXT_TYPES or \ + name.lower().endswith((".txt", ".md", ".csv", ".json")): + doc = _plain_doc(name, data, doc_id=doc_id) + else: + raise BlobReadRefused("unsupported_type", + f"'{content_type or 'bilinmeyen'}' türü " + "indekslenemiyor") + except BlobReadRefused as exc: + failed_files.append({"id": meta.id, "name": name, + "code": exc.code, "message": exc.message}) + continue + except Exception as exc: # noqa: BLE001 + failed_files.append({"id": meta.id, "name": name, "code": "parse_failed", + "message": f"{type(exc).__name__}: {exc}"}) + continue + docs.append(doc) + indexed_files.append({"id": meta.id, "doc_id": doc_id, "name": name}) + + chunks = [] + for doc in docs: + chunks.extend(_chunks_for(doc, payload.course_note)) + rows = [] + if chunks: + texts = [c.text for c in chunks] + vecs, sparse = embedder.embed_both(texts, batch_size=16) + rows = [(chunk, vec, sp) for chunk, vec, sp in zip(chunks, vecs, sparse)] + n = index.replace_note(school, payload.course_note, rows) + + return { + "course_note": payload.course_note, + "chunks": n, + "files": indexed_files, + "failed": failed_files, + "summary": _summary(payload.title, n, indexed_files, failed_files), + } + + +def _read_file(meta, *, school: str, author: str, blob_reader): + """One attachment's bytes over its own blob stream. + + The request shape is the bridge's (`protocol.rs::BlobRequest`): the file's + record id, the school slug, and the note's author as `on_behalf_of` — the + `ai` principal can view no course, so a read as itself always earns + `forbidden`. + """ + if blob_reader is None: + raise BlobReadRefused("blob_unavailable", + "bu servis örnekte blob okuma yolu yok") + if int(meta.size or 0) > MAX_NOTE_FILE_BYTES: + raise BlobReadRefused("too_large", + f"ek {meta.size} bayt: sınır {MAX_NOTE_FILE_BYTES}") + return blob_reader.read({"id": meta.id, "school": school, "file": meta.id, + "on_behalf_of": author}, + max_bytes=MAX_NOTE_FILE_BYTES) + + +def _summary(title: str, chunks: int, indexed_files, failed_files) -> str: + """One or two Turkish sentences — the human is the reader of this payload.""" + baslik = (title or "").strip() or "Ders notu" + ek = (f", {len(indexed_files)} ek dosyayla" if indexed_files else "") + metin = (f"'{baslik}' notu indekslendi: {chunks} metin parçası{ek}. " + "Bu not artık sorularda kaynak olarak kullanılabilir.") + if failed_files: + adlar = ", ".join(str(f.get("name") or f.get("id")) for f in failed_files) + metin += (f" Şu ekler okunamadı ve indekslenemedi: {adlar} — " + "notun kendi metni yine de indekslendi.") + return metin diff --git a/tests/unit/_fake_bridge.py b/tests/unit/_fake_bridge.py index 4f57b45..c933b8b 100644 --- a/tests/unit/_fake_bridge.py +++ b/tests/unit/_fake_bridge.py @@ -231,6 +231,11 @@ class _Connection(QuicConnectionProtocol): self._quic.send_stream_data(sid, encode_frame(obj), end_stream=end) self.transmit() + def send_bytes(self, sid: int, data: bytes, end: bool) -> None: + """Ham bayt — blob gövdesi çerçeve DEĞİLDİR (`protocol.rs:27-30`).""" + self._quic.send_stream_data(sid, data, end_stream=end) + self.transmit() + def forget(self, sid: int) -> None: self._readers.pop(sid, None) @@ -290,9 +295,12 @@ class _Connection(QuicConnectionProtocol): # -- istemci başlatımlı akışlar -- async def _serve_client_stream(self, sid: int, reader: _Reader) -> None: - """Bugün istemci HİÇ akış açmaz (RAG yalnız `Request` cevaplar). + """İstemci başlatımlı akış = BİR blob okuma (`rag.index`). - Açarsa bu bir kayıttır: sunucu tipli bir red yazar ki bekleyen bir + Bir `BlobRequest` (gerekli alan: `file`) → `BlobResponse` başlığı; `ok` + ise tam `size` **ham** bayt (`server.rs::serve_blob`). Başlıktan sonraki + gövde çerçeve DEĞİLDİR. Kayıtlı olmayan bir dosya `not_found` ile + reddedilir; başka bir çerçeve de tipli reddedilir ki bekleyen bir okuyucu asılı kalmasın.""" try: raw = await reader.read_frame() @@ -300,9 +308,24 @@ class _Connection(QuicConnectionProtocol): self._bridge.client_streams.append({"malformed": str(exc)}) self.send(sid, _err("", "", "malformed", str(exc)), end=True) return - self._bridge.client_streams.append(raw if isinstance(raw, dict) else {}) - self.send(sid, _err(str(raw.get("id") or ""), str(raw.get("school") or ""), - "malformed", "bu servis istemci akışı açmıyor"), end=True) + if not isinstance(raw, dict) or raw.get("file") is None: + self._bridge.client_streams.append(raw if isinstance(raw, dict) else {}) + self.send(sid, _err(str((raw or {}).get("id") or ""), + str((raw or {}).get("school") or ""), "malformed", + "bu servis yalnız blob okuma akışı açar"), end=True) + return + self._bridge.blob_requests.append(raw) + entry = self._bridge.blobs.get(str(raw.get("file"))) + if entry is None: + self.send(sid, {"status": "err", "id": raw.get("id") or "", + "school": raw.get("school") or "", "code": "not_found", + "message": "no such course-note file"}, end=True) + return + name, content_type, data = entry + self.send(sid, {"status": "ok", "id": raw.get("id") or "", + "school": raw.get("school") or "", "name": name, + "content_type": content_type, "size": len(data)}, end=False) + self.send_bytes(sid, data, end=True) def _err(request_id: str, school: str, code: str, message: str) -> dict: @@ -353,6 +376,10 @@ class FakeBridge: self.rejects: list[str] = [] #: İstemcinin açtığı (kontrol dışı) akışların çerçeveleri. self.client_streams: list[dict] = [] + #: `rag.index` blob okumaları: file id → (name, content_type, bytes). + self.blobs: dict[str, tuple[str, str, bytes]] = {} + #: Gelen her `BlobRequest` çerçevesi (sırayla) — okul/adına-okuma kanıtı. + self.blob_requests: list[dict] = [] self._port = port self._server: Any = None self._quic_config: Any = None @@ -451,6 +478,11 @@ class FakeBridge: self._connections.add(worker.connection) self._worker_event.set() + def add_blob(self, file_id: str, data: bytes, *, name: str = "ek.pdf", + content_type: str = "application/pdf") -> None: + """Bir ders-notu ekinin baytlarını servise sun (blob okuma için).""" + self.blobs[str(file_id)] = (name, content_type, data) + def deregister(self, worker: _Worker) -> None: self._connections.discard(worker.connection) self.workers = [w for w in self.workers if w.worker_id != worker.worker_id] diff --git a/tests/unit/test_bridge_transport.py b/tests/unit/test_bridge_transport.py index be1ba9d..e14b34b 100644 --- a/tests/unit/test_bridge_transport.py +++ b/tests/unit/test_bridge_transport.py @@ -62,10 +62,11 @@ def _ayarlar(bridge: FakeBridge, *, port: int | None = None, **ustune) -> Settin @contextlib.asynccontextmanager -async def _calisan_kopru(bridge: FakeBridge, servis: _SahteServis, **ustune): +async def _calisan_kopru(bridge: FakeBridge, servis: _SahteServis, *, + indexer=None, **ustune): """Köprüyü arka planda koştur, çıkışta temizle.""" gorev = asyncio.ensure_future( - run_forever(_ayarlar(bridge, **ustune), Dispatcher(servis))) + run_forever(_ayarlar(bridge, **ustune), Dispatcher(servis, indexer=indexer))) try: yield gorev finally: @@ -188,12 +189,13 @@ class KopruTasimaTestleri(unittest.TestCase): await akis2.read(timeout=0.5) akis2.close() - # (c) `rag.index` ilan edilir ama HENÜZ sunulmaz: "tamam" - # demek sessiz bir yalandır, backend eski çıktıyı korur. + # (c) `rag.index` SUNULUR: gövdesi eksikse TİPLİ reddedilir + # (uydurma "tamam" yok; gövde tam olduğunda yol aşağıdaki + # testte blob akışıyla uçtan uca koşar). indeks = await bridge.call("rag.index", "okul-a", {"course_note": "N1"}) self.assertEqual(indeks["status"], "err") - self.assertEqual(indeks["code"], "index_path_unwired") + self.assertEqual(indeks["code"], "malformed") self.assertEqual(indeks["school"], "okul-a") # (d) Hepsinin ardından normal istek cevaplanıyor. @@ -367,3 +369,119 @@ class OrtamAdlariTestleri(unittest.TestCase): self.assertEqual(ayar.reconnect_max_secs, 60.0) # Özet SIR vermez: anahtarın kendisi değil, var/yok bilgisi yazılır. self.assertNotIn("test-token", ayar.summary()) + + +class RagIndexBlobAkisiTestleri(unittest.TestCase): + """`rag.index` uçtan uca: çerçeve → (sahte) dizinleyici → BLOB AKIŞI → cevap. + + Ölçülen iddia: ekin baytları kendi istemci akışında, ham olarak (çerçeve + DEĞİL) gelir; cevap `files[].id`yi isteğin verdiği id ile AYNEN yankılar + (backend `course_note_file.rag_doc_id`yi yalnız bu eşleşmeden doldurur). + """ + + BAYT = (b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n" + b"%%EOF\n" * 20) + + def test_ek_baytlari_blob_akisindan_okunur_ve_id_yankilanir(self): + okumalar: list = [] + + def sahte_indeksleyici(payload, *, school, blob_reader): + meta = payload.files[0] + header, data = blob_reader.read( + {"id": f"ULID-{meta.id}", "school": school, "file": meta.id, + "on_behalf_of": payload.author}, + max_bytes=8 * 1024 * 1024) + okumalar.append((header, data)) + return {"course_note": payload.course_note, + "chunks": 1, + "files": [{"id": meta.id, "doc_id": "5eda1f0a9c32"}], + "summary": f"'{payload.title}' notu indekslendi."} + + async def senaryo() -> None: + bridge = FakeBridge() + bridge.add_blob("01FILE", self.BAYT, name="kaynak.pdf", + content_type="application/pdf") + await bridge.start() + try: + async with _calisan_kopru(bridge, _SahteServis(), + indexer=sahte_indeksleyici): + await bridge.wait_for_worker(timeout=10) + cevap = await bridge.call("rag.index", "okul-a", { + "course_note": "01NOTE", "course": "01COURSE", + "author": "01AUTHOR", "title": "Hücre ve Canlılar", + "content": "Hücre, canlıların en küçük yapı birimidir.", + "files": [{"id": "01FILE", "name": "kaynak.pdf", + "content_type": "application/pdf", + "size": len(self.BAYT)}]}) + + self.assertEqual(cevap["status"], "ok") + self.assertEqual(cevap["school"], "okul-a") + govde = cevap["payload"] + self.assertEqual(govde["course_note"], "01NOTE") + # id AYNEN yankılanır → backend ekin satırını damgalar. + self.assertEqual(govde["files"][0]["id"], "01FILE") + self.assertEqual(govde["files"][0]["doc_id"], "5eda1f0a9c32") + + # Baytlar ham aktı: çerçeve çözülmedi, tam boyutta geldi. + self.assertEqual(len(okumalar), 1) + header, data = okumalar[0] + self.assertEqual(header["status"], "ok") + self.assertEqual(header["size"], len(self.BAYT)) + self.assertEqual(header["name"], "kaynak.pdf") + self.assertEqual(data, self.BAYT) + + # İstek backend'e okul + ADINA OKUMA ile gitti. + istek = bridge.blob_requests[0] + self.assertEqual(istek["school"], "okul-a") + self.assertEqual(istek["file"], "01FILE") + self.assertEqual(istek["on_behalf_of"], "01AUTHOR") + finally: + await bridge.stop() + + asyncio.run(senaryo()) + + def test_okunamayan_ek_indekslemeyi_durdurmaz(self): + """Blob `not_found` derse dizinleme REDDEDİLMEZ: notun kendi metni + indekslenir ve cevap hangi ekin okunamadığını söyler (backend eski + satırı koruyacağı için "sessiz tamam" en kötü sonuçtur).""" + cevaplar: list = [] + + def sahte_indeksleyici(payload, *, school, blob_reader): + from src.bridge.contract import BlobReadRefused + hata = None + try: + blob_reader.read({"id": "ULID", "school": school, + "file": payload.files[0].id, + "on_behalf_of": payload.author}, + max_bytes=1 << 20) + except BlobReadRefused as exc: + hata = exc + cevaplar.append(hata) + return {"course_note": payload.course_note, "chunks": 2, "files": [], + "failed": [{"id": payload.files[0].id, "code": hata.code, + "message": hata.message}], + "summary": f"'{payload.title}' notu indekslendi."} + + async def senaryo() -> None: + bridge = FakeBridge() # blobs BOŞ: dosya yok + await bridge.start() + try: + async with _calisan_kopru(bridge, _SahteServis(), + indexer=sahte_indeksleyici): + await bridge.wait_for_worker(timeout=10) + cevap = await bridge.call("rag.index", "okul-a", { + "course_note": "01NOTE", "course": "01COURSE", + "author": "01AUTHOR", "title": "Hücre", + "content": "Hücre...", + "files": [{"id": "01YOK", "name": "yok.pdf", + "content_type": "application/pdf", + "size": 10}]}) + self.assertEqual(cevap["status"], "ok") + self.assertEqual(cevap["payload"]["failed"][0]["code"], + "not_found") + self.assertIsNotNone(cevaplar[0]) + self.assertEqual(cevaplar[0].code, "not_found") + finally: + await bridge.stop() + + asyncio.run(senaryo()) diff --git a/tests/unit/test_notes_index.py b/tests/unit/test_notes_index.py new file mode 100644 index 0000000..48fc685 --- /dev/null +++ b/tests/unit/test_notes_index.py @@ -0,0 +1,205 @@ +"""`rag.index` dizinleme yolu — çevrimdışı (ağ YOK, model YOK). + +Sahte gömme sağlayıcısı SABİT (hash tohumlu) vektörler üretir; sahte blob +okuyucu baytları yerel sözlükten verir. Testin ölçtüğü iddialar: + + 1. notun KENDİ başlık+içeriği ek olmadan da indekslenir; + 2. ekler okunur, `files[].id` AYNEN yankılanır (`doc_id` içerik sha256'sıdır); + 3. yeniden indeksleme ÇOĞALTMAZ (notun satırları değiştirilir); + 4. okunamayan bir ek dizinlemeyi DURDURMAZ ve cevapta adı geçer; + 5. not kanalı okul süzgeciyle aranır (başka okulun satırı görünmez). +""" +from __future__ import annotations + +import hashlib +import unittest + +import numpy as np + +from src.bridge.contract import BlobReadRefused, RagIndexPayload, RagFile +from src.index.notes import NoteIndex, doc_id_for_bytes +from src.service.notes_index import index_course_note + + +class SahteEmbedder: + """Deterministik, ağsız gömme. Dense: tohumlu rastgele 1024 boyut.""" + + def _vec(self, text: str) -> np.ndarray: + tohum = int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "big") + return np.random.default_rng(tohum).random(1024).astype(np.float32) + + def embed(self, texts, batch_size=None): + return [self._vec(t) for t in texts] + + def embed_query(self, query): + return [self._vec(query)] + + def embed_sparse(self, texts): + return [{w: 1.0 for w in t.lower().split()} for t in texts] + + def embed_both(self, texts, batch_size=16): + return self.embed(texts), self.embed_sparse(texts) + + +class SahteBlobOkuyucu: + def __init__(self, blobs, *, refuse=()): + self.blobs = blobs + self.refuse = set(refuse) + self.istekler: list[dict] = [] + + def read(self, request, *, max_bytes): + self.istekler.append(dict(request)) + fid = str(request["file"]) + if fid in self.refuse: + raise BlobReadRefused("forbidden", "bu dosyayı göremiyorsun") + name, content_type, data = self.blobs[fid] + return ({"status": "ok", "name": name, "content_type": content_type, + "size": len(data)}, data) + + +def _payload(**ustune) -> RagIndexPayload: + alanlar = dict(course_note="01NOTE", course="01COURSE", author="01AUTHOR", + title="Hücre ve Canlıların Ortak Özellikleri", + content="Hücre, canlıların en küçük yapı ve görev birimidir.", + files=[]) + alanlar.update(ustune) + return RagIndexPayload(**alanlar) + + +class NotIndekslemeTestleri(unittest.TestCase): + def setUp(self) -> None: + self.index = NoteIndex() + self.embedder = SahteEmbedder() + + def _indeksle(self, payload=None, reader=None): + return index_course_note(payload or _payload(), school="okul-a", + blob_reader=reader, note_index=self.index, + embedder=self.embedder) + + def test_ek_olmadan_da_notun_kendi_metni_indekslenir(self): + """Şart: başlık + içerik HER durumda indekslenir (ek yoksa bile).""" + cevap = self._indeksle() + self.assertEqual(cevap["course_note"], "01NOTE") + self.assertGreater(cevap["chunks"], 0) + self.assertEqual(cevap["files"], []) + # Özet insan içindir: notun başlığını anar (Türkçe, 1-2 cümle). + self.assertIn("Hücre ve Canlıların Ortak Özellikleri", cevap["summary"]) + # Satırlar okul damgasıyla yazıldı (kiracılık). + self.assertEqual(self.index.stats(), {"okul-a": cevap["chunks"]}) + + def test_ek_baytlari_okunur_ve_idler_aynen_yankilanir(self): + """`files[].id` isteğin verdiği id OLMALI; `doc_id` içerik sha256'sı.""" + data = "Hücre zarı, sitoplazma ve çekirdek.".encode("utf-8") + reader = SahteBlobOkuyucu({"01FILE": ("ozet.txt", "text/plain", data)}) + cevap = self._indeksle( + _payload(files=[RagFile(id="01FILE", name="ozet.txt", + content_type="text/plain", size=len(data))]), + reader) + self.assertEqual(cevap["files"], [{"id": "01FILE", + "doc_id": doc_id_for_bytes(data), + "name": "ozet.txt"}]) + self.assertEqual(cevap["failed"], []) + # İstek ADINA OKUMA taşır: `ai` görevlisi hiçbir dersi göremez. + self.assertEqual(reader.istekler[0]["on_behalf_of"], "01AUTHOR") + self.assertEqual(reader.istekler[0]["school"], "okul-a") + + def test_yeniden_indeksleme_cogaltmaz(self): + """Aynı not iki kez indekslenirse satır sayısı İKİYE KATLANMAZ.""" + self._indeksle() + ilk = self.index.stats()["okul-a"] + self._indeksle() + ikinci = self.index.stats()["okul-a"] + self.assertGreater(ilk, 0) + self.assertEqual(ikinci, ilk) + + def test_okunamayan_ek_dizinlemeyi_durdurmaz(self): + """Reddedilen ek atlanır; notun kendi metni indekslenir ve adı geçer.""" + reader = SahteBlobOkuyucu({}, refuse={"01YOK"}) + cevap = self._indeksle( + _payload(files=[RagFile(id="01YOK", name="yok.pdf", + content_type="application/pdf", size=10)]), + reader) + self.assertGreater(cevap["chunks"], 0) + self.assertEqual(cevap["files"], []) + self.assertEqual(cevap["failed"][0]["id"], "01YOK") + self.assertEqual(cevap["failed"][0]["code"], "forbidden") + self.assertIn("yok.pdf", cevap["summary"]) + + def test_blob_okuyucusu_yoksa_not_yine_indekslenir(self): + """Taşıma blob okuyucusunu takmamışsa (ör. yalın test) ekler düşer, + notun metni DÜŞMEZ.""" + cevap = self._indeksle( + _payload(files=[RagFile(id="01FILE", name="a.txt", + content_type="text/plain", size=3)]), + None) + self.assertGreater(cevap["chunks"], 0) + self.assertEqual(cevap["failed"][0]["code"], "blob_unavailable") + + def test_not_kanali_okulla_suzulur(self): + """Arama okul süzgeçlidir: başka okul bu notu GÖRMEZ.""" + data = "Fotosentez, klorofil ile ışık enerjisini bağlar.".encode("utf-8") + reader = SahteBlobOkuyucu({"01FILE": ("foto.txt", "text/plain", data)}) + self._indeksle( + _payload(files=[RagFile(id="01FILE", name="foto.txt", + content_type="text/plain", size=len(data))]), + reader) + bulunan = self.index.retrieve("fotosentez klorofil", self.embedder, + school="okul-a") + self.assertTrue(bulunan, "not kanalı kendi okulunda bulunmalı") + parcalar = [self.index.chunk(cid) for cid, _ in bulunan] + ekli = [c for c in parcalar if "klorofil" in c.text] + self.assertTrue(ekli, "ekin metni kanalda bulunmalı") + # Ekin parçası içerik sha256'sını doc_id olarak taşır (atıf eşleşmesi). + self.assertEqual(ekli[0].doc_id, doc_id_for_bytes(data)) + # Başka okul: damgasız/başka okulun satırı ASLA dönmez. + self.assertEqual( + self.index.retrieve("fotosentez", self.embedder, school="okul-b"), []) + + +class BoruHattiUyumTestleri(unittest.TestCase): + """`NoteAwareChunks`, GERÇEK tüketicisiyle (`rerank_select`) uyumlu olmalı: + not satırları korpus kurulduktan SONRA gelir, yani `chunks_by_id`/`span_meta` + sarmalayıcıdan geçer. Sarmalayıcı `Mapping` sözleşmesini bozarsa seçim + adımı not parçalarını sessizce düşürür.""" + + class SahteReranker: + def rerank(self, query, candidates): + return [(cid, 0.9) for cid, _ in candidates] + + def test_not_parcasi_secim_adimindan_gecer(self): + from src.index.notes import NoteAwareChunks + from src.rerank.pipeline import rerank_select + index = NoteIndex() + cevap = index_course_note( + _payload(), school="okul-a", blob_reader=None, note_index=index, + embedder=SahteEmbedder()) + self.assertGreater(cevap["chunks"], 0) + cid = index.retrieve("hücre canlılar", SahteEmbedder(), + school="okul-a")[0][0] + sarmal = NoteAwareChunks({}, index.chunk) + self.assertIn(cid, sarmal) + secilen = rerank_select("hücre", [(cid, 1.0)], sarmal, + self.SahteReranker(), top_n=1) + self.assertEqual([c.chunk_id for c in secilen], [cid]) + self.assertIn("Hücre", secilen[0].text) + self.assertEqual(secilen[0].doc_id, "01NOTE") + # Span meta da canlı indeksten çözülür (atıf → sayfa). + self.assertEqual(index.span(index.chunk(cid).span_ids[0])["page"], 1) + self.assertNotIn("yok", sarmal) + + +class BasarisizTasimaTestleri(unittest.TestCase): + def test_sozlesme_disli_tur_indekslenemez_ama_raporlanir(self): + index = NoteIndex() + reader = SahteBlobOkuyucu({"01FILE": ("ses.mp3", "audio/mpeg", b"\x00\x01")}) + cevap = index_course_note( + _payload(files=[RagFile(id="01FILE", name="ses.mp3", + content_type="audio/mpeg", size=2)]), + school="okul-a", blob_reader=reader, note_index=index, + embedder=SahteEmbedder()) + self.assertEqual(cevap["failed"][0]["code"], "unsupported_type") + self.assertEqual(cevap["files"], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_tenant_multischool.py b/tests/unit/test_tenant_multischool.py index 6718451..b98b232 100644 --- a/tests/unit/test_tenant_multischool.py +++ b/tests/unit/test_tenant_multischool.py @@ -21,7 +21,7 @@ import numpy as np from src.bridge.contract import (AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, AI_RAG_INDEX_CAPABILITY, BridgeFrameError, BridgeRequest) -from src.bridge.dispatch import Dispatcher, INDEX_UNWIRED +from src.bridge.dispatch import Dispatcher from src.cache.response_cache import canonical_key from src.guard.tenant import (TenantError, content_visible, normalize_school, require_owner, visible_owners) @@ -319,11 +319,15 @@ class BridgeEchoTests(unittest.TestCase): self.assertEqual(out["code"], "invalid_school") self.assertEqual(out["school"], "Okul A") - def test_rag_index_is_refused_until_the_transport_exists(self): + def test_rag_index_is_served_and_a_bad_body_is_refused_typed(self): + """`rag.index` SUNULUR (BL-010 kapandı): gövdesi eksik çerçeve tipli + reddedilir, okul yine AYNEN eko edilir. Gövdesi tam olduğunda yol + `Dispatcher(indexer=...)` ile uçtan uca koşar + (`tests/unit/test_bridge_transport.py::RagIndexBlobAkisiTestleri`).""" out = Dispatcher(self._Svc()).handle(self._cerceve( capability=AI_RAG_INDEX_CAPABILITY, payload={})) self.assertEqual(out["status"], "err") - self.assertEqual(out["code"], INDEX_UNWIRED) + self.assertEqual(out["code"], "malformed") self.assertEqual(out["school"], A) def test_unknown_capability_is_refused(self):