Coverage for app / services / rag.py: 93%

473 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2RAG retrieval service for svc-ai. 

3 

4Uses AsyncQdrantClient directly (no LlamaIndex wrapper) and embeds queries with 

5the deployment's embedding model (``app.services.embeddings``), the one svc-core 

6indexes with — so index and query vectors share one embedding space. A 

7collection built with another model is skipped by the dense leg until svc-core 

8rebuilds it (``dense_ready``); the keyword leg still answers. 

9 

10Public API: 

11 search() — formatted Markdown with scores + sources; used by per-KB 

12 tool factories for agent tool calls. No inner LLM synthesis. 

13 ``lexical=True`` upgrades it to hybrid (dense + keyword). 

14 search_hits() / best_overall() / format_hits() 

15 — the same hybrid search in steps, for ``search_knowledge`` 

16 over several knowledge bases: each one's hits, the best 

17 of them all, then each one's text. 

18 collection_metadata() — a collection's chunk count, TTL-cached; ``None`` when 

19 it could not be read (never cached, never reported as 0). 

20 

21Every nearest-neighbour query goes through ``_nearest`` (``query_points``): 

22qdrant-client 1.17 has no ``search``, and a dense leg calling it failed on 

23every request while the keyword leg answered alone. 

24``tests/services/test_qdrant_contract.py`` holds every client call here to the 

25installed client. 

26 

27Hybrid-retrieval primitives (consumed by ``app.knowledge.retrieval``): 

28 dense_search() — embedding similarity search → list[VectorHit] 

29 lexical_search() — Qdrant full-text (MatchText) keyword search scored in-process 

30 fetch_window() — neighbouring chunks of a document for context expansion 

31 rrf_fuse() — reciprocal-rank fusion of several ranked id lists 

32 extract_keywords() — stop-word-filtered salient terms of a query 

33""" 

34 

35from __future__ import annotations 

36 

37import asyncio 

38import logging 

39import math 

40import re 

41import time 

42from collections.abc import Mapping, Sequence 

43from dataclasses import dataclass, field 

44from typing import Any 

45 

46from opentelemetry import trace as _otel_trace 

47from qdrant_client import AsyncQdrantClient 

48 

49from app.common.settings import get_settings 

50from app.knowledge import passage_text 

51from app.models.spec import RAGConfig 

52from app.services import embeddings, model_errors 

53from app.util import source_registry, source_trailers 

54 

55_tracer = _otel_trace.get_tracer(__name__) 

56 

57settings = get_settings() 

58logger = logging.getLogger(__name__) 

59 

60# Sentinel appended to tool output so citation extractor can locate sources. 

61_SOURCES_MARKER = source_trailers.KNOWLEDGE 

62 

63 

64def split_sources(body: str) -> tuple[str, list[str | dict[str, Any]]]: 

65 """A search result's text without its ``__SOURCES__`` trailer, and the 

66 sources the trailer lists (read from the last marker; see 

67 ``app.util.source_trailers``): each a name, or ``{"source", 

68 "citation_id"}`` within a run. 

69 

70 For a caller that combines several results into one — a search of every 

71 knowledge base attached — and writes one trailer for them all. 

72 """ 

73 head, entries = source_trailers.split(body, _SOURCES_MARKER) 

74 return head, [ 

75 e 

76 for e in entries 

77 if (isinstance(e, str) and e) or (isinstance(e, dict) and e.get("source")) 

78 ] 

79 

80 

81def append_sources(body: str, sources: list) -> str: 

82 """``body`` ending in the trailer that lists ``sources``: each a source's 

83 name, or ``{"source", "kb_name"}``. As it is when there are none.""" 

84 return source_trailers.append(body, _SOURCES_MARKER, sources) 

85 

86 

87# Metadata cache TTL — evict entries older than this many seconds. 

88_METADATA_TTL: float = 300.0 

89#: How long a count that is unknown, or 0, is kept: briefly, so a Qdrant that 

90#: cannot answer is not waited on by every turn, and a first upload shows. 

91_UNSETTLED_TTL: float = 20.0 

92#: How long the routing inventory waits for a collection's count. It is on 

93#: the path to every turn's first model call. 

94_COUNT_TIMEOUT_S: float = 3.0 

95 

96# ── Singletons ──────────────────────────────────────────────────────────────── 

97 

98_aclient: AsyncQdrantClient | None = None 

99_metadata_cache: dict[str, dict] = {} 

100 

101 

102def get_aclient() -> AsyncQdrantClient: 

103 global _aclient 

104 if _aclient is None: 

105 _aclient = AsyncQdrantClient(url=settings.qdrant_url) 

106 return _aclient 

107 

108 

109# ── Internal helpers ────────────────────────────────────────────────────────── 

110 

111 

112def _to_collection_name(kb_id: str) -> str: 

113 """Normalise a knowledge base UUID to the Qdrant collection name used by svc-core.""" 

114 if kb_id.startswith("kb_"): 

115 return kb_id 

116 return f"kb_{kb_id.replace('-', '_')}" 

117 

118 

119async def _embed(text: str) -> list[float]: 

120 """Embed *text* with the deployment's embedding model.""" 

121 embedder = embeddings.active() 

122 with _tracer.start_as_current_span("rag.embed") as span: 

123 if span.is_recording(): 

124 span.set_attribute("embedding.model", embedder.model) 

125 span.set_attribute("embedding.input_length", len(text)) 

126 return await embedder.embed_one(text) 

127 

128 

129async def embed_texts(texts: list[str]) -> list[list[float]]: 

