🧩 rag.index served end to end — blob reads, note index, chat channel
Browse files at this commit0877e45ecd97da81de9dc4fce31ec99c76f2e753Parent: 36db106- feat
- 🧩 rag.index served end to end — blob reads, note index, chat channel
15 changed files +1064 -69
- PROJECT_STATE.md +18 -15
- docs/API-CONTRACT.md +2 -1
- docs/BACKEND-INTEGRATION.md +11 -12
- docs/Backlog.md +4 -5
- src/bridge/contract.py +17 -0
- src/bridge/dispatch.py +42 -12
- src/bridge/transport.py +89 -7
- src/generate/generator.py +23 -3
- src/index/notes.py +264 -0
- src/service/http_app.py +6 -1
- src/service/notes_index.py +216 -0
- tests/unit/_fake_bridge.py +37 -5
- tests/unit/test_bridge_transport.py +123 -5
- tests/unit/test_notes_index.py +205 -0
- tests/unit/test_tenant_multischool.py +7 -3
PROJECT_STATE.mdmodified+18 -15
| @@ -101,7 +101,8 @@ ham veri + soru/cevap defteri: `outputs/EXP-009-model-karsilastirma/`), maliyet | |||
| 101 | `.github/workflows/main.yml` (elle tetiklenen VPS deploy). Backend bu HTTP'yi | 101 | `.github/workflows/main.yml` (elle tetiklenen VPS deploy). Backend bu HTTP'yi |
| 102 | ÇAĞIRMAZ; gerçek entegrasyon QUIC `hab/2` köprüsüdür ve **taşıması yazıldı** | 102 | ÇAĞIRMAZ; gerçek entegrasyon QUIC `hab/2` köprüsüdür ve **taşıması yazıldı** |
| 103 | (`src/bridge/transport.py`, ¶11.4) → `rag.chat` artık telden servis edilir; | 103 | (`src/bridge/transport.py`, ¶11.4) → `rag.chat` artık telden servis edilir; |
| 104 | - `rag.index` hâlâ TİPLİ REDDEDER (`index_path_unwired`). | 104 | + `rag.index` SUNULUR (2026-09-18): not + ekler indekslenir — ek baytları kendi |
| 105 | + blob akışıyla okunur, parçalar okulun not indeksine yazılır. | ||
| 105 | Kalıcı Qdrant hâlâ yok (in-memory indeks; #75/RISK-01). | 106 | Kalıcı Qdrant hâlâ yok (in-memory indeks; #75/RISK-01). |
| 106 | 107 | ||
| 107 | ## 4. Mimari Özet | 108 | ## 4. Mimari Özet |
| @@ -114,8 +115,8 @@ ham veri + soru/cevap defteri: `outputs/EXP-009-model-karsilastirma/`), maliyet | |||
| 114 | `role`; `rag.chat`/`chat.reply`), **taşıma `src/bridge/transport.py`** (dial-out, | 115 | `role`; `rag.chat`/`chat.reply`), **taşıma `src/bridge/transport.py`** (dial-out, |
| 115 | `Hello`/`Greeting`, `Request` → dağıtıcı → `Response`, PING, üstel geri | 116 | `Hello`/`Greeting`, `Request` → dağıtıcı → `Response`, PING, üstel geri |
| 116 | çekilmeyle sonsuz yeniden bağlanma; ¶11.4). Yani `rag.chat` telden servis | 117 | çekilmeyle sonsuz yeniden bağlanma; ¶11.4). Yani `rag.chat` telden servis |
| 117 | - edilir; eksik kalan: `rag.index` (ek dosya baytları + korpus yönlendirmesi) ve | 118 | + edilir; kalan: backend'den genel OKUMA yolu (`ApiRequest`, çağıranı yok) — `rag.index` |
| 118 | - backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`, bugün çağıranı yok). | 119 | + ek baytlarını `BlobRequest` ile OKUR (2026-09-18). |
| 119 | Girdi/çıktı sözleşmesi + kiracılık: `docs/API-CONTRACT.md` §0.3, | 120 | Girdi/çıktı sözleşmesi + kiracılık: `docs/API-CONTRACT.md` §0.3, |
| 120 | `docs/BACKEND-INTEGRATION.md` §4/§4.1/§4.2. | 121 | `docs/BACKEND-INTEGRATION.md` §4/§4.1/§4.2. |
| 121 | 122 | ||
| @@ -127,10 +128,10 @@ flowchart LR | |||
| 127 | S[Öğrenci] -->|soru| FE[frontend] --> BR[backend QUIC hab/2] --> RAG --> BR --> FE --> S | 128 | S[Öğrenci] -->|soru| FE[frontend] --> BR[backend QUIC hab/2] --> RAG --> BR --> FE --> S |
| 128 | ``` | 129 | ``` |
| 129 | > Diyagram NİYETİ gösterir. 2026-09-17 durumu: `S → BR → RAG → BR → FE → S` | 130 | > Diyagram NİYETİ gösterir. 2026-09-17 durumu: `S → BR → RAG → BR → FE → S` |
| 130 | -> yolu ARTIK ÇALIŞIR (taşıma landı, `rag.chat` telden servis edilir). Kesikli | 131 | +> yolu ARTIK ÇALIŞIR (taşıma landı, `rag.chat` telden servis edilir) ve korpus |
| 131 | -> oklar hâlâ çizilmemiştir çünkü **korpus akışı yok**: `rag.index` tipli | 132 | +> akışı AÇILDI (2026-09-18): `rag.index` notu + eklerini indeksler (ek baytları |
| 132 | -> reddediyor (dosya baytları `BlobRequest` ile okunmuyor), kalıcı Qdrant yok ve | 133 | +> `BlobRequest` ile okunur). Kesikli oklar hâlâ çizilmemiştir çünkü **kalıcı |
| 133 | -> öğretmenin yüklediği not otomatik indekslenmiyor. | 134 | +> Qdrant yok**: not indeksi süreç-içidir, restart'ta kaybolur. |
| 134 | 135 | ||
| 135 | ## 5. Teknik Kararlar | 136 | ## 5. Teknik Kararlar |
| 136 | - **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. | 137 | - **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 | |||
| 149 | - **TASK-GOLDEN-APPROVE** — P1 — golden v1.1 (200 item) Kadir onayı → üretim ölçümü kilidi açılır. dep: Kadir. **BLOCKED**. | 150 | - **TASK-GOLDEN-APPROVE** — P1 — golden v1.1 (200 item) Kadir onayı → üretim ölçümü kilidi açılır. dep: Kadir. **BLOCKED**. |
| 150 | - **TASK-CRISIS-LINE** — P1 — self-harm guardrail mesajına kriz-hattı no'su. dep: Kadir. **BLOCKED**. | 151 | - **TASK-CRISIS-LINE** — P1 — self-harm guardrail mesajına kriz-hattı no'su. dep: Kadir. **BLOCKED**. |
| 151 | - **TASK-RAG-SERVICE** — P2 — HTTP servisi + `hab/2` dağıtıcısı + **QUIC taşıması | 152 | - **TASK-RAG-SERVICE** — P2 — HTTP servisi + `hab/2` dağıtıcısı + **QUIC taşıması |
| 152 | - TAMAM** (2026-09-17, ¶11.4); kalan: `rag.index` yolunun yazılması (ek dosya | 153 | + TAMAM** (2026-09-17, ¶11.4); `rag.index` yolu da yazıldı (2026-09-18: blob okuma → parça → gömme → okulun not |
| 153 | - baytları + korpus yönlendirmesi) ve kalıcı Qdrant (sözleşme: | 154 | + indeksi); kalan: kalıcı Qdrant (sözleşme: `docs/API-CONTRACT.md` §0.3). |
| 154 | - `docs/API-CONTRACT.md` §0.3). **KISMİ (eksik: index + kalıcı store)**. | 155 | + **KISMİ (eksik: kalıcı store)**. |
| 155 | - **TASK-RAG-SCALE** — P3 — Faz 2 RAPTOR ölçek + çok-dersli korpus + özet-PDF/OCR (Faz 0.8). dep: Kadir yönü. **TODO**. | 156 | - **TASK-RAG-SCALE** — P3 — Faz 2 RAPTOR ölçek + çok-dersli korpus + özet-PDF/OCR (Faz 0.8). dep: Kadir yönü. **TODO**. |
| 156 | - **TASK-REARCH** — P4 — derin yeniden-mimari (EB-KOS/layout/kalibrasyon) — "optimizasyon fazı", Kadir'e ayrıldı. **DEFERRED**. | 157 | - **TASK-REARCH** — P4 — derin yeniden-mimari (EB-KOS/layout/kalibrasyon) — "optimizasyon fazı", Kadir'e ayrıldı. **DEFERRED**. |
| 157 | 158 | ||
| @@ -345,11 +346,13 @@ transport-bağımsız dağıtıcıya verip tek `Response` yazar. Her hatada üst | |||
| 345 | `docs/BACKEND-INTEGRATION.md` §4.2). | 346 | `docs/BACKEND-INTEGRATION.md` §4.2). |
| 346 | 347 | ||
| 347 | **KAPSAM DIŞI (bilinçli, yalan söylenmiyor):** | 348 | **KAPSAM DIŞI (bilinçli, yalan söylenmiyor):** |
| 348 | -- `rag.index` hâlâ TİPLİ REDDEDER (`index_path_unwired`): dizin yazımı ek dosya | 349 | +- `rag.index` SUNULUR (2026-09-18); iki dürüst sınır: (a) not indeksi SÜREÇ-İÇİDİR |
| 349 | - baytlarını (`BlobRequest`) ve korpus yönlendirmesini ister — yazılmadı. | 350 | + (restart'ta kaybolur; not düzenlenince backend yeniden gönderir), (b) notun |
| 350 | -- Backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`) QUIC üzerinden | 351 | + (sınıf, ders) bilgisi telde YOKTUR — not kanalı OKUL süzgeçli, kasa süzgeci |
| 351 | - bağlanmadı: bugünkü iki yetenek de onu istemiyor (`rag.chat` kapsamı | 352 | + değil (`src/index/notes.py` başlığı). |
| 352 | - çerçevede), yani çağıranı olmayan bir yol yazılmadı. | 353 | +- Backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden bağlanmadı: |
| 354 | + `rag.chat` kapsamı çerçevede gelir, `rag.index` yalnız BLOB okur; çağıranı | ||
| 355 | + olmayan yol yazılmadı. | ||
| 353 | - **Canlı bir backend'e karşı uçtan uca koşum YAPILMADI** (bu oturumda ayakta | 356 | - **Canlı bir backend'e karşı uçtan uca koşum YAPILMADI** (bu oturumda ayakta |
| 354 | backend yoktu): kanıt sahte sunucuyla alınan gerçek QUIC el sıkışmasıdır | 357 | backend yoktu): kanıt sahte sunucuyla alınan gerçek QUIC el sıkışmasıdır |
| 355 | (kayıt, istek→dağıtım→cevap, tipli redler, kopma→yeniden kayıt, | 358 | (kayıt, istek→dağıtım→cevap, tipli redler, kopma→yeniden kayıt, |
docs/API-CONTRACT.mdmodified+2 -1
| @@ -82,7 +82,8 @@ okulsuz okur hiçbir şey görmez. | |||
| 82 | testlidir (okul eko'su, yetenek eşlemesi, `asker_role` → `role`). QUIC taşıması | 82 | testlidir (okul eko'su, yetenek eşlemesi, `asker_role` → `role`). QUIC taşıması |
| 83 | (`bridge/transport.py`) 2026-09-17'de eklendi: dial-out + kayıt + gelen | 83 | (`bridge/transport.py`) 2026-09-17'de eklendi: dial-out + kayıt + gelen |
| 84 | `Request`lerin dağıtıcıya verilmesi + yeniden bağlanma. `rag.chat` böylece | 84 | `Request`lerin dağıtıcıya verilmesi + yeniden bağlanma. `rag.chat` böylece |
| 85 | -telden servis edilebilir; `rag.index` hâlâ TİPLİ REDDEDER (sunulmuyor). | 85 | +telden servis edilebilir; `rag.index` de SUNULUR (2026-09-18) — ek baytları |
| 86 | +`BlobRequest` ile okunur, cevap `{course_note, chunks, files[], failed[], summary}`. | ||
| 86 | HTTP yüzeyi yerel koşum/ölçüm için durur; backend onu ÇAĞIRMAZ. | 87 | HTTP yüzeyi yerel koşum/ölçüm için durur; backend onu ÇAĞIRMAZ. |
| 87 | 88 | ||
| 88 | ## 0. Sorumluluk sınırı — kim neyi yapar (#87, 2026-09-12) | 89 | ## 0. Sorumluluk sınırı — kim neyi yapar (#87, 2026-09-12) |
docs/BACKEND-INTEGRATION.mdmodified+11 -12
| @@ -24,8 +24,8 @@ RAG servisi: | |||
| 24 | > artık VAR: `src/bridge/transport.py` backend'e dial-out eder, `rag.chat` + | 24 | > artık VAR: `src/bridge/transport.py` backend'e dial-out eder, `rag.chat` + |
| 25 | > `rag.index` ilan eder ve gelen `Request`leri `bridge/dispatch.py`'ye verir | 25 | > `rag.index` ilan eder ve gelen `Request`leri `bridge/dispatch.py`'ye verir |
| 26 | > (§4.2). `src/bridge/client.py` ise hâlâ yalnız çerçeve kurma/çözme tarafıdır: | 26 | > (§4.2). `src/bridge/client.py` ise hâlâ yalnız çerçeve kurma/çözme tarafıdır: |
| 27 | -> backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`) QUIC üzerinden | 27 | +> backend'den BLOB okuma yolu da LANDI: `rag.index` her eki `BlobRequest` ile |
| 28 | -> bağlanmadı — bugünkü yetenekler onu istemiyor (§7). | 28 | +> okur (2026-09-18); yalnız genel `ApiRequest` yolunun çağıranı yok (§7). |
| 29 | 29 | ||
| 30 | ## 2. Bugün ÇALIŞAN yol: `rag.index` | 30 | ## 2. Bugün ÇALIŞAN yol: `rag.index` |
| 31 | 31 | ||
| @@ -170,7 +170,7 @@ denemek bırakılmaz. | |||
| 170 | **Testler (ağ yok, DB yok):** `tests/unit/test_bridge_transport.py` sahte bir | 170 | **Testler (ağ yok, DB yok):** `tests/unit/test_bridge_transport.py` sahte bir |
| 171 | QUIC sunucusuyla (`tests/unit/_fake_bridge.py`, aioquic, 127.0.0.1) kaydı, | 171 | QUIC sunucusuyla (`tests/unit/_fake_bridge.py`, aioquic, 127.0.0.1) kaydı, |
| 172 | okul eko'sunu, tipli redleri (`invalid_school`, okulsuz çerçevede cevapsız akış, | 172 | okul eko'sunu, tipli redleri (`invalid_school`, okulsuz çerçevede cevapsız akış, |
| 173 | -`index_path_unwired`), kopma sonrası yeniden kaydolmayı ve backend-yokken boot | 173 | +`malformed`), blob akışından ek okumayı, kopma sonrası yeniden kaydolmayı ve backend-yokken boot |
| 174 | politikasını koşar. | 174 | politikasını koşar. |
| 175 | 175 | ||
| 176 | ## 5. Bu tarafta yapılanlar (bu depoda) | 176 | ## 5. Bu tarafta yapılanlar (bu depoda) |
| @@ -212,15 +212,14 @@ Birleştirilmeden `can_access(sinif=, ders=)` kurulamaz. | |||
| 212 | artık telden servis edilir: kayıt, okul eko'su, tipli redler, kopma sonrası | 212 | artık telden servis edilir: kayıt, okul eko'su, tipli redler, kopma sonrası |
| 213 | yeniden bağlanma ve backend-yokken boot politikası sahte bir QUIC sunucusuyla | 213 | yeniden bağlanma ve backend-yokken boot politikası sahte bir QUIC sunucusuyla |
| 214 | test edilir (`tests/unit/test_bridge_transport.py`). | 214 | test edilir (`tests/unit/test_bridge_transport.py`). |
| 215 | -- **`rag.index` hâlâ SUNULMUYOR** — taşıma onu taşır ama dağıtıcı tipli | 215 | +- **`rag.index` SUNULUR (2026-09-18)** — gövde: `bridge/dispatch.py::_rag_index` → |
| 216 | - reddeder (`index_path_unwired`): dizin yazımı ek dosya BAYTLARINI | 216 | + `service/notes_index.py` (not + ekler → parça → gömme → okulun not indeksi). Ek |
| 217 | - (`BlobRequest`) ve korpus yönlendirmesini ister. Sahte bir "tamam" demek | 217 | + baytları `bridge/transport.py::read_blob` ile HAM okunur (başlık + tam `size` |
| 218 | - yerine reddedilir; backend başarısız indekslemede eski `rag_output` satırını | 218 | + bayt). Dürüst sınır: not indeksi süreç-içidir ve not kanalı OKUL süzgeçlidir, |
| 219 | - korur. | 219 | + kasa süzgeci değil (telde notun sınıfı/dersi yok). |
| 220 | -- **Backend'den OKUMA yolu (`ApiRequest`/`BlobRequest`) QUIC üzerinden | 220 | +- **Backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden bağlanmadı.** |
| 221 | - bağlanmadı.** Bugünkü iki yetenek de onu istemez (`rag.chat`'in kapsamı | 221 | + `rag.chat`'in kapsamı çerçevede gelir; `rag.index` yalnız BLOB okur |
| 222 | - çerçevede gelir; `rag.index` sunulmuyor), bu yüzden çağıranı olmayan bir yol | 222 | + (`BlobRequest`). Çağıranı olmayan `ApiRequest` yolu yazılmadı. Öğrenci bağlamı (`BridgeReader`) gerektiren bir yetenek eklenirse |
| 223 | - yazılmadı. Öğrenci bağlamı (`BridgeReader`) gerektiren bir yetenek eklenirse | ||
| 224 | `client.py`'ın senkron `(gönder, al)` arayüzü ile taşımanın async akışları | 223 | `client.py`'ın senkron `(gönder, al)` arayüzü ile taşımanın async akışları |
| 225 | arasında bir uyarlama gerekir. | 224 | arasında bir uyarlama gerekir. |
| 226 | - `rag.chat` `asker_role` → `role.role` eşlemesi dağıtıcıda YAPILIYOR | 225 | - `rag.chat` `asker_role` → `role.role` eşlemesi dağıtıcıda YAPILIYOR |
docs/Backlog.mdmodified+4 -5
| @@ -164,13 +164,12 @@ Backend QUIC **sunucusudur**, AI servisleri ona dial eder. Taşıma yazıldı: | |||
| 164 | **Test:** `tests/unit/test_bridge_transport.py` — sahte QUIC sunucusu | 164 | **Test:** `tests/unit/test_bridge_transport.py` — sahte QUIC sunucusu |
| 165 | (`tests/unit/_fake_bridge.py`), ağ/DB yok: kayıt, istek→dağıtım→cevap (okul | 165 | (`tests/unit/_fake_bridge.py`), ağ/DB yok: kayıt, istek→dağıtım→cevap (okul |
| 166 | eko'su), tipli redler (`invalid_school`, okulsuz çerçevede cevapsız akış, | 166 | eko'su), tipli redler (`invalid_school`, okulsuz çerçevede cevapsız akış, |
| 167 | -`index_path_unwired`), kopma sonrası yeniden kaydolma, backend-yokken süreç | 167 | +`malformed`), blob akışından ek okuma, kopma sonrası yeniden kaydolma, backend-yokken süreç |
| 168 | çıkmaz + backend gelince kendiliğinden katılır. | 168 | çıkmaz + backend gelince kendiliğinden katılır. |
| 169 | 169 | ||
| 170 | -**Kalan (bilinçli):** `rag.index` hâlâ TİPLİ REDDEDER (ek dosya baytları | 170 | +**Kalan (bilinçli):** backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden |
| 171 | -`BlobRequest` + korpus yönlendirmesi ister, yazılmadı); backend'den OKUMA yolu | 171 | +bağlanmadı — çağıranı yok. `rag.index` (2026-09-18) ek baytlarını `BlobRequest` |
| 172 | -(`ApiRequest`/`BlobRequest`) QUIC üzerinden bağlanmadı — bugünkü yetenekler | 172 | +ile okur ve notu okulun not indeksine yazar (süreç-içi). Ayrıntı: |
| 173 | -istemediği için çağıranı olmayan yol yazılmadı. Ayrıntı: | ||
| 174 | `docs/BACKEND-INTEGRATION.md` §4.2 + §7. | 173 | `docs/BACKEND-INTEGRATION.md` §4.2 + §7. |
| 175 | 174 | ||
| 176 | ### BL-011 — Veli (parent) görünürlüğü kurulmadı | 175 | ### BL-011 — Veli (parent) görünürlüğü kurulmadı |
src/bridge/contract.pymodified+17 -0
| @@ -346,6 +346,23 @@ class BlobRequest: | |||
| 346 | return d | 346 | return d |
| 347 | 347 | ||
| 348 | 348 | ||
| 349 | +class BlobReadRefused(Exception): | ||
| 350 | + """A blob read that did not deliver bytes. | ||
| 351 | + | ||
| 352 | + The backend's own refusal vocabulary (`protocol.rs::BlobResponse::Err`: | ||
| 353 | + `not_found` for a file it does not have, `forbidden` for one the named | ||
| 354 | + reader may not open, `module_disabled`, `unavailable`) plus the codes this | ||
| 355 | + side raises before/after the wire (`too_large`, `blob_unavailable`, | ||
| 356 | + `bad_header`, `unsupported_type`, `parse_failed`). Typed, never a bare | ||
| 357 | + `Exception`: one refused attachment must not abort a whole index. | ||
| 358 | + """ | ||
| 359 | + | ||
| 360 | + def __init__(self, code: str, message: str) -> None: | ||
| 361 | + super().__init__(f"{code}: {message}") | ||
| 362 | + self.code = code | ||
| 363 | + self.message = message | ||
| 364 | + | ||
| 365 | + | ||
| 349 | class ApiError(Exception): | 366 | class ApiError(Exception): |
| 350 | """Köprü düzeyinde red (yol izinli değil, kullanıcı bilinmiyor). | 367 | """Köprü düzeyinde red (yol izinli değil, kullanıcı bilinmiyor). |
| 351 | 368 | ||
src/bridge/dispatch.pymodified+42 -12
| @@ -26,18 +26,22 @@ from .contract import (AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, | |||
| 26 | AI_RAG_INDEX_CAPABILITY, BridgeFrameError, BridgeRequest, | 26 | AI_RAG_INDEX_CAPABILITY, BridgeFrameError, BridgeRequest, |
| 27 | BridgeResponse) | 27 | BridgeResponse) |
| 28 | 28 | ||
| 29 | -#: Bu depo `rag.index`i HENÜZ sunamaz: dizin yazımı ek dosya BAYTLARINI | 29 | +# `rag.index` is served end to end: the payload is parsed, every attachment is |
| 30 | -#: (`BlobRequest`) ve korpus yönlendirmesini ister; taşıma yazılmadı (BL-010). | 30 | +# read as bytes over its own blob stream, the note is chunked, embedded and |
| 31 | -#: Sahte bir "tamam" demek yerine tipli reddedilir — backend zaten sessizlik | 31 | +# written into the school's note index (`service::notes_index`), and the answer |
| 32 | -#: üzerine kurulu (başarısız indeksleme eski `rag_output` satırını korur). | 32 | +# object goes back for the backend to store as the note's `rag_output`. |
| 33 | -INDEX_UNWIRED = "index_path_unwired" | ||
| 34 | - | ||
| 35 | - | ||
| 36 | class Dispatcher: | 33 | class Dispatcher: |
| 37 | """`Request` çerçevesi → servis metodu → `Response` çerçevesi.""" | 34 | """`Request` çerçevesi → servis metodu → `Response` çerçevesi.""" |
| 38 | 35 | ||
| 39 | - def __init__(self, service, *, capabilities=None): | 36 | + def __init__(self, service, *, capabilities=None, indexer=None): |
| 40 | self.service = service | 37 | self.service = service |
| 38 | + #: `rag.index`'in gövdesi (not → parça → gömme → not indeksi). Enjekte | ||
| 39 | + #: edilebilir: taşıma testleri ağ/örnek istemeyen bir sahte verir; | ||
| 40 | + #: üretimde `service::notes_index.index_course_note` koşar. | ||
| 41 | + self.indexer = indexer | ||
| 42 | + #: Blob okuyucusu — TAŞIMA takar (`transport.BridgeTransport.register`). | ||
| 43 | + #: Yoksa ekler okunamaz ve notun kendi metni yine indekslenir. | ||
| 44 | + self.blob_reader = None | ||
| 41 | self.capabilities = tuple(capabilities or ( | 45 | self.capabilities = tuple(capabilities or ( |
| 42 | AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, AI_RAG_INDEX_CAPABILITY)) | 46 | AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, AI_RAG_INDEX_CAPABILITY)) |
| 43 | 47 | ||
| @@ -65,10 +69,7 @@ class Dispatcher: | |||
| 65 | "`school` ZORUNLU (varsayılan/fallback yok)") | 69 | "`school` ZORUNLU (varsayılan/fallback yok)") |
| 66 | 70 | ||
| 67 | if req.capability == AI_RAG_INDEX_CAPABILITY: | 71 | if req.capability == AI_RAG_INDEX_CAPABILITY: |
| 68 | - return BridgeResponse.err( | 72 | + return self._rag_index(req, okul) |
| 69 | - req, INDEX_UNWIRED, | ||
| 70 | - "rag.index bu serviste henüz sunulmuyor (taşıma/BLOB yolu " | ||
| 71 | - "yazılmadı) — istek reddedildi, eski çıktı korunur") | ||
| 72 | if req.capability == AI_RAG_CHAT_CAPABILITY: | 73 | if req.capability == AI_RAG_CHAT_CAPABILITY: |
| 73 | return BridgeResponse.ok(req, self._rag_chat(req, okul)) | 74 | return BridgeResponse.ok(req, self._rag_chat(req, okul)) |
| 74 | if req.capability == AI_CHAT_CAPABILITY: | 75 | if req.capability == AI_CHAT_CAPABILITY: |
| @@ -79,6 +80,35 @@ class Dispatcher: | |||
| 79 | f"{', '.join(self.capabilities)})") | 80 | f"{', '.join(self.capabilities)})") |
| 80 | 81 | ||
| 81 | # -- gövde eşlemeleri (tel biçimi → servis sözlüğü) -------------------- | 82 | # -- gövde eşlemeleri (tel biçimi → servis sözlüğü) -------------------- |
| 83 | + def _rag_index(self, req: BridgeRequest, okul: str) -> BridgeResponse: | ||
| 84 | + """`rag.index` → not + ekler → not indeksi → backend'in sakladığı gövde. | ||
| 85 | + | ||
| 86 | + Redler TİPLİ ve küçük tutulur: backend bir hatada eski `rag_output` | ||
| 87 | + satırını korur, yani "sessiz tamam" en kötü sonuçtur. Tek bir ekin | ||
| 88 | + okunamaması ise red DEĞİLDİR — notun kendi metni indekslenir ve cevap | ||
| 89 | + hangi ekin okunamadığını söyler (bkz. `service/notes_index.py`).""" | ||
| 90 | + from .contract import RagIndexPayload | ||
| 91 | + try: | ||
| 92 | + payload = RagIndexPayload.from_wire(req.payload) | ||
| 93 | + except (KeyError, TypeError) as exc: | ||
| 94 | + return BridgeResponse.err(req, "malformed", | ||
| 95 | + f"rag.index gövdesi eksik/yanlış: {exc}") | ||
| 96 | + indexer = self.indexer | ||
| 97 | + if indexer is None: | ||
| 98 | + from ..service.notes_index import index_course_note as indexer | ||
| 99 | + try: | ||
| 100 | + cevap = indexer(payload, school=okul, blob_reader=self.blob_reader) | ||
| 101 | + except Exception as exc: # noqa: BLE001 | ||
| 102 | + import traceback | ||
| 103 | + traceback.print_exc() | ||
| 104 | + return BridgeResponse.err(req, "internal", | ||
| 105 | + f"rag.index çalıştırılamadı: " | ||
| 106 | + f"{type(exc).__name__}: {exc}") | ||
| 107 | + if not isinstance(cevap, dict): | ||
| 108 | + return BridgeResponse.err(req, "internal", | ||
| 109 | + "rag.index bir nesne döndürmedi") | ||
| 110 | + return BridgeResponse.ok(req, cevap) | ||
| 111 | + | ||
| 82 | def _govde(self, req: BridgeRequest, okul: str) -> dict: | 112 | def _govde(self, req: BridgeRequest, okul: str) -> dict: |
| 83 | """Servis isteğinin ortak alanları: sorgu + ROL + okul. | 113 | """Servis isteğinin ortak alanları: sorgu + ROL + okul. |
| 84 | 114 | ||
src/bridge/transport.pymodified+89 -7
| @@ -15,17 +15,20 @@ Desen, kanıtlanmış bir istemciden alındı: `hezarfen_zeka/service/src/bridge | |||
| 15 | ayrılır: | 15 | ayrılır: |
| 16 | 16 | ||
| 17 | 1. **İş yönü.** ZEKA `insight.*` YAZAR (backend'in açtığı akışlara cevap verir | 17 | 1. **İş yönü.** ZEKA `insight.*` YAZAR (backend'in açtığı akışlara cevap verir |
| 18 | - ve kendi okuma/yazma akışlarını açar). RAG yalnız `Request`leri CEVAPLAR: | 18 | + ve kendi okuma/yazma akışlarını açar). RAG `Request`leri CEVAPLAR ve |
| 19 | - bugün açtığı istemci akışı YOKTUR, çünkü `rag.chat` cevabını hesaplamak için | 19 | + `rag.index` için kendi İSTEMCİ akışlarını açar: her ek dosyanın baytları |
| 20 | - okul verisi istemez (kapsamı çerçeve taşır) ve `rag.index` TİPLİ REDDEDER. | 20 | + ayrı bir çift yönlü akışta `BlobRequest` → `BlobResponse` başlığı → tam |
| 21 | + `size` HAM bayt olarak okunur (`read_blob`; şekil `protocol.rs:25-31`). | ||
| 22 | + `rag.chat` hâlâ okul verisi istemez: kapsamı çerçeve taşır. | ||
| 21 | 2. **Yetenekler.** İlan edilen küme `rag.chat` + `rag.index`tir | 23 | 2. **Yetenekler.** İlan edilen küme `rag.chat` + `rag.index`tir |
| 22 | (`ADVERTISED_CAPABILITIES`). Dispatcher `chat.reply`ı da KARŞILAR (backend | 24 | (`ADVERTISED_CAPABILITIES`). Dispatcher `chat.reply`ı da KARŞILAR (backend |
| 23 | yollarsa cevaplanır) ama onu İLAN ETMEYİZ: o yetenek chatbot'undur ve ilan | 25 | yollarsa cevaplanır) ama onu İLAN ETMEYİZ: o yetenek chatbot'undur ve ilan |
| 24 | etmek sohbet trafiğini RAG'e yönlendirmeye davetiye olurdu. | 26 | etmek sohbet trafiğini RAG'e yönlendirmeye davetiye olurdu. |
| 25 | 3. **Redler tiplidir.** Kayıt reddi (`unauthorized`, `unsupported_protocol`) | 27 | 3. **Redler tiplidir.** Kayıt reddi (`unauthorized`, `unsupported_protocol`) |
| 26 | loglanır; süreç ÇIKMAZ. | 28 | loglanır; süreç ÇIKMAZ. |
| 27 | -4. **`rag.index` bugün TİPLİ REDDEDER** (`dispatch.INDEX_UNWIRED`): taşıma onu | 29 | +4. **`rag.index` SUNULUR.** Gövdesi `bridge/dispatch.py` → `service/notes_index.py`; |
| 28 | - taşır ama "tamam" demez. | 30 | + blob akışını bu modül açar (`_LoopBlobReader` ile executor thread'inden |
| 31 | + köprülenir) ve not indeksi süreç-içidir (`index/notes.py`). | ||
| 29 | 32 | ||
| 30 | BOOT POLİTİKASI (uygulanan; testle sabitlenen): | 33 | BOOT POLİTİKASI (uygulanan; testle sabitlenen): |
| 31 | * **Backend YOKKEN süreç DÜŞMEZ.** `run_forever` hiçbir hatada çıkmaz; üstel | 34 | * **Backend YOKKEN süreç DÜŞMEZ.** `run_forever` hiçbir hatada çıkmaz; üstel |
| @@ -107,6 +110,12 @@ DEFAULT_BRIDGE_PORT = 8090 | |||
| 107 | DEFAULT_BACKEND_URL = "http://hezarfen_backend:7656" | 110 | DEFAULT_BACKEND_URL = "http://hezarfen_backend:7656" |
| 108 | CERT_FETCH_TIMEOUT_SECS = 10.0 | 111 | CERT_FETCH_TIMEOUT_SECS = 10.0 |
| 109 | """`GET /ai/certificate` için HTTP zaman aşımı.""" | 112 | """`GET /ai/certificate` için HTTP zaman aşımı.""" |
| 113 | +BLOB_HEADER_TIMEOUT_SECS = 30.0 | ||
| 114 | +"""Bir blob akışının BAŞLIK çerçevesi için bekleme: backend reddi ya da `ok`.""" | ||
| 115 | +BLOB_BODY_TIMEOUT_SECS = 120.0 | ||
| 116 | +"""Gövde için bekleme. backend gövdeyi 64 KiB'lik parçalarla akıtır | ||
| 117 | +(`server.rs::write_blob_body`) ve her yazıya kendi takılma sınırını koyar; bu | ||
| 118 | +sınır bizim tarafımızda, not indekslemesinin son tarihinin (120 s) altında.""" | ||
| 110 | 119 | ||
| 111 | 120 | ||
| 112 | def _env_str(name: str, default: str) -> str: | 121 | def _env_str(name: str, default: str) -> str: |
| @@ -287,11 +296,12 @@ class BridgeTransport(QuicConnectionProtocol): | |||
| 287 | """Tek bir QUIC bağlantısı: kontrol akışı + backend'in açtığı iş akışları.""" | 296 | """Tek bir QUIC bağlantısı: kontrol akışı + backend'in açtığı iş akışları.""" |
| 288 | 297 | ||
| 289 | def __init__(self, *args, settings: Settings, handler, capabilities, | 298 | def __init__(self, *args, settings: Settings, handler, capabilities, |
| 290 | - **kwargs) -> None: | 299 | + dispatcher=None, **kwargs) -> None: |
| 291 | super().__init__(*args, **kwargs) | 300 | super().__init__(*args, **kwargs) |
| 292 | self._settings = settings | 301 | self._settings = settings |
| 293 | self._handler = handler | 302 | self._handler = handler |
| 294 | self._capabilities = tuple(capabilities) | 303 | self._capabilities = tuple(capabilities) |
| 304 | + self._dispatcher = dispatcher | ||
| 295 | self._streams: dict[int, FrameStream] = {} | 305 | self._streams: dict[int, FrameStream] = {} |
| 296 | self._control_sid: int | None = None | 306 | self._control_sid: int | None = None |
| 297 | self._ping_uid = 0 | 307 | self._ping_uid = 0 |
| @@ -348,10 +358,54 @@ class BridgeTransport(QuicConnectionProtocol): | |||
| 348 | greeting = await asyncio.wait_for(stream.read_frame(), | 358 | greeting = await asyncio.wait_for(stream.read_frame(), |
| 349 | timeout=GREETING_TIMEOUT_SECS) | 359 | timeout=GREETING_TIMEOUT_SECS) |
| 350 | self.worker_id = parse_greeting(greeting) | 360 | self.worker_id = parse_greeting(greeting) |
| 361 | + # Blob okuma yolu BURADA takılır: `rag.index` executor thread'inde koşar | ||
| 362 | + # (PING'ler durmasın) ve o thread'den QUIC akışı açmak bu köprüyü | ||
| 363 | + # (`run_coroutine_threadsafe`) gerektirir. | ||
| 364 | + if self._dispatcher is not None: | ||
| 365 | + self._dispatcher.blob_reader = _LoopBlobReader(self) | ||
| 351 | log("info", f"kayıt başarılı: worker_id={self.worker_id} " | 366 | log("info", f"kayıt başarılı: worker_id={self.worker_id} " |
| 352 | f"yetenekler={','.join(self._capabilities)}") | 367 | f"yetenekler={','.join(self._capabilities)}") |
| 353 | return self.worker_id | 368 | return self.worker_id |
| 354 | 369 | ||
| 370 | + # -- istemci başlatımlı akışlar: blob okuma -- | ||
| 371 | + async def read_blob(self, request: dict, *, max_bytes: int, | ||
| 372 | + header_timeout: float = BLOB_HEADER_TIMEOUT_SECS, | ||
| 373 | + body_timeout: float = BLOB_BODY_TIMEOUT_SECS): | ||
| 374 | + """Bir ekin baytlarını KENDİ istemci akışında oku. | ||
| 375 | + | ||
| 376 | + Şekil (`protocol.rs:25-31`): bir `BlobRequest` yaz, gönderme tarafını | ||
| 377 | + bitir, BİR `BlobResponse` başlık çerçevesi oku; `ok` ise tam `size` | ||
| 378 | + HAM bayt gelir (çerçeve DEĞİL — `AI_MAX_FRAME_BYTES` onları sınırlamaz), | ||
| 379 | + sonra akış biter. Dönüş: `(header, bytes)`; red `BlobReadRefused`. | ||
| 380 | + """ | ||
| 381 | + from .contract import BlobReadRefused | ||
| 382 | + sid = self._quic.get_next_available_stream_id() | ||
| 383 | + stream = FrameStream() | ||
| 384 | + self._streams[sid] = stream | ||
| 385 | + try: | ||
| 386 | + self._send_frame(sid, request, end=True) | ||
| 387 | + header = await asyncio.wait_for(stream.read_frame(), timeout=header_timeout) | ||
| 388 | + if not isinstance(header, dict): | ||
| 389 | + raise BlobReadRefused("bad_header", "blob başlığı nesne değil") | ||
| 390 | + if header.get("status") != "ok": | ||
| 391 | + raise BlobReadRefused(str(header.get("code") or "unknown"), | ||
| 392 | + str(header.get("message") or "")) | ||
| 393 | + size = int(header.get("size") or 0) | ||
| 394 | + if size < 0 or size > max_bytes: | ||
| 395 | + raise BlobReadRefused( | ||
| 396 | + "too_large", f"blob {size} bayt: sınır {max_bytes}") | ||
| 397 | + body = await asyncio.wait_for(stream.read_exact(size), | ||
| 398 | + timeout=body_timeout) | ||
| 399 | + return header, body | ||
| 400 | + except BlobReadRefused: | ||
| 401 | + raise | ||
| 402 | + except asyncio.TimeoutError as exc: | ||
| 403 | + raise BlobReadRefused("timeout", "blob akışı zaman aşımına uğradı") from exc | ||
| 404 | + except (BridgeFrameError, EOFError, ValueError) as exc: | ||
| 405 | + raise BlobReadRefused("bad_header", str(exc)) from exc | ||
| 406 | + finally: | ||
| 407 | + self._streams.pop(sid, None) | ||
| 408 | + | ||
| 355 | async def keepalive(self) -> None: | 409 | async def keepalive(self) -> None: |
| 356 | """QUIC PING. Uygulama düzeyinde heartbeat ÇERÇEVESİ yoktur | 410 | """QUIC PING. Uygulama düzeyinde heartbeat ÇERÇEVESİ yoktur |
| 357 | (`ai/protocol.rs:13-14`); boşta kalma zaman aşımını bu önler.""" | 411 | (`ai/protocol.rs:13-14`); boşta kalma zaman aşımını bu önler.""" |
| @@ -425,6 +479,33 @@ class BridgeTransport(QuicConnectionProtocol): | |||
| 425 | self._streams.pop(sid, None) | 479 | self._streams.pop(sid, None) |
| 426 | 480 | ||
| 427 | 481 | ||
| 482 | +class _LoopBlobReader: | ||
| 483 | + """`rag.index`'in blob okuması için thread ↔ olay döngüsü köprüsü. | ||
| 484 | + | ||
| 485 | + Boru hattı (chunk + gömme) executor thread'inde koşar; QUIC akışı ise olay | ||
| 486 | + döngüsünde açılır. Executor thread'inden `run_coroutine_threadsafe` ile | ||
| 487 | + geçilir ve SENKRON beklenir — `rag.index` zaten arka planda, kimse | ||
| 488 | + bekleyemez. | ||
| 489 | + """ | ||
| 490 | + | ||
| 491 | + def __init__(self, protocol) -> None: | ||
| 492 | + self._protocol = protocol | ||
| 493 | + | ||
| 494 | + def read(self, request: dict, *, max_bytes: int): | ||
| 495 | + from concurrent.futures import TimeoutError as FutureTimeout | ||
| 496 | + from .contract import BlobReadRefused | ||
| 497 | + loop = getattr(self._protocol, "_loop", None) | ||
| 498 | + if loop is None or loop.is_closed(): | ||
| 499 | + raise BlobReadRefused("unavailable", "köprü olay döngüsü yok/ kapalı") | ||
| 500 | + future = asyncio.run_coroutine_threadsafe( | ||
| 501 | + self._protocol.read_blob(request, max_bytes=max_bytes), loop) | ||
| 502 | + try: | ||
| 503 | + return future.result( | ||
| 504 | + timeout=BLOB_HEADER_TIMEOUT_SECS + BLOB_BODY_TIMEOUT_SECS) | ||
| 505 | + except FutureTimeout as exc: | ||
| 506 | + raise BlobReadRefused("timeout", "blob okuması zaman aşımına uğradı") from exc | ||
| 507 | + | ||
| 508 | + | ||
| 428 | def _err_frame(kaynak, code: str, message: str) -> dict: | 509 | def _err_frame(kaynak, code: str, message: str) -> dict: |
| 429 | """Türsüz bir hata için küçük bir `Response{status:"err"}` çerçevesi. | 510 | """Türsüz bir hata için küçük bir `Response{status:"err"}` çerçevesi. |
| 430 | 511 | ||
| @@ -447,7 +528,8 @@ async def run_once(settings: Settings, dispatcher: Dispatcher, | |||
| 447 | log("info", f"{settings.host}:{settings.port} adresine bağlanılıyor " | 528 | log("info", f"{settings.host}:{settings.port} adresine bağlanılıyor " |
| 448 | f"(ALPN {AI_ALPN})") | 529 | f"(ALPN {AI_ALPN})") |
| 449 | create = partial(BridgeTransport, settings=settings, | 530 | create = partial(BridgeTransport, settings=settings, |
| 450 | - handler=dispatcher.handle, capabilities=capabilities) | 531 | + handler=dispatcher.handle, dispatcher=dispatcher, |
| 532 | + capabilities=capabilities) | ||
| 451 | async with connect(settings.host, settings.port, configuration=quic_config, | 533 | async with connect(settings.host, settings.port, configuration=quic_config, |
| 452 | create_protocol=create) as connection: | 534 | create_protocol=create) as connection: |
| 453 | await connection.wait_connected() | 535 | await connection.wait_connected() |
src/generate/generator.pymodified+23 -3
| @@ -306,11 +306,22 @@ class Generator: | |||
| 306 | cost_recorder=None, role_ctx=None, response_cache=None, | 306 | cost_recorder=None, role_ctx=None, response_cache=None, |
| 307 | safety_classifier=None, context_packing: bool = False, | 307 | safety_classifier=None, context_packing: bool = False, |
| 308 | context_max_tokens: int = 8000, context_reorder: bool = True, | 308 | context_max_tokens: int = 8000, context_reorder: bool = True, |
| 309 | - rewriter=None, corpus_version: str = "", require_role: bool = False): | 309 | + rewriter=None, corpus_version: str = "", require_role: bool = False, |
| 310 | + note_index=None): | ||
| 310 | self.retriever = retriever | 311 | self.retriever = retriever |
| 311 | self.reranker = reranker | 312 | self.reranker = reranker |
| 312 | - self.chunks_by_id = chunks_by_id | 313 | + # Not kanalı (`rag.index`'in yazdığı indeks, bkz. src/index/notes.py). |
| 313 | - self.span_meta = span_meta | 314 | + # `chunks_by_id`/`span_meta` KORPUS KURULURKEN donar; not satırları ise |
| 315 | + # çalışma anında gelir ve değişir — bu yüzden ikisi de canlı indekse | ||
| 316 | + # bakan bir sarmalayıcıdan geçer. None ise davranış ÖNCEKİYLE AYNIDIR. | ||
| 317 | + self.note_index = note_index | ||
| 318 | + if note_index is not None: | ||
| 319 | + from ..index.notes import NoteAwareChunks | ||
| 320 | + self.chunks_by_id = NoteAwareChunks(chunks_by_id, note_index.chunk) | ||
| 321 | + self.span_meta = NoteAwareChunks(span_meta, note_index.span) | ||
| 322 | + else: | ||
| 323 | + self.chunks_by_id = chunks_by_id | ||
| 324 | + self.span_meta = span_meta | ||
| 314 | self.llm = llm if llm is not None else LLMClient() | 325 | self.llm = llm if llm is not None else LLMClient() |
| 315 | self.ders = ders | 326 | self.ders = ders |
| 316 | # PROVİZYONEL eşik — golden set (Faz 1.8) sonrası kalibre edilecek. | 327 | # PROVİZYONEL eşik — golden set (Faz 1.8) sonrası kalibre edilecek. |
| @@ -499,6 +510,15 @@ class Generator: | |||
| 499 | school=school) | 510 | school=school) |
| 500 | else: | 511 | else: |
| 501 | hits = self.retriever.retrieve(q, top_k=candidate_n, school=school) | 512 | hits = self.retriever.retrieve(q, top_k=candidate_n, school=school) |
| 513 | + # NOT KANALI (`rag.index`): okulun ders notları ders korpusunun YANINDA | ||
| 514 | + # aranır. Okul süzgeci store'un kendisindedir; (sınıf, ders) kapısı not | ||
| 515 | + # satırlarına UYGULANAMAZ çünkü telde notun sınıfı/dersi yoktur (bkz. | ||
| 516 | + # `index/notes.py` başlığı — dürüst sınır). | ||
| 517 | + if self.note_index is not None and school: | ||
| 518 | + from ..index.notes import merge_hits | ||
| 519 | + not_vurus = self.note_index.retrieve(q, self.retriever.embedder, | ||
| 520 | + school=school, top_k=candidate_n) | ||
| 521 | + hits = merge_hits(hits, not_vurus, candidate_n) | ||
| 502 | contexts = rerank_select(q, hits, self.chunks_by_id, self.reranker, | 522 | contexts = rerank_select(q, hits, self.chunks_by_id, self.reranker, |
| 503 | top_n=top_n, candidate_n=candidate_n) | 523 | top_n=top_n, candidate_n=candidate_n) |
| 504 | _tr("retrieve", n_hits=len(hits), n_contexts=len(contexts), | 524 | _tr("retrieve", n_hits=len(hits), n_contexts=len(contexts), |
src/index/notes.pyadded+264 -0
| @@ -0,0 +1,264 @@ | |||
| 1 | +"""The course-note index — the retrieval channel `rag.index` fills. | ||
| 2 | + | ||
| 3 | +WHY IT IS ITS OWN INDEX. A textbook corpus is a file on disk | ||
| 4 | +(`data/<school>/<kasa>/<sinif>/<ders>/kitap.pdf`) keyed by `(school, sinif, | ||
| 5 | +ders)`. A course note names none of those on the wire: the `rag.index` payload | ||
| 6 | +carries the note's `course` **uuid**, while a `rag.chat` scope pair carries a | ||
| 7 | +class grade and a course **title** (derived by the backend from the asker's own | ||
| 8 | +memberships) — and the backend's AI-read allowlist has no route that would let | ||
| 9 | +this service resolve one to the other. There is no join, so a note cannot be | ||
| 10 | +filed under a subject corpus. | ||
| 11 | + | ||
| 12 | +WHAT IT IS INSTEAD. One bucket per **school** — the tenant dimension every store | ||
| 13 | +already filters on, by exact equality (`guard/tenant.py`). `replace_note()` swaps | ||
| 14 | +a note's rows as one unit (a re-index never duplicates); `retrieve()` ranks that | ||
| 15 | +bucket's rows and `rag.chat` merges the hits into the subject corpus's. | ||
| 16 | + | ||
| 17 | +HONEST LIMIT — the (class, subject) gate does not reach here. `can_access` | ||
| 18 | +isolates class+subject for textbook chunks; a note carries neither on the wire, | ||
| 19 | +so its rows cannot be checked against the asker's scope pairs. The backend still | ||
| 20 | +refuses to *link* a citation the asker may not open (it stores `file: null`), | ||
| 21 | +but a note's *text* from another course of the same school can be quoted. | ||
| 22 | +Closing that needs the note's class+subject on the `rag.index` payload — a wire | ||
| 23 | +change owned by the backend, not by this repo. | ||
| 24 | + | ||
| 25 | +IN-MEMORY, DERIVED, DISPOSABLE. Nothing here is a source of truth: a restart | ||
| 26 | +loses it, and any note edit re-dispatches `rag.index` — the backend's own model | ||
| 27 | +of a `rag_output` row ("derived data"). | ||
| 28 | +""" | ||
| 29 | +from __future__ import annotations | ||
| 30 | + | ||
| 31 | +import hashlib | ||
| 32 | +import threading | ||
| 33 | +from collections.abc import Mapping | ||
| 34 | + | ||
| 35 | +import numpy as np | ||
| 36 | + | ||
| 37 | +from src.index.dense import DenseIndex | ||
| 38 | +from src.index.lexical import BM25Index | ||
| 39 | +from src.retrieve.rrf import rrf_fuse | ||
| 40 | +from src.retrieve.sparse import SparseIndex | ||
| 41 | + | ||
| 42 | +#: One attachment's byte ceiling — the backend's own `MAX_MAX_FILE_BYTES` | ||
| 43 | +#: (`constant.rs:80`). A blob header promising more is refused before a byte of | ||
| 44 | +#: the body is read. | ||
| 45 | +MAX_NOTE_FILE_BYTES = 25 * 1024 * 1024 | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +def doc_id_for_bytes(data: bytes) -> str: | ||
| 49 | + """Content-derived document id — the same rule the textbook path uses | ||
| 50 | + (`ingest/canonical.py`: the first 12 hex of the sha256). Identical bytes | ||
| 51 | + hash to one document, which is exactly what the backend's citation | ||
| 52 | + resolver expects (several files may claim one doc id).""" | ||
| 53 | + return hashlib.sha256(data).hexdigest()[:12] | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +class _Bucket: | ||
| 57 | + """One school's note rows, plus indexes rebuilt lazily after a write.""" | ||
| 58 | + | ||
| 59 | + def __init__(self) -> None: | ||
| 60 | + self.ids: list[str] = [] | ||
| 61 | + self.texts: list[str] = [] | ||
| 62 | + self.vectors: list[np.ndarray] = [] | ||
| 63 | + self.sparse: list[dict] = [] | ||
| 64 | + self.chunks: dict = {} # chunk_id -> Chunk | ||
| 65 | + self.spans: dict = {} # span_id -> {"page", "bbox"} | ||
| 66 | + self.owner: dict = {} # chunk_id -> note key | ||
| 67 | + self.dense = None | ||
| 68 | + self.bm25 = None | ||
| 69 | + self.spar = None | ||
| 70 | + self.dirty = True | ||
| 71 | + | ||
| 72 | + def rebuild(self, school: str) -> None: | ||
| 73 | + if not self.dirty: | ||
| 74 | + return | ||
| 75 | + if self.ids: | ||
| 76 | + self.dense = DenseIndex(dim=1024).build( | ||
| 77 | + list(self.ids), np.asarray(self.vectors, dtype=np.float32), | ||
| 78 | + school=school) | ||
| 79 | + self.bm25 = BM25Index().build(list(self.ids), list(self.texts), | ||
| 80 | + school=school) | ||
| 81 | + self.spar = SparseIndex().build(list(self.ids), list(self.sparse), | ||
| 82 | + school=school) | ||
| 83 | + else: | ||
| 84 | + self.dense = self.bm25 = self.spar = None | ||
| 85 | + self.dirty = False | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +class NoteIndex: | ||
| 89 | + """School-scoped course-note rows + their three retrieval indexes. | ||
| 90 | + | ||
| 91 | + Thread-safe: `rag.index` runs in the transport's executor thread while | ||
| 92 | + `rag.chat` retrieves on request threads. | ||
| 93 | + """ | ||
| 94 | + | ||
| 95 | + def __init__(self) -> None: | ||
| 96 | + self._buckets: dict[str, _Bucket] = {} | ||
| 97 | + self._lock = threading.Lock() | ||
| 98 | + | ||
| 99 | + # -- yazma ------------------------------------------------------------ | ||
| 100 | + def replace_note(self, school: str, course_note: str, rows) -> int: | ||
| 101 | + """Swap one note's rows for `rows` — the note-level unit of update. | ||
| 102 | + | ||
| 103 | + `rows` is `[(Chunk, dense_vector, sparse_dict), ...]`. The previous rows | ||
| 104 | + of this note are dropped first, so a re-index is idempotent by | ||
| 105 | + construction (chunk ids are note-scoped; nothing survives to duplicate). | ||
| 106 | + """ | ||
| 107 | + from src.guard.tenant import require_owner | ||
| 108 | + sahip = require_owner(school) | ||
| 109 | + with self._lock: | ||
| 110 | + bucket = self._buckets.setdefault(sahip, _Bucket()) | ||
| 111 | + self._drop_locked(bucket, course_note) | ||
| 112 | + for chunk, vector, sparse in rows: | ||
| 113 | + cid = chunk.chunk_id | ||
| 114 | + bucket.ids.append(cid) | ||
| 115 | + bucket.texts.append(chunk.text) | ||
| 116 | + bucket.vectors.append(np.asarray(vector, dtype=np.float32)) | ||
| 117 | + bucket.sparse.append({str(k): float(v) for k, v in dict(sparse).items()}) | ||
| 118 | + bucket.chunks[cid] = chunk | ||
| 119 | + bucket.owner[cid] = course_note | ||
| 120 | + for sid in chunk.span_ids: | ||
| 121 | + bucket.spans[sid] = {"page": chunk.page_start, | ||
| 122 | + "bbox": (0.0, 0.0, 0.0, 0.0)} | ||
| 123 | + bucket.dirty = True | ||
| 124 | + return len(rows) | ||
| 125 | + | ||
| 126 | + def drop_note(self, school: str, course_note: str) -> int: | ||
| 127 | + from src.guard.tenant import require_owner | ||
| 128 | + sahip = require_owner(school) | ||
| 129 | + with self._lock: | ||
| 130 | + bucket = self._buckets.get(sahip) | ||
| 131 | + if bucket is None: | ||
| 132 | + return 0 | ||
| 133 | + n = self._drop_locked(bucket, course_note) | ||
| 134 | + bucket.dirty = True | ||
| 135 | + return n | ||
| 136 | + | ||
| 137 | + @staticmethod | ||
| 138 | + def _drop_locked(bucket: _Bucket, course_note: str) -> int: | ||
| 139 | + victims = [cid for cid, owner in bucket.owner.items() if owner == course_note] | ||
| 140 | + if not victims: | ||
| 141 | + return 0 | ||
| 142 | + drop = set(victims) | ||
| 143 | + keep = [i for i, cid in enumerate(bucket.ids) if cid not in drop] | ||
| 144 | + bucket.ids = [bucket.ids[i] for i in keep] | ||
| 145 | + bucket.texts = [bucket.texts[i] for i in keep] | ||
| 146 | + bucket.vectors = [bucket.vectors[i] for i in keep] | ||
| 147 | + bucket.sparse = [bucket.sparse[i] for i in keep] | ||
| 148 | + for cid in victims: | ||
| 149 | + cid_chunk = bucket.chunks.pop(cid, None) | ||
| 150 | + bucket.owner.pop(cid, None) | ||
| 151 | + for sid in (getattr(cid_chunk, "span_ids", None) or []): | ||
| 152 | + bucket.spans.pop(sid, None) | ||
| 153 | + return len(victims) | ||
| 154 | + | ||
| 155 | + # -- okuma ------------------------------------------------------------ | ||
| 156 | + def retrieve(self, query: str, embedder, *, school: str, top_k: int = 40, | ||
| 157 | + rrf_k: int = 60): | ||
| 158 | + """Rank this school's note rows — `[(chunk_id, rrf_score), ...]`. | ||
| 159 | + | ||
| 160 | + The tenant filter is the store's own (`school=` on every index search): | ||
| 161 | + another school's notes, and rows with no school stamp, are never | ||
| 162 | + returned (`guard/tenant.py`). | ||
| 163 | + """ | ||
| 164 | + if not query or not query.strip() or not school: | ||
| 165 | + return [] | ||
| 166 | + with self._lock: | ||
| 167 | + bucket = self._buckets.get(school) | ||
| 168 | + if bucket is None or not bucket.ids: | ||
| 169 | + return [] | ||
| 170 | + bucket.rebuild(school) | ||
| 171 | + dense, bm25, spar = bucket.dense, bucket.bm25, bucket.spar | ||
| 172 | + sorgu = getattr(embedder, "embed_query", None) | ||
| 173 | + qv = sorgu(query)[0] if sorgu is not None else embedder.embed([query])[0] | ||
| 174 | + rankings = [dense.search(qv, top_k, school=school), | ||
| 175 | + bm25.search(query, top_k, school=school)] | ||
| 176 | + if spar is not None: | ||
| 177 | + qs = embedder.embed_sparse([query])[0] | ||
| 178 | + rankings.append(spar.search(qs, top_k, school=school)) | ||
| 179 | + return rrf_fuse(rankings, k=rrf_k, top_k=top_k) | ||
| 180 | + | ||
| 181 | + def chunk(self, chunk_id: str): | ||
| 182 | + with self._lock: | ||
| 183 | + for bucket in self._buckets.values(): | ||
| 184 | + if chunk_id in bucket.chunks: | ||
| 185 | + return bucket.chunks[chunk_id] | ||
| 186 | + return None | ||
| 187 | + | ||
| 188 | + def span(self, span_id: str): | ||
| 189 | + with self._lock: | ||
| 190 | + for bucket in self._buckets.values(): | ||
| 191 | + if span_id in bucket.spans: | ||
| 192 | + return bucket.spans[span_id] | ||
| 193 | + return None | ||
| 194 | + | ||
| 195 | + def stats(self) -> dict: | ||
| 196 | + with self._lock: | ||
| 197 | + return {school: len(bucket.ids) for school, bucket in self._buckets.items() | ||
| 198 | + if bucket.ids} | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +_SHARED: NoteIndex | None = None | ||
| 202 | +_SHARED_LOCK = threading.Lock() | ||
| 203 | + | ||
| 204 | + | ||
| 205 | +def shared_note_index() -> NoteIndex: | ||
| 206 | + """The process-wide note index. | ||
| 207 | + | ||
| 208 | + `rag.index` (transport thread) and `rag.chat` (request threads) must see the | ||
| 209 | + same rows, and the service is built per corpus — so the store is a process | ||
| 210 | + singleton, like `guard/tenant.py`'s rules and the provider configuration. | ||
| 211 | + """ | ||
| 212 | + global _SHARED | ||
| 213 | + with _SHARED_LOCK: | ||
| 214 | + if _SHARED is None: | ||
| 215 | + _SHARED = NoteIndex() | ||
| 216 | + return _SHARED | ||
| 217 | + | ||
| 218 | + | ||
| 219 | +class NoteAwareChunks(Mapping): | ||
| 220 | + """`{chunk_id: object}` that falls back to the note index. | ||
| 221 | + | ||
| 222 | + `Generator` holds `chunks_by_id` and `span_meta` — both built once, from a | ||
| 223 | + corpus that was on disk at build time. Note rows arrive later (and are | ||
| 224 | + replaced), so lookups consult the live note index first; the base mapping | ||
| 225 | + answers everything else. Read-only `Mapping` is enough: the pipeline only | ||
| 226 | + reads (`cid in chunks`, `chunks[cid].text`, `span_meta.get(sid)`). | ||
| 227 | + """ | ||
| 228 | + | ||
| 229 | + def __init__(self, base, lookup) -> None: | ||
| 230 | + self._base = base | ||
| 231 | + self._lookup = lookup # (key) -> value | None | ||
| 232 | + | ||
| 233 | + def __getitem__(self, key): | ||
| 234 | + found = self._lookup(key) | ||
| 235 | + if found is not None: | ||
| 236 | + return found | ||
| 237 | + return self._base[key] | ||
| 238 | + | ||
| 239 | + def __iter__(self): | ||
| 240 | + yield from self._base | ||
| 241 | + # Live rows are not enumerated: the base keys are what a caller | ||
| 242 | + # iterates for counts/aggregates, and the note rows are already found | ||
| 243 | + # by id. Enumerating them here would silently change `len()` semantics. | ||
| 244 | + | ||
| 245 | + def __len__(self) -> int: | ||
| 246 | + return len(self._base) | ||
| 247 | + | ||
| 248 | + def get(self, key, default=None): | ||
| 249 | + found = self._lookup(key) | ||
| 250 | + return found if found is not None else self._base.get(key, default) | ||
| 251 | + | ||
| 252 | + def __contains__(self, key) -> bool: | ||
| 253 | + return self._lookup(key) is not None or key in self._base | ||
| 254 | + | ||
| 255 | + | ||
| 256 | +def merge_hits(base_hits, extra_hits, top_k: int, *, rrf_k: int = 60): | ||
| 257 | + """RRF-merge two best-first rank lists — the subject corpus's hits and the | ||
| 258 | + school's note hits. Ranks (not scores) are what RRF uses, which is exactly | ||
| 259 | + what two differently-calibrated indexes need.""" | ||
| 260 | + if not extra_hits: | ||
| 261 | + return base_hits | ||
| 262 | + if not base_hits: | ||
| 263 | + return extra_hits[:top_k] | ||
| 264 | + return rrf_fuse([base_hits, extra_hits], k=rrf_k, top_k=top_k) | ||
src/service/http_app.pymodified+6 -1
| @@ -613,6 +613,7 @@ def build_service(book_path: str, *, school, sinif: str, ders: str, | |||
| 613 | from ..ingest.canonical import build_canonical | 613 | from ..ingest.canonical import build_canonical |
| 614 | from ..chunk import chunk_document | 614 | from ..chunk import chunk_document |
| 615 | from ..index import DenseIndex, BM25Index | 615 | from ..index import DenseIndex, BM25Index |
| 616 | + from ..index.notes import shared_note_index | ||
| 616 | from ..retrieve import SparseIndex, HybridRetriever | 617 | from ..retrieve import SparseIndex, HybridRetriever |
| 617 | from ..generate import Generator, QuestionGenerator, build_span_meta | 618 | from ..generate import Generator, QuestionGenerator, build_span_meta |
| 618 | from ..summarize.summarizer import Summarizer | 619 | from ..summarize.summarizer import Summarizer |
| @@ -715,7 +716,11 @@ def build_service(book_path: str, *, school, sinif: str, ders: str, | |||
| 715 | gen = Generator(retr, reranker, by_id, span_meta, ders=ders, | 716 | gen = Generator(retr, reranker, by_id, span_meta, ders=ders, |
| 716 | safety_classifier=LLMSafetyClassifier(), context_packing=True, | 717 | safety_classifier=LLMSafetyClassifier(), context_packing=True, |
| 717 | corpus_version=cv, require_role=True, # STRICT: rolsüz istek fail-closed | 718 | corpus_version=cv, require_role=True, # STRICT: rolsüz istek fail-closed |
| 718 | - response_cache=response_cache, rewriter=rewriter) | 719 | + response_cache=response_cache, rewriter=rewriter, |
| 720 | + # Ders notları (`rag.index`) bu korpusun YANINDA aranır: | ||
| 721 | + # süreç-içi tek indeks, çünkü `rag.index` korpus nesnesine | ||
| 722 | + # değil okula yazar (bkz. src/index/notes.py). | ||
| 723 | + note_index=shared_note_index()) | ||
| 719 | return RagService(gen, doc=doc, summarizer=Summarizer(), | 724 | return RagService(gen, doc=doc, summarizer=Summarizer(), |
| 720 | question_gen=QuestionGenerator(), ders=ders, school=sahip) | 725 | question_gen=QuestionGenerator(), ders=ders, school=sahip) |
| 721 | 726 | ||
src/service/notes_index.pyadded+216 -0
| @@ -0,0 +1,216 @@ | |||
| 1 | +"""`rag.index` — the write path: note + attachments → chunks → vectors → the | ||
| 2 | +note index (`src/index/notes.py`), and the answer object the backend stores. | ||
| 3 | + | ||
| 4 | +WHAT ONE REQUEST DOES | ||
| 5 | + | ||
| 6 | + 1. the note's own `title` + `content` become one document (always); | ||
| 7 | + 2. each `files[]` entry is read as **bytes over its own QUIC blob stream** | ||
| 8 | + (`BlobRequest` → `BlobResponse` header → exactly `size` raw bytes), then | ||
| 9 | + parsed by content type — PDFs through the same canonical loader the | ||
| 10 | + textbook corpus uses (`ingest/canonical.build_canonical`), plain text | ||
| 11 | + decoded directly; | ||
| 12 | + 3. every document is chunked (`chunk.chunk_document`) and embedded in one | ||
| 13 | + pass (`embed_both`: dense + sparse, the provider configured by | ||
| 14 | + `RAG_EMBED_*`); | ||
| 15 | + 4. the note's rows replace whatever this note held before (one unit — a | ||
| 16 | + re-index cannot duplicate); | ||
| 17 | + 5. the answer echoes `files[].id` so the backend can stamp the doc id it | ||
| 18 | + minted onto the attachment row, and names any attachment that failed. | ||
| 19 | + | ||
| 20 | +A FAILED ATTACHMENT DOES NOT ABORT THE INDEX. A blob read that refuses (missing | ||
| 21 | +file, permission, unknown type) is recorded and the rest — including the note | ||
| 22 | +body — is indexed: a partly indexed note beats no note. The backend keeps the | ||
| 23 | +previous `rag_output` rows when the whole round trip fails, which is why a | ||
| 24 | +refusal must be typed rather than answered with an empty "ok". | ||
| 25 | +""" | ||
| 26 | +from __future__ import annotations | ||
| 27 | + | ||
| 28 | +import os | ||
| 29 | +import tempfile | ||
| 30 | + | ||
| 31 | +from ..bridge.contract import BlobReadRefused, RagIndexPayload | ||
| 32 | +from ..index.notes import (MAX_NOTE_FILE_BYTES, doc_id_for_bytes, | ||
| 33 | + shared_note_index) | ||
| 34 | + | ||
| 35 | +PDF_TYPES = ("application/pdf", "application/x-pdf") | ||
| 36 | +TEXT_TYPES = ("text/plain", "text/markdown", "text/csv", "application/json") | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def _is_pdf(name: str, content_type: str) -> bool: | ||
| 40 | + return (content_type or "").lower() in PDF_TYPES or \ | ||
| 41 | + (name or "").lower().endswith(".pdf") | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def _text_units(doc, text: str, *, page: int = 1): | ||
| 45 | + """`text` → canonical units (one per non-empty paragraph). | ||
| 46 | + | ||
| 47 | + The chunker consumes `CanonicalUnit`s, so the note's own prose rides the | ||
| 48 | + exact same pipeline as a parsed PDF page — no second chunker, no second | ||
| 49 | + span scheme. | ||
| 50 | + """ | ||
| 51 | + from ..ingest.canonical import CanonicalUnit, make_span_id | ||
| 52 | + units = [] | ||
| 53 | + for n, parca in enumerate(p for p in text.split("\n") if p.strip()): | ||
| 54 | + units.append(CanonicalUnit( | ||
| 55 | + span_id=make_span_id(doc.doc_id, page, n), doc_id=doc.doc_id, | ||
| 56 | + sinif=doc.sinif, ders=doc.ders, kaynak_turu=doc.kaynak_turu, | ||
| 57 | + page=page, bbox=(0.0, 0.0, 0.0, 0.0), block_no=n, | ||
| 58 | + kind="paragraph", text=parca.strip(), page_visual="low_visual", | ||
| 59 | + retrieval_disi=False)) | ||
| 60 | + return units | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def _body_doc(payload: RagIndexPayload): | ||
| 64 | + """The note's own title + content — doc id is the note's own record key, | ||
| 65 | + so a re-index replaces rows instead of piling up new ones.""" | ||
| 66 | + from ..ingest.canonical import CanonicalDoc | ||
| 67 | + doc = CanonicalDoc(source_path="", doc_id=payload.course_note, | ||
| 68 | + source_version=payload.course_note, sinif="", ders="", | ||
| 69 | + kaynak_turu="konu_ozeti", page_count=1) | ||
| 70 | + doc.units = _text_units(doc, f"{payload.title}\n{payload.content}") | ||
| 71 | + return doc | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def _plain_doc(name: str, data: bytes, *, doc_id: str): | ||
| 75 | + from ..ingest.canonical import CanonicalDoc | ||
| 76 | + metin = data.decode("utf-8", errors="replace") | ||
| 77 | + doc = CanonicalDoc(source_path=name, doc_id=doc_id, | ||
| 78 | + source_version=doc_id, sinif="", ders="", | ||
| 79 | + kaynak_turu="konu_ozeti", page_count=1) | ||
| 80 | + doc.units = _text_units(doc, metin) | ||
| 81 | + return doc | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def _pdf_doc(name: str, data: bytes, *, doc_id: str): | ||
| 85 | + """PDF bytes → canonical document, through the corpus's own loader. | ||
| 86 | + | ||
| 87 | + `build_canonical` reads a path, so the bytes land in a temp file first; the | ||
| 88 | + doc id is computed from the bytes here (not from the temp path) so it stays | ||
| 89 | + the content hash the citation resolver expects. | ||
| 90 | + """ | ||
| 91 | + from ..ingest.canonical import build_canonical | ||
| 92 | + fd, yol = tempfile.mkstemp(suffix=".pdf", prefix="not-eki-") | ||
| 93 | + try: | ||
| 94 | + with os.fdopen(fd, "wb") as f: | ||
| 95 | + f.write(data) | ||
| 96 | + doc = build_canonical(yol, sinif="", ders="", kaynak_turu="konu_ozeti") | ||
| 97 | + doc.source_path = name | ||
| 98 | + doc.doc_id = doc_id # sha256 of the same bytes | ||
| 99 | + for unit in doc.units: | ||
| 100 | + unit.doc_id = doc_id | ||
| 101 | + unit.span_id = unit.span_id.replace(doc.doc_id, doc_id, 0) \ | ||
| 102 | + if unit.span_id.startswith(doc.doc_id) else unit.span_id | ||
| 103 | + return doc | ||
| 104 | + finally: | ||
| 105 | + try: | ||
| 106 | + os.unlink(yol) | ||
| 107 | + except OSError: | ||
| 108 | + pass | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +def _chunks_for(doc, course_note: str): | ||
| 112 | + """Children only, note-scoped ids (two notes sharing one PDF must not | ||
| 113 | + collide), no parent links (no parent rows are stored).""" | ||
| 114 | + from ..chunk import chunk_document | ||
| 115 | + out = [] | ||
| 116 | + for chunk in chunk_document(doc): | ||
| 117 | + if chunk.level != "child": | ||
| 118 | + continue | ||
| 119 | + chunk.chunk_id = f"{course_note}:{chunk.chunk_id}" | ||
| 120 | + chunk.parent_id = None | ||
| 121 | + out.append(chunk) | ||
| 122 | + return out | ||
| 123 | + | ||
| 124 | + | ||
| 125 | +def index_course_note(payload: RagIndexPayload, *, school: str, | ||
| 126 | + blob_reader=None, note_index=None, embedder=None) -> dict: | ||
| 127 | + """Index one course note and return the answer object the backend stores.""" | ||
| 128 | + index = note_index if note_index is not None else shared_note_index() | ||
| 129 | + if embedder is None: | ||
| 130 | + from ..embed.provider import build_embedder | ||
| 131 | + embedder = build_embedder() | ||
| 132 | + | ||
| 133 | + docs = [_body_doc(payload)] | ||
| 134 | + indexed_files, failed_files = [], [] | ||
| 135 | + | ||
| 136 | + for meta in payload.files: | ||
| 137 | + try: | ||
| 138 | + header, data = _read_file(meta, school=school, | ||
| 139 | + author=payload.author, blob_reader=blob_reader) | ||
| 140 | + except BlobReadRefused as exc: | ||
| 141 | + failed_files.append({"id": meta.id, "name": meta.name, | ||
| 142 | + "code": exc.code, "message": exc.message}) | ||
| 143 | + continue | ||
| 144 | + name = str(header.get("name") or meta.name or "") | ||
| 145 | + content_type = str(header.get("content_type") or meta.content_type or "") | ||
| 146 | + doc_id = doc_id_for_bytes(data) | ||
| 147 | + try: | ||
| 148 | + if _is_pdf(name, content_type): | ||
| 149 | + doc = _pdf_doc(name, data, doc_id=doc_id) | ||
| 150 | + elif (content_type or "").lower() in TEXT_TYPES or \ | ||
| 151 | + name.lower().endswith((".txt", ".md", ".csv", ".json")): | ||
| 152 | + doc = _plain_doc(name, data, doc_id=doc_id) | ||
| 153 | + else: | ||
| 154 | + raise BlobReadRefused("unsupported_type", | ||
| 155 | + f"'{content_type or 'bilinmeyen'}' türü " | ||
| 156 | + "indekslenemiyor") | ||
| 157 | + except BlobReadRefused as exc: | ||
| 158 | + failed_files.append({"id": meta.id, "name": name, | ||
| 159 | + "code": exc.code, "message": exc.message}) | ||
| 160 | + continue | ||
| 161 | + except Exception as exc: # noqa: BLE001 | ||
| 162 | + failed_files.append({"id": meta.id, "name": name, "code": "parse_failed", | ||
| 163 | + "message": f"{type(exc).__name__}: {exc}"}) | ||
| 164 | + continue | ||
| 165 | + docs.append(doc) | ||
| 166 | + indexed_files.append({"id": meta.id, "doc_id": doc_id, "name": name}) | ||
| 167 | + | ||
| 168 | + chunks = [] | ||
| 169 | + for doc in docs: | ||
| 170 | + chunks.extend(_chunks_for(doc, payload.course_note)) | ||
| 171 | + rows = [] | ||
| 172 | + if chunks: | ||
| 173 | + texts = [c.text for c in chunks] | ||
| 174 | + vecs, sparse = embedder.embed_both(texts, batch_size=16) | ||
| 175 | + rows = [(chunk, vec, sp) for chunk, vec, sp in zip(chunks, vecs, sparse)] | ||
| 176 | + n = index.replace_note(school, payload.course_note, rows) | ||
| 177 | + | ||
| 178 | + return { | ||
| 179 | + "course_note": payload.course_note, | ||
| 180 | + "chunks": n, | ||
| 181 | + "files": indexed_files, | ||
| 182 | + "failed": failed_files, | ||
| 183 | + "summary": _summary(payload.title, n, indexed_files, failed_files), | ||
| 184 | + } | ||
| 185 | + | ||
| 186 | + | ||
| 187 | +def _read_file(meta, *, school: str, author: str, blob_reader): | ||
| 188 | + """One attachment's bytes over its own blob stream. | ||
| 189 | + | ||
| 190 | + The request shape is the bridge's (`protocol.rs::BlobRequest`): the file's | ||
| 191 | + record id, the school slug, and the note's author as `on_behalf_of` — the | ||
| 192 | + `ai` principal can view no course, so a read as itself always earns | ||
| 193 | + `forbidden`. | ||
| 194 | + """ | ||
| 195 | + if blob_reader is None: | ||
| 196 | + raise BlobReadRefused("blob_unavailable", | ||
| 197 | + "bu servis örnekte blob okuma yolu yok") | ||
| 198 | + if int(meta.size or 0) > MAX_NOTE_FILE_BYTES: | ||
| 199 | + raise BlobReadRefused("too_large", | ||
| 200 | + f"ek {meta.size} bayt: sınır {MAX_NOTE_FILE_BYTES}") | ||
| 201 | + return blob_reader.read({"id": meta.id, "school": school, "file": meta.id, | ||
| 202 | + "on_behalf_of": author}, | ||
| 203 | + max_bytes=MAX_NOTE_FILE_BYTES) | ||
| 204 | + | ||
| 205 | + | ||
| 206 | +def _summary(title: str, chunks: int, indexed_files, failed_files) -> str: | ||
| 207 | + """One or two Turkish sentences — the human is the reader of this payload.""" | ||
| 208 | + baslik = (title or "").strip() or "Ders notu" | ||
| 209 | + ek = (f", {len(indexed_files)} ek dosyayla" if indexed_files else "") | ||
| 210 | + metin = (f"'{baslik}' notu indekslendi: {chunks} metin parçası{ek}. " | ||
| 211 | + "Bu not artık sorularda kaynak olarak kullanılabilir.") | ||
| 212 | + if failed_files: | ||
| 213 | + adlar = ", ".join(str(f.get("name") or f.get("id")) for f in failed_files) | ||
| 214 | + metin += (f" Şu ekler okunamadı ve indekslenemedi: {adlar} — " | ||
| 215 | + "notun kendi metni yine de indekslendi.") | ||
| 216 | + return metin | ||
tests/unit/_fake_bridge.pymodified+37 -5
| @@ -231,6 +231,11 @@ class _Connection(QuicConnectionProtocol): | |||
| 231 | self._quic.send_stream_data(sid, encode_frame(obj), end_stream=end) | 231 | self._quic.send_stream_data(sid, encode_frame(obj), end_stream=end) |
| 232 | self.transmit() | 232 | self.transmit() |
| 233 | 233 | ||
| 234 | + def send_bytes(self, sid: int, data: bytes, end: bool) -> None: | ||
| 235 | + """Ham bayt — blob gövdesi çerçeve DEĞİLDİR (`protocol.rs:27-30`).""" | ||
| 236 | + self._quic.send_stream_data(sid, data, end_stream=end) | ||
| 237 | + self.transmit() | ||
| 238 | + | ||
| 234 | def forget(self, sid: int) -> None: | 239 | def forget(self, sid: int) -> None: |
| 235 | self._readers.pop(sid, None) | 240 | self._readers.pop(sid, None) |
| 236 | 241 | ||
| @@ -290,9 +295,12 @@ class _Connection(QuicConnectionProtocol): | |||
| 290 | # -- istemci başlatımlı akışlar -- | 295 | # -- istemci başlatımlı akışlar -- |
| 291 | 296 | ||
| 292 | async def _serve_client_stream(self, sid: int, reader: _Reader) -> None: | 297 | async def _serve_client_stream(self, sid: int, reader: _Reader) -> None: |
| 293 | - """Bugün istemci HİÇ akış açmaz (RAG yalnız `Request` cevaplar). | 298 | + """İstemci başlatımlı akış = BİR blob okuma (`rag.index`). |
| 294 | 299 | ||
| 295 | - Açarsa bu bir kayıttır: sunucu tipli bir red yazar ki bekleyen bir | 300 | + Bir `BlobRequest` (gerekli alan: `file`) → `BlobResponse` başlığı; `ok` |
| 301 | + ise tam `size` **ham** bayt (`server.rs::serve_blob`). Başlıktan sonraki | ||
| 302 | + gövde çerçeve DEĞİLDİR. Kayıtlı olmayan bir dosya `not_found` ile | ||
| 303 | + reddedilir; başka bir çerçeve de tipli reddedilir ki bekleyen bir | ||
| 296 | okuyucu asılı kalmasın.""" | 304 | okuyucu asılı kalmasın.""" |
| 297 | try: | 305 | try: |
| 298 | raw = await reader.read_frame() | 306 | raw = await reader.read_frame() |
| @@ -300,9 +308,24 @@ class _Connection(QuicConnectionProtocol): | |||
| 300 | self._bridge.client_streams.append({"malformed": str(exc)}) | 308 | self._bridge.client_streams.append({"malformed": str(exc)}) |
| 301 | self.send(sid, _err("", "", "malformed", str(exc)), end=True) | 309 | self.send(sid, _err("", "", "malformed", str(exc)), end=True) |
| 302 | return | 310 | return |
| 303 | - self._bridge.client_streams.append(raw if isinstance(raw, dict) else {}) | 311 | + if not isinstance(raw, dict) or raw.get("file") is None: |
| 304 | - self.send(sid, _err(str(raw.get("id") or ""), str(raw.get("school") or ""), | 312 | + self._bridge.client_streams.append(raw if isinstance(raw, dict) else {}) |
| 305 | - "malformed", "bu servis istemci akışı açmıyor"), end=True) | 313 | + self.send(sid, _err(str((raw or {}).get("id") or ""), |
| 314 | + str((raw or {}).get("school") or ""), "malformed", | ||
| 315 | + "bu servis yalnız blob okuma akışı açar"), end=True) | ||
| 316 | + return | ||
| 317 | + self._bridge.blob_requests.append(raw) | ||
| 318 | + entry = self._bridge.blobs.get(str(raw.get("file"))) | ||
| 319 | + if entry is None: | ||
| 320 | + self.send(sid, {"status": "err", "id": raw.get("id") or "", | ||
| 321 | + "school": raw.get("school") or "", "code": "not_found", | ||
| 322 | + "message": "no such course-note file"}, end=True) | ||
| 323 | + return | ||
| 324 | + name, content_type, data = entry | ||
| 325 | + self.send(sid, {"status": "ok", "id": raw.get("id") or "", | ||
| 326 | + "school": raw.get("school") or "", "name": name, | ||
| 327 | + "content_type": content_type, "size": len(data)}, end=False) | ||
| 328 | + self.send_bytes(sid, data, end=True) | ||
| 306 | 329 | ||
| 307 | 330 | ||
| 308 | def _err(request_id: str, school: str, code: str, message: str) -> dict: | 331 | def _err(request_id: str, school: str, code: str, message: str) -> dict: |
| @@ -353,6 +376,10 @@ class FakeBridge: | |||
| 353 | self.rejects: list[str] = [] | 376 | self.rejects: list[str] = [] |
| 354 | #: İstemcinin açtığı (kontrol dışı) akışların çerçeveleri. | 377 | #: İstemcinin açtığı (kontrol dışı) akışların çerçeveleri. |
| 355 | self.client_streams: list[dict] = [] | 378 | self.client_streams: list[dict] = [] |
| 379 | + #: `rag.index` blob okumaları: file id → (name, content_type, bytes). | ||
| 380 | + self.blobs: dict[str, tuple[str, str, bytes]] = {} | ||
| 381 | + #: Gelen her `BlobRequest` çerçevesi (sırayla) — okul/adına-okuma kanıtı. | ||
| 382 | + self.blob_requests: list[dict] = [] | ||
| 356 | self._port = port | 383 | self._port = port |
| 357 | self._server: Any = None | 384 | self._server: Any = None |
| 358 | self._quic_config: Any = None | 385 | self._quic_config: Any = None |
| @@ -451,6 +478,11 @@ class FakeBridge: | |||
| 451 | self._connections.add(worker.connection) | 478 | self._connections.add(worker.connection) |
| 452 | self._worker_event.set() | 479 | self._worker_event.set() |
| 453 | 480 | ||
| 481 | + def add_blob(self, file_id: str, data: bytes, *, name: str = "ek.pdf", | ||
| 482 | + content_type: str = "application/pdf") -> None: | ||
| 483 | + """Bir ders-notu ekinin baytlarını servise sun (blob okuma için).""" | ||
| 484 | + self.blobs[str(file_id)] = (name, content_type, data) | ||
| 485 | + | ||
| 454 | def deregister(self, worker: _Worker) -> None: | 486 | def deregister(self, worker: _Worker) -> None: |
| 455 | self._connections.discard(worker.connection) | 487 | self._connections.discard(worker.connection) |
| 456 | self.workers = [w for w in self.workers if w.worker_id != worker.worker_id] | 488 | self.workers = [w for w in self.workers if w.worker_id != worker.worker_id] |
tests/unit/test_bridge_transport.pymodified+123 -5
| @@ -62,10 +62,11 @@ def _ayarlar(bridge: FakeBridge, *, port: int | None = None, **ustune) -> Settin | |||
| 62 | 62 | ||
| 63 | 63 | ||
| 64 | @contextlib.asynccontextmanager | 64 | @contextlib.asynccontextmanager |
| 65 | -async def _calisan_kopru(bridge: FakeBridge, servis: _SahteServis, **ustune): | 65 | +async def _calisan_kopru(bridge: FakeBridge, servis: _SahteServis, *, |
| 66 | + indexer=None, **ustune): | ||
| 66 | """Köprüyü arka planda koştur, çıkışta temizle.""" | 67 | """Köprüyü arka planda koştur, çıkışta temizle.""" |
| 67 | gorev = asyncio.ensure_future( | 68 | gorev = asyncio.ensure_future( |
| 68 | - run_forever(_ayarlar(bridge, **ustune), Dispatcher(servis))) | 69 | + run_forever(_ayarlar(bridge, **ustune), Dispatcher(servis, indexer=indexer))) |
| 69 | try: | 70 | try: |
| 70 | yield gorev | 71 | yield gorev |
| 71 | finally: | 72 | finally: |
| @@ -188,12 +189,13 @@ class KopruTasimaTestleri(unittest.TestCase): | |||
| 188 | await akis2.read(timeout=0.5) | 189 | await akis2.read(timeout=0.5) |
| 189 | akis2.close() | 190 | akis2.close() |
| 190 | 191 | ||
| 191 | - # (c) `rag.index` ilan edilir ama HENÜZ sunulmaz: "tamam" | 192 | + # (c) `rag.index` SUNULUR: gövdesi eksikse TİPLİ reddedilir |
| 192 | - # demek sessiz bir yalandır, backend eski çıktıyı korur. | 193 | + # (uydurma "tamam" yok; gövde tam olduğunda yol aşağıdaki |
| 194 | + # testte blob akışıyla uçtan uca koşar). | ||
| 193 | indeks = await bridge.call("rag.index", "okul-a", | 195 | indeks = await bridge.call("rag.index", "okul-a", |
| 194 | {"course_note": "N1"}) | 196 | {"course_note": "N1"}) |
| 195 | self.assertEqual(indeks["status"], "err") | 197 | self.assertEqual(indeks["status"], "err") |
| 196 | - self.assertEqual(indeks["code"], "index_path_unwired") | 198 | + self.assertEqual(indeks["code"], "malformed") |
| 197 | self.assertEqual(indeks["school"], "okul-a") | 199 | self.assertEqual(indeks["school"], "okul-a") |
| 198 | 200 | ||
| 199 | # (d) Hepsinin ardından normal istek cevaplanıyor. | 201 | # (d) Hepsinin ardından normal istek cevaplanıyor. |
| @@ -367,3 +369,119 @@ class OrtamAdlariTestleri(unittest.TestCase): | |||
| 367 | self.assertEqual(ayar.reconnect_max_secs, 60.0) | 369 | self.assertEqual(ayar.reconnect_max_secs, 60.0) |
| 368 | # Özet SIR vermez: anahtarın kendisi değil, var/yok bilgisi yazılır. | 370 | # Özet SIR vermez: anahtarın kendisi değil, var/yok bilgisi yazılır. |
| 369 | self.assertNotIn("test-token", ayar.summary()) | 371 | self.assertNotIn("test-token", ayar.summary()) |
| 372 | + | ||
| 373 | + | ||
| 374 | +class RagIndexBlobAkisiTestleri(unittest.TestCase): | ||
| 375 | + """`rag.index` uçtan uca: çerçeve → (sahte) dizinleyici → BLOB AKIŞI → cevap. | ||
| 376 | + | ||
| 377 | + Ölçülen iddia: ekin baytları kendi istemci akışında, ham olarak (çerçeve | ||
| 378 | + DEĞİL) gelir; cevap `files[].id`yi isteğin verdiği id ile AYNEN yankılar | ||
| 379 | + (backend `course_note_file.rag_doc_id`yi yalnız bu eşleşmeden doldurur). | ||
| 380 | + """ | ||
| 381 | + | ||
| 382 | + BAYT = (b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n" | ||
| 383 | + b"%%EOF\n" * 20) | ||
| 384 | + | ||
| 385 | + def test_ek_baytlari_blob_akisindan_okunur_ve_id_yankilanir(self): | ||
| 386 | + okumalar: list = [] | ||
| 387 | + | ||
| 388 | + def sahte_indeksleyici(payload, *, school, blob_reader): | ||
| 389 | + meta = payload.files[0] | ||
| 390 | + header, data = blob_reader.read( | ||
| 391 | + {"id": f"ULID-{meta.id}", "school": school, "file": meta.id, | ||
| 392 | + "on_behalf_of": payload.author}, | ||
| 393 | + max_bytes=8 * 1024 * 1024) | ||
| 394 | + okumalar.append((header, data)) | ||
| 395 | + return {"course_note": payload.course_note, | ||
| 396 | + "chunks": 1, | ||
| 397 | + "files": [{"id": meta.id, "doc_id": "5eda1f0a9c32"}], | ||
| 398 | + "summary": f"'{payload.title}' notu indekslendi."} | ||
| 399 | + | ||
| 400 | + async def senaryo() -> None: | ||
| 401 | + bridge = FakeBridge() | ||
| 402 | + bridge.add_blob("01FILE", self.BAYT, name="kaynak.pdf", | ||
| 403 | + content_type="application/pdf") | ||
| 404 | + await bridge.start() | ||
| 405 | + try: | ||
| 406 | + async with _calisan_kopru(bridge, _SahteServis(), | ||
| 407 | + indexer=sahte_indeksleyici): | ||
| 408 | + await bridge.wait_for_worker(timeout=10) | ||
| 409 | + cevap = await bridge.call("rag.index", "okul-a", { | ||
| 410 | + "course_note": "01NOTE", "course": "01COURSE", | ||
| 411 | + "author": "01AUTHOR", "title": "Hücre ve Canlılar", | ||
| 412 | + "content": "Hücre, canlıların en küçük yapı birimidir.", | ||
| 413 | + "files": [{"id": "01FILE", "name": "kaynak.pdf", | ||
| 414 | + "content_type": "application/pdf", | ||
| 415 | + "size": len(self.BAYT)}]}) | ||
| 416 | + | ||
| 417 | + self.assertEqual(cevap["status"], "ok") | ||
| 418 | + self.assertEqual(cevap["school"], "okul-a") | ||
| 419 | + govde = cevap["payload"] | ||
| 420 | + self.assertEqual(govde["course_note"], "01NOTE") | ||
| 421 | + # id AYNEN yankılanır → backend ekin satırını damgalar. | ||
| 422 | + self.assertEqual(govde["files"][0]["id"], "01FILE") | ||
| 423 | + self.assertEqual(govde["files"][0]["doc_id"], "5eda1f0a9c32") | ||
| 424 | + | ||
| 425 | + # Baytlar ham aktı: çerçeve çözülmedi, tam boyutta geldi. | ||
| 426 | + self.assertEqual(len(okumalar), 1) | ||
| 427 | + header, data = okumalar[0] | ||
| 428 | + self.assertEqual(header["status"], "ok") | ||
| 429 | + self.assertEqual(header["size"], len(self.BAYT)) | ||
| 430 | + self.assertEqual(header["name"], "kaynak.pdf") | ||
| 431 | + self.assertEqual(data, self.BAYT) | ||
| 432 | + | ||
| 433 | + # İstek backend'e okul + ADINA OKUMA ile gitti. | ||
| 434 | + istek = bridge.blob_requests[0] | ||
| 435 | + self.assertEqual(istek["school"], "okul-a") | ||
| 436 | + self.assertEqual(istek["file"], "01FILE") | ||
| 437 | + self.assertEqual(istek["on_behalf_of"], "01AUTHOR") | ||
| 438 | + finally: | ||
| 439 | + await bridge.stop() | ||
| 440 | + | ||
| 441 | + asyncio.run(senaryo()) | ||
| 442 | + | ||
| 443 | + def test_okunamayan_ek_indekslemeyi_durdurmaz(self): | ||
| 444 | + """Blob `not_found` derse dizinleme REDDEDİLMEZ: notun kendi metni | ||
| 445 | + indekslenir ve cevap hangi ekin okunamadığını söyler (backend eski | ||
| 446 | + satırı koruyacağı için "sessiz tamam" en kötü sonuçtur).""" | ||
| 447 | + cevaplar: list = [] | ||
| 448 | + | ||
| 449 | + def sahte_indeksleyici(payload, *, school, blob_reader): | ||
| 450 | + from src.bridge.contract import BlobReadRefused | ||
| 451 | + hata = None | ||
| 452 | + try: | ||
| 453 | + blob_reader.read({"id": "ULID", "school": school, | ||
| 454 | + "file": payload.files[0].id, | ||
| 455 | + "on_behalf_of": payload.author}, | ||
| 456 | + max_bytes=1 << 20) | ||
| 457 | + except BlobReadRefused as exc: | ||
| 458 | + hata = exc | ||
| 459 | + cevaplar.append(hata) | ||
| 460 | + return {"course_note": payload.course_note, "chunks": 2, "files": [], | ||
| 461 | + "failed": [{"id": payload.files[0].id, "code": hata.code, | ||
| 462 | + "message": hata.message}], | ||
| 463 | + "summary": f"'{payload.title}' notu indekslendi."} | ||
| 464 | + | ||
| 465 | + async def senaryo() -> None: | ||
| 466 | + bridge = FakeBridge() # blobs BOŞ: dosya yok | ||
| 467 | + await bridge.start() | ||
| 468 | + try: | ||
| 469 | + async with _calisan_kopru(bridge, _SahteServis(), | ||
| 470 | + indexer=sahte_indeksleyici): | ||
| 471 | + await bridge.wait_for_worker(timeout=10) | ||
| 472 | + cevap = await bridge.call("rag.index", "okul-a", { | ||
| 473 | + "course_note": "01NOTE", "course": "01COURSE", | ||
| 474 | + "author": "01AUTHOR", "title": "Hücre", | ||
| 475 | + "content": "Hücre...", | ||
| 476 | + "files": [{"id": "01YOK", "name": "yok.pdf", | ||
| 477 | + "content_type": "application/pdf", | ||
| 478 | + "size": 10}]}) | ||
| 479 | + self.assertEqual(cevap["status"], "ok") | ||
| 480 | + self.assertEqual(cevap["payload"]["failed"][0]["code"], | ||
| 481 | + "not_found") | ||
| 482 | + self.assertIsNotNone(cevaplar[0]) | ||
| 483 | + self.assertEqual(cevaplar[0].code, "not_found") | ||
| 484 | + finally: | ||
| 485 | + await bridge.stop() | ||
| 486 | + | ||
| 487 | + asyncio.run(senaryo()) | ||
tests/unit/test_notes_index.pyadded+205 -0
| @@ -0,0 +1,205 @@ | |||
| 1 | +"""`rag.index` dizinleme yolu — çevrimdışı (ağ YOK, model YOK). | ||
| 2 | + | ||
| 3 | +Sahte gömme sağlayıcısı SABİT (hash tohumlu) vektörler üretir; sahte blob | ||
| 4 | +okuyucu baytları yerel sözlükten verir. Testin ölçtüğü iddialar: | ||
| 5 | + | ||
| 6 | + 1. notun KENDİ başlık+içeriği ek olmadan da indekslenir; | ||
| 7 | + 2. ekler okunur, `files[].id` AYNEN yankılanır (`doc_id` içerik sha256'sıdır); | ||
| 8 | + 3. yeniden indeksleme ÇOĞALTMAZ (notun satırları değiştirilir); | ||
| 9 | + 4. okunamayan bir ek dizinlemeyi DURDURMAZ ve cevapta adı geçer; | ||
| 10 | + 5. not kanalı okul süzgeciyle aranır (başka okulun satırı görünmez). | ||
| 11 | +""" | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +import hashlib | ||
| 15 | +import unittest | ||
| 16 | + | ||
| 17 | +import numpy as np | ||
| 18 | + | ||
| 19 | +from src.bridge.contract import BlobReadRefused, RagIndexPayload, RagFile | ||
| 20 | +from src.index.notes import NoteIndex, doc_id_for_bytes | ||
| 21 | +from src.service.notes_index import index_course_note | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class SahteEmbedder: | ||
| 25 | + """Deterministik, ağsız gömme. Dense: tohumlu rastgele 1024 boyut.""" | ||
| 26 | + | ||
| 27 | + def _vec(self, text: str) -> np.ndarray: | ||
| 28 | + tohum = int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "big") | ||
| 29 | + return np.random.default_rng(tohum).random(1024).astype(np.float32) | ||
| 30 | + | ||
| 31 | + def embed(self, texts, batch_size=None): | ||
| 32 | + return [self._vec(t) for t in texts] | ||
| 33 | + | ||
| 34 | + def embed_query(self, query): | ||
| 35 | + return [self._vec(query)] | ||
| 36 | + | ||
| 37 | + def embed_sparse(self, texts): | ||
| 38 | + return [{w: 1.0 for w in t.lower().split()} for t in texts] | ||
| 39 | + | ||
| 40 | + def embed_both(self, texts, batch_size=16): | ||
| 41 | + return self.embed(texts), self.embed_sparse(texts) | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +class SahteBlobOkuyucu: | ||
| 45 | + def __init__(self, blobs, *, refuse=()): | ||
| 46 | + self.blobs = blobs | ||
| 47 | + self.refuse = set(refuse) | ||
| 48 | + self.istekler: list[dict] = [] | ||
| 49 | + | ||
| 50 | + def read(self, request, *, max_bytes): | ||
| 51 | + self.istekler.append(dict(request)) | ||
| 52 | + fid = str(request["file"]) | ||
| 53 | + if fid in self.refuse: | ||
| 54 | + raise BlobReadRefused("forbidden", "bu dosyayı göremiyorsun") | ||
| 55 | + name, content_type, data = self.blobs[fid] | ||
| 56 | + return ({"status": "ok", "name": name, "content_type": content_type, | ||
| 57 | + "size": len(data)}, data) | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _payload(**ustune) -> RagIndexPayload: | ||
| 61 | + alanlar = dict(course_note="01NOTE", course="01COURSE", author="01AUTHOR", | ||
| 62 | + title="Hücre ve Canlıların Ortak Özellikleri", | ||
| 63 | + content="Hücre, canlıların en küçük yapı ve görev birimidir.", | ||
| 64 | + files=[]) | ||
| 65 | + alanlar.update(ustune) | ||
| 66 | + return RagIndexPayload(**alanlar) | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +class NotIndekslemeTestleri(unittest.TestCase): | ||
| 70 | + def setUp(self) -> None: | ||
| 71 | + self.index = NoteIndex() | ||
| 72 | + self.embedder = SahteEmbedder() | ||
| 73 | + | ||
| 74 | + def _indeksle(self, payload=None, reader=None): | ||
| 75 | + return index_course_note(payload or _payload(), school="okul-a", | ||
| 76 | + blob_reader=reader, note_index=self.index, | ||
| 77 | + embedder=self.embedder) | ||
| 78 | + | ||
| 79 | + def test_ek_olmadan_da_notun_kendi_metni_indekslenir(self): | ||
| 80 | + """Şart: başlık + içerik HER durumda indekslenir (ek yoksa bile).""" | ||
| 81 | + cevap = self._indeksle() | ||
| 82 | + self.assertEqual(cevap["course_note"], "01NOTE") | ||
| 83 | + self.assertGreater(cevap["chunks"], 0) | ||
| 84 | + self.assertEqual(cevap["files"], []) | ||
| 85 | + # Özet insan içindir: notun başlığını anar (Türkçe, 1-2 cümle). | ||
| 86 | + self.assertIn("Hücre ve Canlıların Ortak Özellikleri", cevap["summary"]) | ||
| 87 | + # Satırlar okul damgasıyla yazıldı (kiracılık). | ||
| 88 | + self.assertEqual(self.index.stats(), {"okul-a": cevap["chunks"]}) | ||
| 89 | + | ||
| 90 | + def test_ek_baytlari_okunur_ve_idler_aynen_yankilanir(self): | ||
| 91 | + """`files[].id` isteğin verdiği id OLMALI; `doc_id` içerik sha256'sı.""" | ||
| 92 | + data = "Hücre zarı, sitoplazma ve çekirdek.".encode("utf-8") | ||
| 93 | + reader = SahteBlobOkuyucu({"01FILE": ("ozet.txt", "text/plain", data)}) | ||
| 94 | + cevap = self._indeksle( | ||
| 95 | + _payload(files=[RagFile(id="01FILE", name="ozet.txt", | ||
| 96 | + content_type="text/plain", size=len(data))]), | ||
| 97 | + reader) | ||
| 98 | + self.assertEqual(cevap["files"], [{"id": "01FILE", | ||
| 99 | + "doc_id": doc_id_for_bytes(data), | ||
| 100 | + "name": "ozet.txt"}]) | ||
| 101 | + self.assertEqual(cevap["failed"], []) | ||
| 102 | + # İstek ADINA OKUMA taşır: `ai` görevlisi hiçbir dersi göremez. | ||
| 103 | + self.assertEqual(reader.istekler[0]["on_behalf_of"], "01AUTHOR") | ||
| 104 | + self.assertEqual(reader.istekler[0]["school"], "okul-a") | ||
| 105 | + | ||
| 106 | + def test_yeniden_indeksleme_cogaltmaz(self): | ||
| 107 | + """Aynı not iki kez indekslenirse satır sayısı İKİYE KATLANMAZ.""" | ||
| 108 | + self._indeksle() | ||
| 109 | + ilk = self.index.stats()["okul-a"] | ||
| 110 | + self._indeksle() | ||
| 111 | + ikinci = self.index.stats()["okul-a"] | ||
| 112 | + self.assertGreater(ilk, 0) | ||
| 113 | + self.assertEqual(ikinci, ilk) | ||
| 114 | + | ||
| 115 | + def test_okunamayan_ek_dizinlemeyi_durdurmaz(self): | ||
| 116 | + """Reddedilen ek atlanır; notun kendi metni indekslenir ve adı geçer.""" | ||
| 117 | + reader = SahteBlobOkuyucu({}, refuse={"01YOK"}) | ||
| 118 | + cevap = self._indeksle( | ||
| 119 | + _payload(files=[RagFile(id="01YOK", name="yok.pdf", | ||
| 120 | + content_type="application/pdf", size=10)]), | ||
| 121 | + reader) | ||
| 122 | + self.assertGreater(cevap["chunks"], 0) | ||
| 123 | + self.assertEqual(cevap["files"], []) | ||
| 124 | + self.assertEqual(cevap["failed"][0]["id"], "01YOK") | ||
| 125 | + self.assertEqual(cevap["failed"][0]["code"], "forbidden") | ||
| 126 | + self.assertIn("yok.pdf", cevap["summary"]) | ||
| 127 | + | ||
| 128 | + def test_blob_okuyucusu_yoksa_not_yine_indekslenir(self): | ||
| 129 | + """Taşıma blob okuyucusunu takmamışsa (ör. yalın test) ekler düşer, | ||
| 130 | + notun metni DÜŞMEZ.""" | ||
| 131 | + cevap = self._indeksle( | ||
| 132 | + _payload(files=[RagFile(id="01FILE", name="a.txt", | ||
| 133 | + content_type="text/plain", size=3)]), | ||
| 134 | + None) | ||
| 135 | + self.assertGreater(cevap["chunks"], 0) | ||
| 136 | + self.assertEqual(cevap["failed"][0]["code"], "blob_unavailable") | ||
| 137 | + | ||
| 138 | + def test_not_kanali_okulla_suzulur(self): | ||
| 139 | + """Arama okul süzgeçlidir: başka okul bu notu GÖRMEZ.""" | ||
| 140 | + data = "Fotosentez, klorofil ile ışık enerjisini bağlar.".encode("utf-8") | ||
| 141 | + reader = SahteBlobOkuyucu({"01FILE": ("foto.txt", "text/plain", data)}) | ||
| 142 | + self._indeksle( | ||
| 143 | + _payload(files=[RagFile(id="01FILE", name="foto.txt", | ||
| 144 | + content_type="text/plain", size=len(data))]), | ||
| 145 | + reader) | ||
| 146 | + bulunan = self.index.retrieve("fotosentez klorofil", self.embedder, | ||
| 147 | + school="okul-a") | ||
| 148 | + self.assertTrue(bulunan, "not kanalı kendi okulunda bulunmalı") | ||
| 149 | + parcalar = [self.index.chunk(cid) for cid, _ in bulunan] | ||
| 150 | + ekli = [c for c in parcalar if "klorofil" in c.text] | ||
| 151 | + self.assertTrue(ekli, "ekin metni kanalda bulunmalı") | ||
| 152 | + # Ekin parçası içerik sha256'sını doc_id olarak taşır (atıf eşleşmesi). | ||
| 153 | + self.assertEqual(ekli[0].doc_id, doc_id_for_bytes(data)) | ||
| 154 | + # Başka okul: damgasız/başka okulun satırı ASLA dönmez. | ||
| 155 | + self.assertEqual( | ||
| 156 | + self.index.retrieve("fotosentez", self.embedder, school="okul-b"), []) | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +class BoruHattiUyumTestleri(unittest.TestCase): | ||
| 160 | + """`NoteAwareChunks`, GERÇEK tüketicisiyle (`rerank_select`) uyumlu olmalı: | ||
| 161 | + not satırları korpus kurulduktan SONRA gelir, yani `chunks_by_id`/`span_meta` | ||
| 162 | + sarmalayıcıdan geçer. Sarmalayıcı `Mapping` sözleşmesini bozarsa seçim | ||
| 163 | + adımı not parçalarını sessizce düşürür.""" | ||
| 164 | + | ||
| 165 | + class SahteReranker: | ||
| 166 | + def rerank(self, query, candidates): | ||
| 167 | + return [(cid, 0.9) for cid, _ in candidates] | ||
| 168 | + | ||
| 169 | + def test_not_parcasi_secim_adimindan_gecer(self): | ||
| 170 | + from src.index.notes import NoteAwareChunks | ||
| 171 | + from src.rerank.pipeline import rerank_select | ||
| 172 | + index = NoteIndex() | ||
| 173 | + cevap = index_course_note( | ||
| 174 | + _payload(), school="okul-a", blob_reader=None, note_index=index, | ||
| 175 | + embedder=SahteEmbedder()) | ||
| 176 | + self.assertGreater(cevap["chunks"], 0) | ||
| 177 | + cid = index.retrieve("hücre canlılar", SahteEmbedder(), | ||
| 178 | + school="okul-a")[0][0] | ||
| 179 | + sarmal = NoteAwareChunks({}, index.chunk) | ||
| 180 | + self.assertIn(cid, sarmal) | ||
| 181 | + secilen = rerank_select("hücre", [(cid, 1.0)], sarmal, | ||
| 182 | + self.SahteReranker(), top_n=1) | ||
| 183 | + self.assertEqual([c.chunk_id for c in secilen], [cid]) | ||
| 184 | + self.assertIn("Hücre", secilen[0].text) | ||
| 185 | + self.assertEqual(secilen[0].doc_id, "01NOTE") | ||
| 186 | + # Span meta da canlı indeksten çözülür (atıf → sayfa). | ||
| 187 | + self.assertEqual(index.span(index.chunk(cid).span_ids[0])["page"], 1) | ||
| 188 | + self.assertNotIn("yok", sarmal) | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +class BasarisizTasimaTestleri(unittest.TestCase): | ||
| 192 | + def test_sozlesme_disli_tur_indekslenemez_ama_raporlanir(self): | ||
| 193 | + index = NoteIndex() | ||
| 194 | + reader = SahteBlobOkuyucu({"01FILE": ("ses.mp3", "audio/mpeg", b"\x00\x01")}) | ||
| 195 | + cevap = index_course_note( | ||
| 196 | + _payload(files=[RagFile(id="01FILE", name="ses.mp3", | ||
| 197 | + content_type="audio/mpeg", size=2)]), | ||
| 198 | + school="okul-a", blob_reader=reader, note_index=index, | ||
| 199 | + embedder=SahteEmbedder()) | ||
| 200 | + self.assertEqual(cevap["failed"][0]["code"], "unsupported_type") | ||
| 201 | + self.assertEqual(cevap["files"], []) | ||
| 202 | + | ||
| 203 | + | ||
| 204 | +if __name__ == "__main__": | ||
| 205 | + unittest.main() | ||
tests/unit/test_tenant_multischool.pymodified+7 -3
| @@ -21,7 +21,7 @@ import numpy as np | |||
| 21 | from src.bridge.contract import (AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, | 21 | from src.bridge.contract import (AI_CHAT_CAPABILITY, AI_RAG_CHAT_CAPABILITY, |
| 22 | AI_RAG_INDEX_CAPABILITY, BridgeFrameError, | 22 | AI_RAG_INDEX_CAPABILITY, BridgeFrameError, |
| 23 | BridgeRequest) | 23 | BridgeRequest) |
| 24 | -from src.bridge.dispatch import Dispatcher, INDEX_UNWIRED | 24 | +from src.bridge.dispatch import Dispatcher |
| 25 | from src.cache.response_cache import canonical_key | 25 | from src.cache.response_cache import canonical_key |
| 26 | from src.guard.tenant import (TenantError, content_visible, normalize_school, | 26 | from src.guard.tenant import (TenantError, content_visible, normalize_school, |
| 27 | require_owner, visible_owners) | 27 | require_owner, visible_owners) |
| @@ -319,11 +319,15 @@ class BridgeEchoTests(unittest.TestCase): | |||
| 319 | self.assertEqual(out["code"], "invalid_school") | 319 | self.assertEqual(out["code"], "invalid_school") |
| 320 | self.assertEqual(out["school"], "Okul A") | 320 | self.assertEqual(out["school"], "Okul A") |
| 321 | 321 | ||
| 322 | - def test_rag_index_is_refused_until_the_transport_exists(self): | 322 | + def test_rag_index_is_served_and_a_bad_body_is_refused_typed(self): |
| 323 | + """`rag.index` SUNULUR (BL-010 kapandı): gövdesi eksik çerçeve tipli | ||
| 324 | + reddedilir, okul yine AYNEN eko edilir. Gövdesi tam olduğunda yol | ||
| 325 | + `Dispatcher(indexer=...)` ile uçtan uca koşar | ||
| 326 | + (`tests/unit/test_bridge_transport.py::RagIndexBlobAkisiTestleri`).""" | ||
| 323 | out = Dispatcher(self._Svc()).handle(self._cerceve( | 327 | out = Dispatcher(self._Svc()).handle(self._cerceve( |
| 324 | capability=AI_RAG_INDEX_CAPABILITY, payload={})) | 328 | capability=AI_RAG_INDEX_CAPABILITY, payload={})) |
| 325 | self.assertEqual(out["status"], "err") | 329 | self.assertEqual(out["status"], "err") |
| 326 | - self.assertEqual(out["code"], INDEX_UNWIRED) | 330 | + self.assertEqual(out["code"], "malformed") |
| 327 | self.assertEqual(out["school"], A) | 331 | self.assertEqual(out["school"], A) |
| 328 | 332 | ||
| 329 | def test_unknown_capability_is_refused(self): | 333 | def test_unknown_capability_is_refused(self): |