📄 rag.index answer carries the extracted text (passages)
Browse files at this commit9e3b62def92456b2d957ba418e7b288b8a14b1d0Parent: 4a533be- feat
- 📄 rag.index answer carries the extracted text (passages)
4 changed files +193 -3
- docs/API-CONTRACT.md +21 -0
- docs/BACKEND-INTEGRATION.md +6 -0
- src/service/notes_index.py +65 -2
- tests/unit/test_notes_index.py +101 -1
docs/API-CONTRACT.mdmodified+21 -0
| @@ -21,6 +21,27 @@ backend `course_note_file.rag_doc_id`'yi yalnız bu eşleşmeden öğrenir — b | |||
| 21 | yeniden indekslerken/silerken hangi korpusu hedefleyeceğini bilmeli (`bridge/contract.py`: | 21 | yeniden indekslerken/silerken hangi korpusu hedefleyeceğini bilmeli (`bridge/contract.py`: |
| 22 | `RagIndexReply`/`RagIndexReplyFile`). | 22 | `RagIndexReply`/`RagIndexReplyFile`). |
| 23 | 23 | ||
| 24 | +**`rag.index` yanıtı çıkarılan METNİ de taşır (2026-09-18, ek anahtar).** | ||
| 25 | +`chunks` yalnız bir SAYIdır; panel onunla "18 metin parçası" yazıp ne çıkarıldığını | ||
| 26 | +gösteremiyordu. Cevap artık iki **ek** anahtar taşır (eski tüketiciler etkilenmez): | ||
| 27 | + | ||
| 28 | +```jsonc | ||
| 29 | +{ "chunks": 18, // DEĞİŞMEDİ: indekse yazılan TOPLAM parça | ||
| 30 | + "passages": [ // indekslenen ÇOCUK parçalar (parent'lar | ||
| 31 | + { "chunk_id": "<not>:<doc>:c0", // çocukların metnini kopyalar, listelenmez) | ||
| 32 | + "doc_id": "<not kaydı|sha256>", // notun kendisi → not anahtarı, ek → içerik sha | ||
| 33 | + "text": "<parçanın TAM metni>", // kısaltma YOK — kırpmak istemcinin işi | ||
| 34 | + "page_start": 1, "page_end": 1 } ], | ||
| 35 | + "passages_truncated": false } // liste kırpıldıysa true | ||
| 36 | +``` | ||
| 37 | + | ||
| 38 | +TAVANLAR: en fazla **50** satır **ve/veya** cevabın tamamı **512 KB** — hangisi önce | ||
| 39 | +dolarsa liste orada kesilir ve `passages_truncated` `true` olur. Tavan bir çerçeve | ||
| 40 | +tavanı değil, DEPOLAMA/kullanım tavanıdır: `AI_MAX_FRAME_BYTES` 8 MiB'dır ama cevap | ||
| 41 | +`rag_output.payload` olarak saklanır ve panelde bir notu açmak o kadar JSON indirmek | ||
| 42 | +olurdu. Parça üretimi **hiçbir zaman** indekslemeyi düşürmez: bir arıza olursa cevap | ||
| 43 | +yine `status: ok` döner, `passages: []` + `passages_truncated: true` ile. | ||
| 44 | + | ||
| 24 | **`rag.chat` kapsamı (sınıf, ders) ÇİFT listesidir.** Eski `role.sinif` + | 45 | **`rag.chat` kapsamı (sınıf, ders) ÇİFT listesidir.** Eski `role.sinif` + |
| 25 | `role.ders_list` biçimi bir KARTEZYEN ÇARPIM ifade eder (`sinif="10"` + | 46 | `role.ders_list` biçimi bir KARTEZYEN ÇARPIM ifade eder (`sinif="10"` + |
| 26 | `ders_list=["biyoloji","satranç"]` → "10-biyoloji **VE** 10-satranç"); oysa gerçek | 47 | `ders_list=["biyoloji","satranç"]` → "10-biyoloji **VE** 10-satranç"); oysa gerçek |
docs/BACKEND-INTEGRATION.mdmodified+6 -0
| @@ -217,6 +217,12 @@ Birleştirilmeden `can_access(sinif=, ders=)` kurulamaz. | |||
| 217 | baytları `bridge/transport.py::read_blob` ile HAM okunur (başlık + tam `size` | 217 | baytları `bridge/transport.py::read_blob` ile HAM okunur (başlık + tam `size` |
| 218 | bayt). Dürüst sınır: not indeksi süreç-içidir ve not kanalı OKUL süzgeçlidir, | 218 | bayt). Dürüst sınır: not indeksi süreç-içidir ve not kanalı OKUL süzgeçlidir, |
| 219 | kasa süzgeci değil (telde notun sınıfı/dersi yok). | 219 | kasa süzgeci değil (telde notun sınıfı/dersi yok). |
| 220 | + **Cevap artık metnin KENDİSİNİ de taşır (2026-09-18):** `passages` — indekslenen | ||
| 221 | + ÇOCUK parçalar (`chunk_id`, `doc_id`, `text`, `page_start`, `page_end`), yani | ||
| 222 | + "18 metin parçası" diyen panel SAYInın yanında ne çıkarıldığını da gösterebilir. | ||
| 223 | + `passages_truncated`, liste kırpıldıysa `True`'dur; `chunks` KIRPILMAZ (indekse | ||
| 224 | + yazılan toplam parça sayısı olarak kalır, `passages` uzunluğu değildir). Sözleşme: | ||
| 225 | + `API-CONTRACT.md` §0.1. | ||
| 220 | - **Backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden bağlanmadı.** | 226 | - **Backend'den genel OKUMA yolu (`ApiRequest`) QUIC üzerinden bağlanmadı.** |
| 221 | `rag.chat`'in kapsamı çerçevede gelir; `rag.index` yalnız BLOB okur | 227 | `rag.chat`'in kapsamı çerçevede gelir; `rag.index` yalnız BLOB okur |
| 222 | (`BlobRequest`). Çağıranı olmayan `ApiRequest` yolu yazılmadı. Öğrenci bağlamı (`BridgeReader`) gerektiren bir yetenek eklenirse | 228 | (`BlobRequest`). Çağıranı olmayan `ApiRequest` yolu yazılmadı. Öğrenci bağlamı (`BridgeReader`) gerektiren bir yetenek eklenirse |
src/service/notes_index.pymodified+65 -2
| @@ -15,7 +15,11 @@ WHAT ONE REQUEST DOES | |||
| 15 | 4. the note's rows replace whatever this note held before (one unit — a | 15 | 4. the note's rows replace whatever this note held before (one unit — a |
| 16 | re-index cannot duplicate); | 16 | re-index cannot duplicate); |
| 17 | 5. the answer echoes `files[].id` so the backend can stamp the doc id it | 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. | 18 | + minted onto the attachment row, and names any attachment that failed; |
| 19 | + 6. the answer also carries `passages` — the indexed **child** chunks with | ||
| 20 | + their full text — so the caller can show WHAT was extracted instead of | ||
| 21 | + only how many pieces there are (`MAX_PASSAGES`/`MAX_PASSAGES_BYTES` cap | ||
| 22 | + the list; `passages_truncated` says whether anything was left out). | ||
| 19 | 23 | ||
| 20 | A FAILED ATTACHMENT DOES NOT ABORT THE INDEX. A blob read that refuses (missing | 24 | 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 | 25 | file, permission, unknown type) is recorded and the rest — including the note |
| @@ -25,6 +29,7 @@ refusal must be typed rather than answered with an empty "ok". | |||
| 25 | """ | 29 | """ |
| 26 | from __future__ import annotations | 30 | from __future__ import annotations |
| 27 | 31 | ||
| 32 | +import json | ||
| 28 | import os | 33 | import os |
| 29 | import tempfile | 34 | import tempfile |
| 30 | 35 | ||
| @@ -35,6 +40,53 @@ from ..index.notes import (MAX_NOTE_FILE_BYTES, doc_id_for_bytes, | |||
| 35 | PDF_TYPES = ("application/pdf", "application/x-pdf") | 40 | PDF_TYPES = ("application/pdf", "application/x-pdf") |
| 36 | TEXT_TYPES = ("text/plain", "text/markdown", "text/csv", "application/json") | 41 | TEXT_TYPES = ("text/plain", "text/markdown", "text/csv", "application/json") |
| 37 | 42 | ||
| 43 | +MAX_PASSAGES = 50 | ||
| 44 | +"""Cevaba konan en fazla parça SAYISI.""" | ||
| 45 | + | ||
| 46 | +MAX_PASSAGES_BYTES = 512 * 1024 | ||
| 47 | +"""Cevabın tamamı (bütün anahtarlar) için bayt bütçesi. | ||
| 48 | + | ||
| 49 | +Bayt tavanı Çerçeve tavanından (`AI_MAX_FRAME_BYTES` = 8 MiB) çok küçük | ||
| 50 | +seçildi: 8 MiB'lık bir cevap telden geçse bile `rag_output.payload` olarak | ||
| 51 | +saklanır ve panelde bir notu açmak ~8 MiB'lık bir JSON indirmek olurdu. | ||
| 52 | +Parçaların hepsi zaten indekste duruyor — cevaptaki liste bir ÖRNEK.""" | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def _json_bytes(obj) -> int: | ||
| 56 | + """Tel biçimi (`contract.encode_frame`) ile AYNI serileştirmenin boyutu.""" | ||
| 57 | + return len(json.dumps(obj, ensure_ascii=False, | ||
| 58 | + separators=(",", ":")).encode("utf-8")) | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +def _passages(chunks, head: dict) -> tuple[list[dict], bool]: | ||
| 62 | + """Çocuk chunk'lar → cevabın `passages` listesi + `passages_truncated`. | ||
| 63 | + | ||
| 64 | + Sözleşme (backend/frontend bu anahtarlara göre kod yazıyor): her satır | ||
| 65 | + `chunk_id`, `doc_id`, `text`, `page_start`, `page_end` taşır ve `text` | ||
| 66 | + indekste duran metnin BİREBİR kendisidir (kısaltma UI'ın işi). | ||
| 67 | + | ||
| 68 | + Bütçe cevabın TAMAMI içindir; `head` cevabın diğer anahtarlarıdır, yani | ||
| 69 | + "512 KB" iddiası telden geçen şeyin kendisi hakkındadır. İki tavan da | ||
| 70 | + (`MAX_PASSAGES`, `MAX_PASSAGES_BYTES`) aynı listeye bakar ve hangisi önce | ||
| 71 | + dolarsa liste orada kesilir — kesildiyse bayrak `True`'dur. | ||
| 72 | + """ | ||
| 73 | + out: list[dict] = [] | ||
| 74 | + used = _json_bytes({**head, "passages": [], "passages_truncated": False}) | ||
| 75 | + for chunk in chunks: | ||
| 76 | + if len(out) >= MAX_PASSAGES: | ||
| 77 | + return out, True | ||
| 78 | + satir = {"chunk_id": chunk.chunk_id, "doc_id": chunk.doc_id, | ||
| 79 | + "text": chunk.text, "page_start": chunk.page_start, | ||
| 80 | + "page_end": chunk.page_end} | ||
| 81 | + # JSON ilk satırdan sonra her satır için bir virgül harcar; listenin | ||
| 82 | + # kendi köşeli parantezleri `used` içindeki boş listede ödendi. | ||
| 83 | + boyut = _json_bytes(satir) + (1 if out else 0) | ||
| 84 | + if used + boyut > MAX_PASSAGES_BYTES: | ||
| 85 | + return out, True | ||
| 86 | + out.append(satir) | ||
| 87 | + used += boyut | ||
| 88 | + return out, False | ||
| 89 | + | ||
| 38 | 90 | ||
| 39 | def _is_pdf(name: str, content_type: str) -> bool: | 91 | def _is_pdf(name: str, content_type: str) -> bool: |
| 40 | return (content_type or "").lower() in PDF_TYPES or \ | 92 | return (content_type or "").lower() in PDF_TYPES or \ |
| @@ -175,13 +227,24 @@ def index_course_note(payload: RagIndexPayload, *, school: str, | |||
| 175 | rows = [(chunk, vec, sp) for chunk, vec, sp in zip(chunks, vecs, sparse)] | 227 | rows = [(chunk, vec, sp) for chunk, vec, sp in zip(chunks, vecs, sparse)] |
| 176 | n = index.replace_note(school, payload.course_note, rows) | 228 | n = index.replace_note(school, payload.course_note, rows) |
| 177 | 229 | ||
| 178 | - return { | 230 | + head = { |
| 179 | "course_note": payload.course_note, | 231 | "course_note": payload.course_note, |
| 180 | "chunks": n, | 232 | "chunks": n, |
| 181 | "files": indexed_files, | 233 | "files": indexed_files, |
| 182 | "failed": failed_files, | 234 | "failed": failed_files, |
| 183 | "summary": _summary(payload.title, n, indexed_files, failed_files), | 235 | "summary": _summary(payload.title, n, indexed_files, failed_files), |
| 184 | } | 236 | } |
| 237 | + # Parça listesi indeksin KENDİSİ değil, ondan bir örnektir: buradaki | ||
| 238 | + # herhangi bir arıza cevabı düşürmez, yalnız listeyi boşaltır (`chunks` | ||
| 239 | + # yine tam sayıyı söyler). Backend eski `rag_output` satırını ancak TÜM | ||
| 240 | + # tur düşerse korur — parça üretimi yüzünden reddetmek, indekslenmiş bir | ||
| 241 | + # notu kaybettirirdi. | ||
| 242 | + try: | ||
| 243 | + passages, truncated = _passages(chunks, head) | ||
| 244 | + except Exception: # noqa: BLE001 | ||
| 245 | + passages, truncated = [], True | ||
| 246 | + | ||
| 247 | + return {**head, "passages": passages, "passages_truncated": truncated} | ||
| 185 | 248 | ||
| 186 | 249 | ||
| 187 | def _read_file(meta, *, school: str, author: str, blob_reader): | 250 | def _read_file(meta, *, school: str, author: str, blob_reader): |
tests/unit/test_notes_index.pymodified+101 -1
| @@ -12,13 +12,16 @@ okuyucu baytları yerel sözlükten verir. Testin ölçtüğü iddialar: | |||
| 12 | from __future__ import annotations | 12 | from __future__ import annotations |
| 13 | 13 | ||
| 14 | import hashlib | 14 | import hashlib |
| 15 | +import json | ||
| 15 | import unittest | 16 | import unittest |
| 16 | 17 | ||
| 17 | import numpy as np | 18 | import numpy as np |
| 18 | 19 | ||
| 19 | from src.bridge.contract import BlobReadRefused, RagIndexPayload, RagFile | 20 | from src.bridge.contract import BlobReadRefused, RagIndexPayload, RagFile |
| 20 | from src.index.notes import NoteIndex, doc_id_for_bytes | 21 | from src.index.notes import NoteIndex, doc_id_for_bytes |
| 21 | -from src.service.notes_index import index_course_note | 22 | +from src.service import notes_index as ni |
| 23 | +from src.service.notes_index import (MAX_PASSAGES, MAX_PASSAGES_BYTES, | ||
| 24 | + index_course_note) | ||
| 22 | 25 | ||
| 23 | 26 | ||
| 24 | class SahteEmbedder: | 27 | class SahteEmbedder: |
| @@ -201,5 +204,102 @@ class BasarisizTasimaTestleri(unittest.TestCase): | |||
| 201 | self.assertEqual(cevap["files"], []) | 204 | self.assertEqual(cevap["files"], []) |
| 202 | 205 | ||
| 203 | 206 | ||
| 207 | +def _metin(bayt: int) -> str: | ||
| 208 | + """~`bayt` baytlık TEK satır: bir paragraf = bir birim = bir çocuk parça. | ||
| 209 | + | ||
| 210 | + `kelime ` 7 bayt; `CHILD_FLUSH`=250 token ≈ 178 kelime, yani 200 kelimelik | ||
| 211 | + bir paragraf tek başına çocuğu kapatır → paragraf sayısı = parça sayısı. | ||
| 212 | + """ | ||
| 213 | + return "kelime " * max(1, bayt // 7) | ||
| 214 | + | ||
| 215 | + | ||
| 216 | +class MetinParcalariTestleri(unittest.TestCase): | ||
| 217 | + """`passages` — indekslenen METİN geri dönüyor mu (yalnız sayı değil). | ||
| 218 | + | ||
| 219 | + Sözleşme (backend ve frontend bu anahtarlara karşı kod yazıyor): her satır | ||
| 220 | + `chunk_id`, `doc_id`, `text`, `page_start`, `page_end` taşır; `text` | ||
| 221 | + indekste duranın BİREBİR kendisidir (kısaltmak UI'ın işi); iki tavandan | ||
| 222 | + (50 satır / cevabın tamamı 512 KB) hangisi önce dolarsa liste orada kesilir | ||
| 223 | + ve `passages_truncated` `True` olur. `chunks` KIRPILMAZ — o, indekse yazılan | ||
| 224 | + toplam parça sayısıdır. | ||
| 225 | + """ | ||
| 226 | + | ||
| 227 | + def setUp(self) -> None: | ||
| 228 | + self.index = NoteIndex() | ||
| 229 | + self.embedder = SahteEmbedder() | ||
| 230 | + | ||
| 231 | + def _indeksle(self, **ustune): | ||
| 232 | + return index_course_note(_payload(**ustune), school="okul-a", | ||
| 233 | + note_index=self.index, embedder=self.embedder) | ||
| 234 | + | ||
| 235 | + def test_kucuk_not_butun_parcalari_birebir_tasir(self): | ||
| 236 | + cevap = self._indeksle(content="Birinci paragraf.\nİkinci paragraf.") | ||
| 237 | + self.assertFalse(cevap["passages_truncated"]) | ||
| 238 | + self.assertEqual(len(cevap["passages"]), cevap["chunks"]) | ||
| 239 | + # Satır, indeksteki parçanın AYNISI: id, doc_id, sayfalar, metin. | ||
| 240 | + for satir in cevap["passages"]: | ||
| 241 | + parca = self.index.chunk(satir["chunk_id"]) | ||
| 242 | + self.assertIsNotNone(parca, "chunk_id indekste bulunmalı") | ||
| 243 | + self.assertEqual(satir["text"], parca.text) | ||
| 244 | + self.assertEqual(satir["doc_id"], parca.doc_id) | ||
| 245 | + self.assertEqual((satir["page_start"], satir["page_end"]), | ||
| 246 | + (parca.page_start, parca.page_end)) | ||
| 247 | + # Not metni: not KAPSAMINDA bir id (iki not aynı PDF'i paylaşabilir). | ||
| 248 | + self.assertEqual(cevap["passages"][0]["chunk_id"], "01NOTE:01NOTE:c0") | ||
| 249 | + # `chunks` hâlâ indeksin TAM sayısı (bu testte tek satır). | ||
| 250 | + self.assertEqual(cevap["chunks"], self.index.stats()["okul-a"]) | ||
| 251 | + self.assertIn("İkinci paragraf.", cevap["passages"][0]["text"]) | ||
| 252 | + | ||
| 253 | + def test_parca_sayisi_tavani_tam_bossa_kirpilmadi_der(self): | ||
| 254 | + """Sınır: tam 50 parça → hepsi döner ve bayrak `False` kalır.""" | ||
| 255 | + cevap = self._indeksle(content="\n".join(_metin(1400) for _ in range(MAX_PASSAGES))) | ||
| 256 | + self.assertEqual(cevap["chunks"], MAX_PASSAGES) | ||
| 257 | + self.assertEqual(len(cevap["passages"]), MAX_PASSAGES) | ||
| 258 | + self.assertFalse(cevap["passages_truncated"]) | ||
| 259 | + | ||
| 260 | + def test_parca_sayisi_tavani_dolunca_kirpilir_ama_sayi_tam_kalir(self): | ||
| 261 | + """60 parça: liste tavanda KESİLİR, `chunks` 60 demeye devam eder.""" | ||
| 262 | + cevap = self._indeksle(content="\n".join(_metin(1400) for _ in range(60))) | ||
| 263 | + self.assertGreater(cevap["chunks"], MAX_PASSAGES) | ||
| 264 | + self.assertEqual(len(cevap["passages"]), MAX_PASSAGES) | ||
| 265 | + self.assertTrue(cevap["passages_truncated"]) | ||
| 266 | + # Sayı uydurulmadı: indekse gerçekten yazılan satır sayısı. | ||
| 267 | + self.assertEqual(cevap["chunks"], self.index.stats()["okul-a"]) | ||
| 268 | + | ||
| 269 | + def test_cevabin_bayt_butcesi_asilmaz_kalan_parcalar_kirpilir(self): | ||
| 270 | + """Tek DEV paragraf = tek dev parça; bayt tavanı burada bağlar.""" | ||
| 271 | + icerik = "\n".join(_metin(150 * 1024) for _ in range(4)) | ||
| 272 | + cevap = self._indeksle(content=icerik) | ||
| 273 | + olcu = len(json.dumps(cevap, ensure_ascii=False, | ||
| 274 | + separators=(",", ":")).encode("utf-8")) | ||
| 275 | + self.assertLessEqual(olcu, MAX_PASSAGES_BYTES) | ||
| 276 | + self.assertTrue(cevap["passages_truncated"]) | ||
| 277 | + self.assertLess(len(cevap["passages"]), cevap["chunks"]) | ||
| 278 | + # Sığanlar tam metindir: kırpma METNİN İÇİNDEN değil, LİSTEDEN olur. | ||
| 279 | + self.assertTrue(cevap["passages"]) | ||
| 280 | + self.assertGreater(len(cevap["passages"][0]["text"]), 100 * 1024) | ||
| 281 | + # Tavan GERÇEKTEN bağlayan şey: bir satır daha konsa bütçe AŞILIRDI. | ||
| 282 | + # (Yoksa "kırpıldı" bayrağı başka bir sebeple yanıyor olabilirdi.) | ||
| 283 | + fazlasi = {**cevap, | ||
| 284 | + "passages": cevap["passages"] + [dict(cevap["passages"][0])]} | ||
| 285 | + self.assertGreater( | ||
| 286 | + len(json.dumps(fazlasi, ensure_ascii=False, | ||
| 287 | + separators=(",", ":")).encode("utf-8")), | ||
| 288 | + MAX_PASSAGES_BYTES) | ||
| 289 | + | ||
| 290 | + def test_parca_uretimi_coktugunde_indeks_yine_basarili(self): | ||
| 291 | + """Parça listesi indeksin KENDİSİ değil: üretimi patlarsa cevap düşmez.""" | ||
| 292 | + from unittest import mock | ||
| 293 | + with mock.patch.object(ni, "_passages", | ||
| 294 | + side_effect=RuntimeError("patladı")): | ||
| 295 | + cevap = self._indeksle() | ||
| 296 | + self.assertGreater(cevap["chunks"], 0) | ||
| 297 | + self.assertEqual(cevap["passages"], []) | ||
| 298 | + self.assertTrue(cevap["passages_truncated"]) | ||
| 299 | + self.assertIn("Hücre", cevap["summary"]) | ||
| 300 | + # İndeks GERÇEKTEN yazıldı — düşen bir cevap eski satırı kaybettirirdi. | ||
| 301 | + self.assertEqual(self.index.stats()["okul-a"], cevap["chunks"]) | ||
| 302 | + | ||
| 303 | + | ||
| 204 | if __name__ == "__main__": | 304 | if __name__ == "__main__": |
| 205 | unittest.main() | 305 | unittest.main() |