130 """Embed many texts with the deployment's embedding model, in order. 

131 

132 This is the single embedding entry point for the platform: svc-core's 

133 ingestion calls it through ``POST /knowledge/embed`` (svc-core has no LLM 

134 egress), and retrieval uses the same model here — so index and query 

135 vectors are guaranteed to share one embedding space. 

136 """ 

137 embedder = embeddings.active() 

138 with _tracer.start_as_current_span("rag.embed_batch") as span: 

139 if span.is_recording(): 

140 span.set_attribute("embedding.model", embedder.model) 

141 span.set_attribute("embedding.batch_size", len(texts)) 

142 return await embedder.embed_many(texts) 

143 

144 

145# ── Which embedding space a collection is in ───────────────────────────────── 

146 

147#: A collection svc-core created before collections recorded their embedder 

148#: holds OpenAI's 1536-dimension vectors, the only ones there were. 

149LEGACY_KEY = "openai/text-embedding-3-small/1536" 

150_LEGACY_SIZE = 1536 

151 

152#: How long a collection's recorded embedder is trusted before it is read 

153#: again — short, so a rebuilt collection is searched again within a minute. 

154_SPACE_TTL: float = 60.0 

155_space_cache: dict[str, tuple[float, str | None]] = {} 

156_warned: set[tuple[str, str]] = set() 

157 

158#: What ``_collection_key`` records for a collection Qdrant says does not 

159#: exist. svc-core creates a knowledge base's collection on its first upload 

160#: or crawl, so a new knowledge base — or a website source not yet crawled — 

161#: has none. It holds nothing: there is nothing to search, and nothing failed. 

162MISSING = "missing" 

163 

164 

165def _is_missing(exc: BaseException) -> bool: 

166 """Whether *exc* is Qdrant saying the collection does not exist.""" 

167 return getattr(exc, "status_code", None) == 404 

168 

169 

170async def _collection_key(collection_name: str) -> str | None: 

171 """The embedder a collection's vectors came from; ``MISSING`` when the 

172 collection does not exist; None when it cannot be told (Qdrant 

173 unreachable, an unexpected shape).""" 

174 cached = _space_cache.get(collection_name) 

175 if cached and time.monotonic() - cached[0] < _SPACE_TTL: 

176 return cached[1] 

177 key: str | None = None 

178 try: 

179 info = await get_aclient().get_collection(collection_name) 

180 config = getattr(info, "config", None) 

181 metadata = getattr(config, "metadata", None) 

182 recorded = ( 

183 metadata.get("embedding", {}).get("key") 

184 if isinstance(metadata, dict) 

185 else None 

186 ) 

187 size = getattr( 

188 getattr(getattr(config, "params", None), "vectors", None), "size", None 

189 ) 

190 if isinstance(recorded, str): 

191 key = recorded 

192 elif isinstance(size, int): 

193 key = LEGACY_KEY if size == _LEGACY_SIZE else f"unknown/{size}" 

194 except Exception as exc: # noqa: BLE001 — unknown, not incompatible 

195 key = MISSING if _is_missing(exc) else None 

196 _space_cache[collection_name] = (time.monotonic(), key) 

197 return key 

198 

199 

200async def collection_missing(collection: str) -> bool: 

201 """Whether *collection* has never been created (nothing indexed yet).""" 

202 return await _collection_key(_to_collection_name(collection)) == MISSING 

203 

204 

205async def dense_ready(collection: str) -> bool: 

206 """Whether *collection* can be searched with the active embedder. 

207 

208 False only when the collection is known to hold another model's vectors 

209 — searching it would fail, or worse, compare across spaces. Unknown 

210 counts as ready: the search itself then succeeds or fails as before. A 

211 missing collection is in no space at all (``collection_missing``). 

212 """ 

213 name = _to_collection_name(collection) 

214 key = await _collection_key(name) 

215 wanted = embeddings.active().key() 

216 if key in (None, MISSING) or key == wanted: 

217 return True 

218 if (name, key) not in _warned: 

219 _warned.add((name, key)) 

220 logger.warning( 

221 "%s holds %s vectors but the embedding model is %s; its dense " 

222 "search is skipped until svc-core rebuilds it", 

223 name, 

224 key, 

225 wanted, 

226 ) 

227 return False 

228 

229 

230def forget_collection_spaces() -> None: 

231 """Drop the cached embedders of every collection (tests).""" 

232 _space_cache.clear() 

233 _warned.clear() 

234 

235 

236REBUILDING_MESSAGE = ( 

237 "This knowledge base is being re-indexed for a new search model; try again shortly." 

238) 

239EMPTY_MESSAGE = "This knowledge base has nothing indexed yet." 

240#: A search that found nothing above its floor. 

241NO_RESULTS = "No results found above the relevance threshold." 

242 

243 

244def _extract_source(payload: dict) -> str: 

245 return ( 

246 payload.get("original_filename") 

247 or payload.get("file_name") 

248 or payload.get("source") 

249 or payload.get("file_path") 

250 or "" 

251 ) 

252 

253 

254# ── Hybrid-retrieval primitives ─────────────────────────────────────────────── 

255 

256 

257@dataclass 

258class VectorHit: 

259 """One Qdrant point returned by a dense or lexical search leg.""" 

260 

261 point_id: str 

262 payload: dict 

263 dense_score: float | None = None 

264 lexical_score: float | None = None 

265 matched_queries: list[str] = field(default_factory=list) 

266 

267 @property 

268 def text(self) -> str: 

269 return str(self.payload.get("text", "")).strip() 

270 

271 @property 

272 def source(self) -> str: 

273 return _extract_source(self.payload) 

