forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

notes.py264 lines, 10.7 KiBHistoryRawDownload
1"""The course-note index — the retrieval channel `rag.index` fills.
2
3WHY 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,
5ders)`. A course note names none of those on the wire: the `rag.index` payload
6carries the note's `course` **uuid**, while a `rag.chat` scope pair carries a
7class grade and a course **title** (derived by the backend from the asker's own
8memberships) — and the backend's AI-read allowlist has no route that would let
9this service resolve one to the other. There is no join, so a note cannot be
10filed under a subject corpus.
11
12WHAT IT IS INSTEAD. One bucket per **school** — the tenant dimension every store
13already filters on, by exact equality (`guard/tenant.py`). `replace_note()` swaps
14a note's rows as one unit (a re-index never duplicates); `retrieve()` ranks that
15bucket's rows and `rag.chat` merges the hits into the subject corpus's.
16
17HONEST LIMIT — the (class, subject) gate does not reach here. `can_access`
18isolates class+subject for textbook chunks; a note carries neither on the wire,
19so its rows cannot be checked against the asker's scope pairs. The backend still
20refuses to *link* a citation the asker may not open (it stores `file: null`),
21but a note's *text* from another course of the same school can be quoted.
22Closing that needs the note's class+subject on the `rag.index` payload — a wire
23change owned by the backend, not by this repo.
24
25IN-MEMORY, DERIVED, DISPOSABLE. Nothing here is a source of truth: a restart
26loses it, and any note edit re-dispatches `rag.index` — the backend's own model
27of a `rag_output` row ("derived data").
28"""
29from __future__ import annotations
30
31import hashlib
32import threading
33from collections.abc import Mapping
34
35import numpy as np
36
37from src.index.dense import DenseIndex
38from src.index.lexical import BM25Index
39from src.retrieve.rrf import rrf_fuse
40from 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.
45MAX_NOTE_FILE_BYTES = 25 * 1024 * 1024
46
47
48def 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
56class _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
88class 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
205def 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
219class 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
256def 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)