274 

275 

276_STOPWORDS: frozenset[str] = frozenset( 

277 [ 

278 "a", 

279 "an", 

280 "the", 

281 "and", 

282 "or", 

283 "but", 

284 "if", 

285 "then", 

286 "else", 

287 "of", 

288 "for", 

289 "to", 

290 "in", 

291 "on", 

292 "at", 

293 "by", 

294 "with", 

295 "from", 

296 "as", 

297 "is", 

298 "are", 

299 "was", 

300 "were", 

301 "be", 

302 "been", 

303 "being", 

304 "do", 

305 "does", 

306 "did", 

307 "doing", 

308 "have", 

309 "has", 

310 "had", 

311 "having", 

312 "this", 

313 "that", 

314 "these", 

315 "those", 

316 "it", 

317 "its", 

318 "i", 

319 "me", 

320 "my", 

321 "we", 

322 "our", 

323 "you", 

324 "your", 

325 "he", 

326 "she", 

327 "they", 

328 "them", 

329 "their", 

330 "what", 

331 "which", 

332 "who", 

333 "whom", 

334 "whose", 

335 "when", 

336 "where", 

337 "why", 

338 "how", 

339 "all", 

340 "any", 

341 "both", 

342 "each", 

343 "few", 

344 "more", 

345 "most", 

346 "other", 

347 "some", 

348 "such", 

349 "no", 

350 "nor", 

351 "not", 

352 "only", 

353 "own", 

354 "same", 

355 "so", 

356 "than", 

357 "too", 

358 "very", 

359 "can", 

360 "will", 

361 "just", 

362 "should", 

363 "would", 

364 "could", 

365 "may", 

366 "might", 

367 "must", 

368 "about", 

369 "above", 

370 "after", 

371 "again", 

372 "against", 

373 "also", 

374 "am", 

375 "because", 

376 "before", 

377 "below", 

378 "between", 

379 "during", 

380 "into", 

381 "over", 

382 "under", 

383 "until", 

384 "up", 

385 "down", 

386 "out", 

387 "off", 

388 "once", 

389 "here", 

390 "there", 

391 "while", 

392 "further", 

393 "please", 

394 "tell", 

395 "give", 

396 "show", 

397 "explain", 

398 "describe", 

399 "find", 

400 "list", 

401 "summarise", 

402 "summarize", 

403 "summary", 

404 "find", 

405 "need", 

406 "want", 

407 "know", 

408 "using", 

409 "use", 

410 "used", 

411 "via", 

412 "per", 

413 "vs", 

414 "versus", 

415 ] 

416) 

417 

418_TOKEN_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_\-\.]{1,}") 

419 

420 

421def extract_keywords(query: str, max_terms: int = 8) -> list[str]: 

422 """Return the salient, stop-word-filtered terms of *query* (order preserved). 

423 

424 Terms shorter than three characters are dropped unless they contain a 

425 digit (ticket numbers, versions). Duplicates are removed case-insensitively. 

426 """ 

427 seen: set[str] = set() 

428 terms: list[str] = [] 

429 for raw in _TOKEN_RE.findall(query or ""): 

430 tok = raw.strip("._-") 

431 low = tok.lower() 

432 if not tok or low in _STOPWORDS: 

433 continue 

434 if len(tok) < 3 and not any(ch.isdigit() for ch in tok): 

435 continue 

436 if low in seen: 

437 continue 

438 seen.add(low) 

439 terms.append(tok) 

440 if len(terms) >= max_terms: 

441 break 

442 return terms 

443 

444 

445def rrf_fuse( 

446 rankings: list[list[str]], k: int = 60, weights: list[float] | None = None 

447) -> dict[str, float]: 

448 """Reciprocal-rank fusion of several ranked id lists. 

449 

450 score(id) = Σ_r weight_r / (k + rank_r(id)). Ids absent from a ranking 

451 contribute nothing for that ranking. Returned dict is unsorted. 

452 """ 

453 fused: dict[str, float] = {} 

454 for i, ranking in enumerate(rankings): 

455 w = weights[i] if weights and i < len(weights) else 1.0 

456 for rank, pid in enumerate(ranking, 1): 

457 fused[pid] = fused.get(pid, 0.0) + w / (k + rank) 

458 return fused 

459 

460 

461def _document_filter(document_ids: list[str] | None): 

462 """Qdrant filter restricting results to the given document ids (or None).""" 

463 if not document_ids: 

464 return None 

465 from qdrant_client.models import FieldCondition, Filter, MatchAny 

466 

467 return Filter( 

468 must=[FieldCondition(key="document_id", match=MatchAny(any=list(document_ids)))] 

469 ) 

470 

471 

472_INDEX_PAYLOAD_FIELDS = [ 

473 "document_id", 

474 "original_filename", 

475 "source_id", 

476 "folder_path", 

477 "mime_type", 

478 "page_number", 

479 "chunk_index", 

480] 

481 

482 

483async def scan_document_index(collection: str, max_points: int = 5000) -> list[dict]: 

484 """Payload metadata (no text) of up to *max_points* points in a collection. 

485 

486 Used to enumerate the documents a knowledge base holds. Returns [] when 

487 the collection is missing or unreachable. 

488 """ 

489 collection_name = _to_collection_name(collection) 

490 out: list[dict] = [] 

491 offset = None 

492 try: 

493 while len(out) < max_points: 

494 page, offset = await get_aclient().scroll( 

495 collection_name=collection_name, 

496 limit=min(500, max_points - len(out)), 

497 offset=offset, 

498 with_payload=_INDEX_PAYLOAD_FIELDS, 

499 with_vectors=False, 

500 ) 

501 out.extend(dict(pt.payload or {}) for pt in (page or [])) 

502 if not offset or not page: 

503 break 

504 except Exception as exc: 

505 logger.debug( 

506 "scan_document_index: scroll failed (%s): %s", collection_name, exc 

507 ) 

508 return [] 

509 return out 

510 

511 

512async def fetch_document_chunks( 

513 collection: str, document_id: str, max_chunks: int = 2000 

514) -> list[dict]: 

515 """Every chunk payload of *document_id*, ordered by ``chunk_index``.""" 

516 collection_name = _to_collection_name(collection) 

517 flt = _document_filter([document_id]) 

518 out: list[dict] = [] 

519 offset = None 

520 try: 

521 while len(out) < max_chunks: 

522 page, offset = await get_aclient().scroll( 

523 collection_name=collection_name, 

524 scroll_filter=flt, 

525 limit=min(500, max_chunks - len(out)), 

526 offset=offset, 

527 with_payload=True, 

528 with_vectors=False, 

529 ) 

530 out.extend(dict(pt.payload or {}) for pt in (page or [])) 

531 if not offset or not page: 

532 break 

533 except Exception as exc: 

534 logger.warning( 

535 "fetch_document_chunks: scroll failed (%s): %s", collection_name, exc 

536 ) 

537 return [] 

538 out.sort(key=lambda p: int(p.get("chunk_index") or 0)) 

539 return out 

540 

541 

542async def _nearest( 

543 collection_name: str, 

544 vector: list[float], 

545 *, 

546 limit: int, 

547 score_threshold: float | None = None, 

548 query_filter=None, 

549) -> list: 

550 """The points nearest *vector*, best first (``ScoredPoint``: id, score, 

551 payload). The one nearest-neighbour query in svc-ai.""" 

552 response = await get_aclient().query_points( 

553 collection_name=collection_name, 

554 query=vector, 

555 query_filter=query_filter, 

556 limit=limit, 

557 score_threshold=score_threshold, 

558 with_payload=True, 

559 with_vectors=False, 

560 ) 

561 return list(response.points or []) 

562 

563 

564#: What a dense leg reports when its collection is in another embedding 

565#: space: not a failure, a rebuild svc-core is running. 

566REINDEXING_NOTE = "semantic search skipped while the knowledge base is re-indexed" 

567 

568 

569async def dense_search( 

570 collection: str, 

571 query: str, 

572 *, 

573 limit: int = 20, 

574 score_threshold: float | None = None, 

575 document_ids: list[str] | None = None, 

576 failures: list[str] | None = None, 

577) -> list[VectorHit]: 

578 """Embedding-similarity search; returns hits ordered by descending score. 

579 

580 ``document_ids`` restricts the search to specific documents. A leg that 

581 could not run returns [] — and, when *failures* is given, says why in one 

582 line there, so a caller can tell "nothing similar" from "not searched". 

583 """ 

584 with _tracer.start_as_current_span("rag.dense_search") as span: 

585 collection_name = _to_collection_name(collection) 

586 if span.is_recording(): 

587 span.set_attribute("rag.collection", collection_name) 

588 span.set_attribute("rag.limit", limit) 

589 if await collection_missing(collection_name): 

590 return [] # nothing indexed yet: nothing to embed for 

591 if not await dense_ready(collection_name): 

592 if failures is not None: 

593 failures.append(f"{collection_name}: {REINDEXING_NOTE}") 

594 return [] 

595 try: 

596 vector = await _embed(query) 

597 except Exception as exc: 

598 logger.warning("dense_search: embed failed (%s): %s", collection_name, exc) 

599 if failures is not None: 

600 failures.append( 

601 f"{collection_name}: embedding failed ({model_errors.describe(exc)})" 

602 ) 

603 return [] 

604 try: 

605 results = await _nearest( 

606 collection_name, 

607 vector, 

608 limit=limit, 

609 score_threshold=score_threshold, 

610 query_filter=_document_filter(document_ids), 

611 ) 

612 except Exception as exc: 

613 if _is_missing(exc): 

614 return [] # deleted since its key was read: it holds nothing 

615 logger.warning( 

616 "dense_search: Qdrant search failed (%s): %s", collection_name, exc 

617 ) 

618 if failures is not None: 

619 failures.append( 

620 f"{collection_name}: semantic search failed " 

621 f"({model_errors.describe(exc)})" 

622 ) 

623 return [] 

624 hits = [ 

625 VectorHit( 

626 point_id=str(r.id), 

627 payload=dict(r.payload or {}), 

628 dense_score=float(r.score), 

629 matched_queries=[query], 

630 ) 

631 for r in results 

632 if r.payload and str(r.payload.get("text", "")).strip() 

633 ] 

634 if span.is_recording(): 

635 span.set_attribute("rag.result_count", len(hits)) 

636 return hits 

637 

638 

639def _lexical_score(text: str, terms: list[str], idf: dict[str, float]) -> float: 

640 """BM25-flavoured score of *text* for *terms* using the supplied IDF table.""" 

641 low = text.lower() 

642 length = max(len(low.split()), 1) 

643 k1, b, avg_len = 1.2, 0.75, 300.0 

644 score = 0.0 

645 for term in terms: 

646 tf = low.count(term.lower()) 

647 if not tf: 

648 continue 

649 norm = tf * (k1 + 1) / (tf + k1 * (1 - b + b * length / avg_len)) 

650 score += idf.get(term.lower(), 1.0) * norm 

651 return score 

652 

653 

654async def lexical_search( 

655 collection: str, 

656 query: str, 

657 *, 

658 limit: int = 20, 

659 scan_limit: int = 200, 

660 document_ids: list[str] | None = None, 

661) -> list[VectorHit]: 

662 """Keyword search via Qdrant's full-text ``MatchText`` filter. 

663 

664 Candidate points containing *any* salient query term are scrolled (up to 

665 ``scan_limit``), then scored in-process with a BM25-style function so the 

666 ranking rewards multiple distinct term matches. Returns hits ordered by 

667 descending lexical score. Requires no embedding call. 

668 """ 

669 from qdrant_client.models import FieldCondition, Filter, MatchText 

670 

671 terms = extract_keywords(query) 

672 if not terms: 

673 return [] 

674 

675 with _tracer.start_as_current_span("rag.lexical_search") as span: 

676 collection_name = _to_collection_name(collection) 

677 if span.is_recording(): 

678 span.set_attribute("rag.collection", collection_name) 

679 span.set_attribute("rag.terms", ", ".join(terms)) 

680 

681 doc_filter = _document_filter(document_ids) 

682 flt = Filter( 

683 must=list(doc_filter.must) if doc_filter is not None else None, 

684 should=[ 

685 FieldCondition(key="text", match=MatchText(text=term)) for term in terms 

686 ], 

687 ) 

688 candidates: list = [] 

689 try: 

690 offset = None 

691 while len(candidates) < scan_limit: 

692 page, offset = await get_aclient().scroll( 

693 collection_name=collection_name, 

694 scroll_filter=flt, 

695 limit=min(100, scan_limit - len(candidates)), 

696 offset=offset, 

697 with_payload=True, 

698 with_vectors=False, 

699 ) 

700 candidates.extend(page or []) 

701 if not offset or not page: 

702 break 

703 except Exception as exc: 

704 if not _is_missing(exc): 

705 logger.warning( 

706 "lexical_search: Qdrant scroll failed (%s): %s", 

707 collection_name, 

708 exc, 

709 ) 

710 return [] 

711 

712 texts = [str((pt.payload or {}).get("text", "")) for pt in candidates] 

713 n = max(len(texts), 1) 

714 idf: dict[str, float] = {} 

715 for term in terms: 

716 df = sum(1 for t in texts if term.lower() in t.lower()) 

717 idf[term.lower()] = math.log(1 + (n - df + 0.5) / (df + 0.5)) 

718 

719 hits: list[VectorHit] = [] 

720 for pt, text in zip(candidates, texts): 

721 if not text.strip(): 

722 continue 

723 score = _lexical_score(text, terms, idf) 

724 if score <= 0: 

725 continue 

726 hits.append( 

727 VectorHit( 

728 point_id=str(pt.id), 

729 payload=dict(pt.payload or {}), 

730 lexical_score=score, 

731 matched_queries=[query], 

732 ) 

733 ) 

734 hits.sort(key=lambda h: h.lexical_score or 0.0, reverse=True) 

735 if span.is_recording(): 

736 span.set_attribute("rag.result_count", len(hits)) 

737 return hits[:limit] 

738 

739 

740async def fetch_window( 

741 collection: str, 

742 document_id: str, 

743 lo: int, 

744 hi: int, 

745) -> list[dict]: 

746 """Return the payloads of chunks ``lo..hi`` (inclusive) of *document_id*, 

747 ordered by ``chunk_index``. Used for neighbour expansion.""" 

748 from qdrant_client.models import FieldCondition, Filter, MatchValue, Range 

749 

750 if hi < lo: 

751 return [] 

752 collection_name = _to_collection_name(collection) 

753 flt = Filter( 

754 must=[ 

755 FieldCondition(key="document_id", match=MatchValue(value=document_id)), 

756 FieldCondition(key="chunk_index", range=Range(gte=lo, lte=hi)), 

757 ] 

758 ) 

759 try: 

760 page, _ = await get_aclient().scroll( 

761 collection_name=collection_name, 

762 scroll_filter=flt, 

763 limit=(hi - lo + 1), 

764 with_payload=True, 

765 with_vectors=False, 

766 ) 

767 except Exception as exc: 

768 logger.debug("fetch_window: scroll failed (%s): %s", collection_name, exc) 

769 return [] 

770 payloads = [dict(pt.payload or {}) for pt in (page or [])] 

771 payloads.sort(key=lambda p: int(p.get("chunk_index") or 0)) 

772 return payloads 

773 

774 

775async def hybrid_hits( 

776 collection: str, 

777 queries: list[str], 

778 *, 

779 candidate_k: int = 20, 

780 score_threshold: float | None = None, 

781 lexical: bool = True, 

782 rrf_k: int = 60, 

783 lexical_only_queries: list[str] | None = None, 

784 document_ids: list[str] | None = None, 

785 failures: list[str] | None = None, 

786) -> list[VectorHit]: 

787 """Dense (+ lexical) search over every query, fused with RRF. 

788 

789 ``lexical_only_queries`` (entity names, identifiers) get a keyword leg but 

790 no embedding call. Returns merged hits ordered by fused score; each hit 

791 records which queries matched it and the best dense / lexical scores. 

792 A dense leg that could not run says why in *failures* (once per reason). 

793 """ 

794 dense_failures: list[str] = [] 

795 dense_tasks = [ 

796 dense_search( 

797 collection, 

798 q, 

799 limit=candidate_k, 

800 score_threshold=score_threshold, 

801 document_ids=document_ids, 

802 failures=dense_failures, 

803 ) 

804 for q in queries 

805 ] 

806 lexical_queries = [*queries, *(lexical_only_queries or [])] if lexical else [] 

807 lexical_tasks = [ 

808 lexical_search(collection, q, limit=candidate_k, document_ids=document_ids) 

809 for q in lexical_queries 

810 ] 

811 results = await asyncio.gather(*dense_tasks, *lexical_tasks) 

812 if failures is not None: 

813 for line in dense_failures: 

814 if line not in failures: 

815 failures.append(line) 

816 dense_lists = results[: len(dense_tasks)] 

817 lexical_lists = results[len(dense_tasks) :] 

818 

819 by_id: dict[str, VectorHit] = {} 

820 rankings: list[list[str]] = [] 

821 weights: list[float] = [] 

822 for hits in dense_lists: 

823 rankings.append([h.point_id for h in hits]) 

824 weights.append(1.0) 

825 for h in hits: 

826 _merge_hit(by_id, h) 

827 for hits in lexical_lists: 

828 rankings.append([h.point_id for h in hits]) 

829 weights.append(0.8) 

830 for h in hits: 

831 _merge_hit(by_id, h) 

832 

833 fused = rrf_fuse(rankings, k=rrf_k, weights=weights) 

834 ordered = sorted( 

835 by_id.values(), key=lambda h: fused.get(h.point_id, 0.0), reverse=True 

836 ) 

837 for h in ordered: 

838 h.payload["_fused_score"] = fused.get(h.point_id, 0.0) 

839 return ordered 

840 

841 

842def _merge_hit(by_id: dict[str, VectorHit], hit: VectorHit) -> None: 

843 cur = by_id.get(hit.point_id) 

844 if cur is None: 

845 by_id[hit.point_id] = VectorHit( 

846 point_id=hit.point_id, 

847 payload=dict(hit.payload), 

848 dense_score=hit.dense_score, 

849 lexical_score=hit.lexical_score, 

850 matched_queries=list(hit.matched_queries), 

851 ) 

852 return 

853 if hit.dense_score is not None: 

854 cur.dense_score = max(cur.dense_score or 0.0, hit.dense_score) 

855 if hit.lexical_score is not None: 

856 cur.lexical_score = max(cur.lexical_score or 0.0, hit.lexical_score) 

857 for q in hit.matched_queries: 

858 if q not in cur.matched_queries: 

859 cur.matched_queries.append(q) 

860 

861 

862# ── Public API ──────────────────────────────────────────────────────────────── 

863 

864 

865def invalidate_metadata_cache(kb_id: str | None = None) -> None: 

866 """Evict cached collection metadata for one KB (or all when kb_id is None).""" 

867 if kb_id is None: 

868 _metadata_cache.clear() 

869 else: 

870 _metadata_cache.pop(kb_id, None) 

871 

872 

873async def collection_metadata(kb_id: str) -> dict: 

874 """A collection's chunk count, TTL-cached. 

875 

876 Returns ``{"vector_count": int | None}``. ``None`` means the collection 

877 could not be read in ``_COUNT_TIMEOUT_S``: unknown, never reported as 0 

878 (an empty knowledge base is described to routing as "do not query", and 

879 left out of the turn's search). A 0 from the collection's approximate 

880 count is confirmed by an exact one. 

881 A collection never created holds 0. Either is asked again after 

882 ``_UNSETTLED_TTL`` — an unreadable Qdrant is not waited on every turn, and 

883 a first upload creates the collection at any moment — and a count after 

884 ``_METADATA_TTL``. 

885 

886 The documents a knowledge base holds come from svc-core's manifest and 

887 the index scan (``app.knowledge.documents.list_documents``), not from here. 

888 """ 

889 cached = _metadata_cache.get(kb_id) 

890 if cached and (time.monotonic() - cached["_ts"]) < cached["_ttl"]: 

891 return {k: v for k, v in cached.items() if not k.startswith("_")} 

892 

893 collection_name = _to_collection_name(kb_id) 

894 count: int | None = None 

895 try: 

896 info = await asyncio.wait_for( 

897 get_aclient().get_collection(collection_name), _COUNT_TIMEOUT_S 

898 ) 

899 count = info.points_count 

900 if count is None: 

901 logger.warning( 

902 "collection_metadata: %s reports no point count", collection_name 

903 ) 

904 elif count == 0: 

905 # ``points_count`` is approximate, and a 0 says "do not search 

906 # it" (the mix leaves it out): confirmed exactly before it does. 

907 exact = await asyncio.wait_for( 

908 get_aclient().count(collection_name, exact=True), _COUNT_TIMEOUT_S 

909 ) 

910 count = int(exact.count) 

911 except Exception as exc: 

912 if _is_missing(exc): 

913 count = 0 # never created: nothing has been indexed into it 

914 else: 

915 logger.warning( 

916 "collection_metadata: could not read %s: %s", 

917 collection_name, 

918 model_errors.describe(exc), 

919 ) 

920 settled = bool(count) 

921 result = {"vector_count": None if count is None else int(count)} 

922 _metadata_cache[kb_id] = { 

923 **result, 

924 "_ts": time.monotonic(), 

925 "_ttl": _METADATA_TTL if settled else _UNSETTLED_TTL, 

926 } 

927 logger.debug("collection_metadata: kb=%s points=%s", kb_id, count) 

928 return result 

929 

930 

931async def search( 

932 config: RAGConfig, 

933 query: str, 

934 *, 

935 lexical: bool = False, 

936 dated: bool = False, 

937 hits: list[tuple[str, int]] | None = None, 

938) -> str: 

939 """ 

940 Retrieve chunks and format them as a structured string for agent tool consumption. 

941 

942 Returns numbered chunks with relevance scores and source attribution, ready for 

943 an agent to reason over directly. No inner LLM synthesis call — the calling 

944 agent performs its own synthesis from the raw evidence. 

945 

946 ``lexical=True`` runs hybrid retrieval (dense + keyword legs fused with RRF) 

947 so exact identifiers, names and rare terms are found even when embedding 

948 similarity alone would miss them. 

949 

950 ``dated`` (temporal knowledge) shows each result's date and lists them 

951 newest first. 

952 

953 ``hits``, when given, collects each result's ``(document_id, 

954 chunk_index)``: the turn's retrieval record counts a passage once, 

955 however many searches returned it (``knowledge.turn_report``). 

956 

957 A ``__SOURCES__:`` suffix is appended for citation extraction by agent.py. 

958 """ 

959 threshold = _strict_floor(config) 

960 with _tracer.start_as_current_span("rag.search") as span: 

961 if span.is_recording(): 

962 span.set_attribute("rag.collection", config.collection) 

963 span.set_attribute("rag.top_k", config.top_k) 

964 span.set_attribute("rag.score_threshold", threshold) 

965 span.set_attribute("rag.lexical", lexical) 

966 

967 if lexical: 

968 found = await search_hits(config, query) 

969 results = [_HitView.of_hybrid(h) for h in found] 

970 return _format_search_results(results, span, dated=dated, hits=hits) 

971 

972 if await collection_missing(config.collection): 

973 return EMPTY_MESSAGE 

974 if not await dense_ready(config.collection): 

975 return REBUILDING_MESSAGE 

976 try: 

977 query_vector = await _embed(query) 

978 except Exception as exc: 

979 logger.warning( 

980 "search: embed failed for collection %s: %s", config.collection, exc 

981 ) 

982 if span.is_recording(): 

983 span.set_attribute("rag.error", f"embed: {exc}") 

984 return "Knowledge base search unavailable (embedding error)." 

985 

986 try: 

987 points = await _nearest( 

988 _to_collection_name(config.collection), 

989 query_vector, 

990 limit=config.top_k, 

991 score_threshold=threshold, 

992 ) 

993 except Exception as exc: 

994 if _is_missing(exc): 

995 return EMPTY_MESSAGE 

996 logger.warning( 

997 "search: Qdrant search failed for collection %s: %s", 

998 config.collection, 

999 exc, 

1000 ) 

1001 if span.is_recording(): 

1002 span.set_attribute("rag.error", f"qdrant: {exc}") 

1003 return "Knowledge base search failed." 

1004 

1005 return _format_search_results( 

1006 [_HitView.of_point(p) for p in points], span, dated=dated, hits=hits 

1007 ) 

1008 

1009 

1010async def search_hits(config: RAGConfig, query: str) -> list[VectorHit]: 

1011 """One knowledge base's best ``config.top_k`` hybrid hits for ``query``, 

1012 in fused order, as :func:`search` finds them before it formats them.""" 

1013 found = await hybrid_hits( 

1014 config.collection, 

1015 [query], 

1016 candidate_k=max(config.top_k * 3, 10), 

1017 score_threshold=_strict_floor(config), 

1018 lexical=True, 

1019 ) 

1020 return found[: config.top_k] 

1021 

1022 

1023def best_overall( 

1024 hits_by_kb: Mapping[str, Sequence[VectorHit]], top_k: int, *, rrf_k: int = 60 

1025) -> list[tuple[str, list[VectorHit]]]: 

1026 """The best ``top_k`` of several knowledge bases' hits, ranked together: 

1027 each knowledge base with the hits it keeps, in its own order, the one 

1028 holding the best hit first. Knowledge bases keeping none are left out. 

1029 

1030 Ranked as :func:`hybrid_hits` ranks one knowledge base's: the similarity 

1031 of every hit (one embedder, so comparable) and its keyword score, fused 

1032 by rank with the same weights. A search of every knowledge base kept 

1033 ``top_k`` of each — 13 knowledge bases, 22–31k tokens a call, and one 

1034 turn's input 1.1M tokens (scenario run 7, a-patching).""" 

1035 keyed = [(kb, h) for kb, hits in hits_by_kb.items() for h in hits] 

1036 

1037 def key(item: tuple[str, VectorHit]) -> str: 

1038 return f"{item[0]}\x00{item[1].point_id}" 

1039 

1040 dense = sorted( 

1041 (x for x in keyed if x[1].dense_score is not None), 

1042 key=lambda x: x[1].dense_score or 0.0, 

1043 reverse=True, 

1044 ) 

1045 lexical = sorted( 

1046 (x for x in keyed if x[1].lexical_score is not None), 

1047 key=lambda x: x[1].lexical_score or 0.0, 

1048 reverse=True, 

1049 ) 

1050 fused = rrf_fuse( 

1051 [[key(x) for x in dense], [key(x) for x in lexical]], 

1052 k=rrf_k, 

1053 weights=[1.0, 0.8], 

1054 ) 

1055 best = sorted(keyed, key=lambda x: fused.get(key(x), 0.0), reverse=True)[:top_k] 

1056 kept = {key(x) for x in best} 

1057 order = list(dict.fromkeys(kb for kb, _ in best)) 

1058 return [(kb, [h for h in hits_by_kb[kb] if key((kb, h)) in kept]) for kb in order] 

1059 

1060 

1061def format_hits( 

1062 found: Sequence[VectorHit], 

1063 *, 

1064 dated: bool = False, 

1065 hits: list[tuple[str, int]] | None = None, 

1066) -> str: 

1067 """``found`` as :func:`search` formats its results: each labelled with 

1068 its source's id, its source trailer last.""" 

1069 with _tracer.start_as_current_span("rag.format_hits") as span: 

1070 return _format_search_results( 

1071 [_HitView.of_hybrid(h) for h in found], span, dated=dated, hits=hits 

1072 ) 

1073 

1074 

1075def _strict_floor(config: RAGConfig) -> float: 

1076 """The similarity floor a per-knowledge-base search applies: the 

1077 config's own, or the embedding model's ``strict`` one.""" 

1078 if config.score_threshold is not None: 

1079 return config.score_threshold 

1080 return embeddings.active().floors.strict 

1081 

1082 

1083@dataclass 

1084class _HitView: 

1085 """One search result as the formatter shows it: its payload and how it 

1086 was found. A keyword-only hybrid hit has no similarity to show, so it 

1087 says "keyword match" rather than "relevance 0.000".""" 

1088 

1089 payload: dict 

1090 label: str 

1091 

1092 @classmethod 

1093 def of_point(cls, point) -> _HitView: 

1094 return cls(dict(point.payload or {}), f"relevance {float(point.score):.3f}") 

1095 

1096 @classmethod 

1097 def of_hybrid(cls, hit: VectorHit) -> _HitView: 

1098 if hit.dense_score is None: 

1099 return cls(hit.payload, "keyword match") 

1100 return cls(hit.payload, f"relevance {hit.dense_score:.3f}") 

1101 

1102 

1103def _result_date(payload: dict) -> str: 

1104 """A result's date as a search shows it: its publication, else when its 

1105 page was stored; empty when it has neither.""" 

1106 for key in ("published", "fetched_at"): 

1107 value = str(payload.get(key) or "").strip() 

1108 if value: 

1109 return value[:10] 

1110 return "" 

1111 

1112 

1113def _format_search_results( 

1114 results: list, 

1115 span, 

1116 *, 

1117 dated: bool = False, 

1118 hits: list[tuple[str, int]] | None = None, 

1119) -> str: 

1120 if dated: 

1121 # Newest first, the undated last (ISO dates sort as text). 

1122 results = sorted( 

1123 results, key=lambda r: _result_date(r.payload or {}) or "", reverse=True 

1124 ) 

1125 if not results: 

1126 if span.is_recording(): 

1127 span.set_attribute("rag.result_count", 0) 

1128 return NO_RESULTS 

1129 

1130 # Within a run each passage is labelled with its source's id 

1131 # (``util/source_registry``), the one the answer cites; outside one, by 

1132 # its place in the list. The trailer names each source with its id. 

1133 registry = source_registry.current() 

1134 sources: list[Any] = [] 

1135 named: set[str] = set() 

1136 parts: list[str] = [] 

1137 for i, r in enumerate(results, 1): 

1138 payload = r.payload or {} 

1139 # Its links' words, not their addresses (``knowledge.passage_text``). 

1140 text = passage_text.readable(str(payload.get("text", "")).strip()) 

1141 if not text: 

1142 continue 

1143 if hits is not None: 

1144 chunk = payload.get("chunk_index") 

1145 hits.append( 

1146 ( 

1147 str(payload.get("document_id") or ""), 

1148 int(chunk) if isinstance(chunk, int) else -1, 

1149 ) 

1150 ) 

1151 source = _extract_source(payload) 

1152 page = payload.get("page_number") 

1153 url = str(payload.get("url") or "") 

1154 

1155 label = f"[{i}]" 

1156 sid = "" 

1157 if registry is not None: 

1158 sid = registry.cite( 

1159 { 

1160 "tool": "search_knowledge", 

1161 "source": url or source, 

1162 "url": url or None, 

1163 "title": str(payload.get("page_title") or "") or source, 

1164 "document_id": str(payload.get("document_id") or ""), 

1165 "page_number": page, 

1166 } 

1167 ) 

1168 label = f"[{sid}]" 

1169 if source: 

1170 label += f" {source}" 

1171 if source not in named: 

1172 named.add(source) 

1173 sources.append( 

1174 {"source": source, "citation_id": sid} if sid else source 

1175 ) 

1176 if page is not None: 

1177 label += f" p.{page}" 

1178 if dated: 

1179 when = _result_date(payload) 

1180 if payload.get("published"): 

1181 label += f" · published {when}" 

1182 elif when: 

1183 label += f" · as of {when}" 

1184 else: 

1185 label += " · date unknown" 

1186 label += f" ({r.label})" 

1187 

1188 parts.append(f"{label}\n{text}") 

1189 

1190 if not parts: 

1191 if span.is_recording(): 

1192 span.set_attribute("rag.result_count", 0) 

1193 return "No relevant results found." 

1194 

1195 if span.is_recording(): 

1196 span.set_attribute("rag.result_count", len(parts)) 

1197 span.set_attribute("rag.unique_sources", len(named)) 

1198 

1199 return append_sources(RESULT_SEPARATOR.join(parts), sources) 

1200 

1201 

1202#: What separates one result from the next in a search's text. 

1203RESULT_SEPARATOR = "\n\n---\n\n" 

1204 

1205 

1206def result_count(text: str) -> int: 

1207 """How many results a search's text holds (its sources trailer split 

1208 off first, ``split_sources``): each opens with its label, ``[1]`` or 

1209 ``[S3]``. A message saying there were none counts none.""" 

1210 return sum( 

1211 1 for part in str(text or "").split(RESULT_SEPARATOR) if part.startswith("[") 

1212 )