Coverage for app / knowledge / retrieval.py: 96%

984 statements  

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

1""" 

2Context-rich retrieval pipeline for svc-ai. 

3 

4Turns a user query plus the knowledge bases granted to an agent into a 

5structured, citation-ready ``RetrievalBundle``. The pipeline is deterministic 

6apart from two optional LLM stages (query planning and reranking) that are 

7skipped gracefully when no LLM is available. 

8 

9Stages 

10------ 

111. Query planning — ``QueryPlanner`` expands the question into rephrasings, 

12 sub-questions and keyword variants (+ entity hints). 

132. Graph retrieval — ``GraphKBRetriever`` finds matching entities in every 

14 graph KB and walks their neighbourhood into ``GraphFact``s. 

15 Entity names found here seed extra *lexical* vector 

16 queries so documents mentioning them are surfaced too. 

173. Vector retrieval — ``VectorKBRetriever`` runs dense + lexical search for 

18 every query against every vector KB and fuses the legs 

19 with reciprocal-rank fusion (``rag_service.hybrid_hits``). 

204. Reranking — ``Reranker`` (LLM listwise) rescores the fused 

21 candidates against the original question. 

225. Neighbour — adjacent chunks of each selected passage are fetched 

23 expansion and merged into a coherent window (``expand_neighbours``). 

246. Packing — ``ContextPacker`` enforces per-document / per-KB caps 

25 and the token budget, assigns stable ``[S#]`` citation 

26 ids and renders the LLM-facing Markdown block. 

27 

28Every stage is a strategy object so deployments can swap implementations 

29(e.g. a cross-encoder reranker) without touching the orchestration in 

30``RetrievalPipeline.run``. 

31""" 

32 

33from __future__ import annotations 

34 

35import asyncio 

36import logging 

37import re 

38import time 

39from abc import ABC, abstractmethod 

40from dataclasses import asdict, dataclass, field 

41from collections.abc import Mapping, Sequence 

42from datetime import date 

43from itertools import combinations 

44from typing import Any, Iterable 

45 

46from pydantic import Field, OnErrorOmit, field_validator 

47 

48from app.util import source_registry 

49from app.util.knowledge_categories import KnowledgeCategory 

50from app.knowledge import categories 

51from app.knowledge import documents as documents_service 

52from app.knowledge import mix, passage_text 

53from app.knowledge.categories import RetrievalTurn 

54from app.knowledge.documents import DocumentRef 

55from app.models.spec import ( 

56 GraphFact, 

57 RetrievalBundle, 

58 RetrievalConfig, 

59 RetrievedPassage, 

60) 

61from app.services import model_errors 

62from app.services import rag as rag_service 

63from app.services.structured_output import ModelOutput, structured_call 

64 

65logger = logging.getLogger(__name__) 

66 

67_MAX_GRAPH_FACTS = 60 

68_MAX_ENTITY_SEEDS = 6 

69_MAX_GRAPH_TERMS = 12 

70_RERANK_SNIPPET_CHARS = 600 

71# Score bonus applied after reranking so passages from an explicitly named 

72# document always rank ahead of unscoped hits (rerank scores are ≤ 1.0 and 

73# fused RRF scores ≪ 1.0, so +1.0 is a strict precedence, not a nudge). 

74_TARGET_BOOST = 1.0 

75_FULL_DOCUMENT_SCORE = 2.0 

76 

77_WHOLE_DOCUMENT_RE = re.compile( 

78 r"\b(summar(y|ise|ize|ies)|overview|outline|tl;?dr|key\s+(points|takeaways|findings)|" 

79 r"what\s+(is|does)\s+(in|it|this|the\s+(document|file|report|paper))|" 

80 r"contents?\s+of|walk\s+me\s+through|read\s+(me\s+)?(the|this)|" 

81 r"explain\s+(the|this)\s+(document|file|report|paper)|" 

82 r"(describe|review|analy[sz]e)\s+(the|this)\s+(document|file|report|paper)|" 

83 r"main\s+(points|ideas|arguments)|executive\s+summary|translate|rewrite)\b", 

84 re.IGNORECASE, 

85) 

86 

87 

88def approx_tokens(text: str) -> int: 

89 """Cheap token estimate (≈4 chars/token) used for context budgeting.""" 

90 return max(1, len(text) // 4) 

91 

92 

93def _kb_field(kb: dict[str, Any], key: str, default: Any) -> Any: 

94 """Per-KB override from ``KnowledgeBaseSpec.config`` with a fallback.""" 

95 cfg = kb.get("config") or {} 

96 value = cfg.get(key) 

97 return default if value is None else value 

98 

99 

100@dataclass 

101class StageReport: 

102 """How one model-backed stage (the query planner, the relevance judge) 

103 went, for the trace: ``failure`` is one line when it failed and the 

104 pipeline went on without it, empty otherwise. A stage's return type is 

105 the stage's own (``QueryPlan`` is a model-facing schema), so the report 

106 travels beside it.""" 

107 

108 failure: str = "" 

109 

110 

111# ═════════════════════════════════════════════════════════════════════════════ 

112# Query planning 

113# ═════════════════════════════════════════════════════════════════════════════ 

114 

115 

116class QueryPlan(ModelOutput): 

117 """Structured output of the query-planning stage.""" 

118 

119 queries: list[str] = Field( 

120 default_factory=list, 

121 description=( 

122 "Alternative search queries — as many as the request allows: " 

123 "rephrasings of the question, decompositions into sub-questions, and " 

124 "short keyword-style variants. Do not repeat the original question." 

125 ), 

126 ) 

127 entity_hints: list[str] = Field( 

128 default_factory=list, 

129 description=( 

130 "Named entities, product names, identifiers, dates or exact terms " 

131 "that should be matched literally in documents." 

132 ), 

133 ) 

134 

135 

136# ── A query set per lane ──────────────────────────────────────────────────── 

137# When a turn's mix runs several lanes (``knowledge.mix``), one planner call 

138# writes each lane its own queries: reference material is searched for what 

139# the request asks, dated material for what changed, frameworks for a method 

140# that applies. One schema per set of kinds that run, built from one mixin a 

141# kind, so the model is never asked for a lane that will not run. A turn of 

142# one lane plans on ``QueryPlan``, as one search always did. 

143 

144_ENTITY_HINTS_DESCRIPTION = QueryPlan.model_fields["entity_hints"].description 

145 

146 

147class _EntityHints(ModelOutput): 

148 entity_hints: list[str] = Field( 

149 default_factory=list, description=_ENTITY_HINTS_DESCRIPTION 

150 ) 

151 

152 

153class _ReferenceQueries(ModelOutput): 

154 reference_queries: list[str] = Field( 

155 default_factory=list, 

156 description=categories.REGISTRY[KnowledgeCategory.domain].query_note, 

157 ) 

158 

159 

160class _DatedQueries(ModelOutput): 

161 dated_queries: list[str] = Field( 

162 default_factory=list, 

163 description=categories.REGISTRY[KnowledgeCategory.temporal].query_note, 

164 ) 

165 

166 

167class _MethodQueries(ModelOutput): 

168 method_queries: list[str] = Field( 

169 default_factory=list, 

170 description=categories.REGISTRY[KnowledgeCategory.reasoning].query_note, 

171 ) 

172 

173 

174class ReferenceDatedQueryPlan(_ReferenceQueries, _DatedQueries, _EntityHints): 

175 """Search queries for reference material and for dated material.""" 

176 

177 

178class ReferenceMethodQueryPlan(_ReferenceQueries, _MethodQueries, _EntityHints): 

179 """Search queries for reference material and for a method to apply.""" 

180 

181 

182class DatedMethodQueryPlan(_DatedQueries, _MethodQueries, _EntityHints): 

183 """Search queries for dated material and for a method to apply.""" 

184 

185 

186class LaneQueryPlan(_ReferenceQueries, _DatedQueries, _MethodQueries, _EntityHints): 

187 """Search queries for reference material, for dated material and for a 

188 method to apply.""" 

189 

190 

191#: Each kind's field in a lane plan. 

192LANE_QUERY_FIELDS: dict[KnowledgeCategory, str] = { 

193 KnowledgeCategory.domain: "reference_queries", 

194 KnowledgeCategory.temporal: "dated_queries", 

195 KnowledgeCategory.reasoning: "method_queries", 

196} 

197 

198_LANE_PLANS: dict[frozenset[KnowledgeCategory], type[ModelOutput]] = { 

199 frozenset({KnowledgeCategory.domain, KnowledgeCategory.temporal}): ( 

200 ReferenceDatedQueryPlan 

201 ), 

202 frozenset({KnowledgeCategory.domain, KnowledgeCategory.reasoning}): ( 

203 ReferenceMethodQueryPlan 

204 ), 

205 frozenset({KnowledgeCategory.temporal, KnowledgeCategory.reasoning}): ( 

206 DatedMethodQueryPlan 

207 ), 

208 frozenset(KnowledgeCategory): LaneQueryPlan, 

209} 

210 

211if set(LANE_QUERY_FIELDS) != set(KnowledgeCategory): 

212 raise RuntimeError("Every kind of knowledge needs its field in a lane plan") 

213for _kinds, _schema in _LANE_PLANS.items(): 

214 if set(_schema.model_fields) != {LANE_QUERY_FIELDS[k] for k in _kinds} | { 

215 "entity_hints" 

216 }: 

217 raise RuntimeError( 

218 f"{_schema.__name__} must ask for exactly its kinds' queries" 

219 ) 

220if {k for k in _LANE_PLANS if len(k) > 1} != { 

221 frozenset(c) 

222 for n in range(2, len(KnowledgeCategory) + 1) 

223 for c in combinations(KnowledgeCategory, n) 

224}: 

225 raise RuntimeError("Every set of two or more kinds needs a lane plan") 

226 

227 

228def lane_plan_schema(kinds: Iterable[KnowledgeCategory]) -> type[ModelOutput]: 

229 """The schema a turn's planner fills for the kinds its lanes search: 

230 ``QueryPlan`` for one, else the lane plan asking for exactly theirs.""" 

231 chosen = frozenset(kinds) 

232 return QueryPlan if len(chosen) < 2 else _LANE_PLANS[chosen] 

233 

234 

235@dataclass 

236class LaneQueries: 

237 """A planner's queries for each lane, by kind (alternatives, the original 

238 question not among them), and the terms every lane matches literally.""" 

239 

240 queries: dict[KnowledgeCategory, list[str]] 

241 entity_hints: list[str] 

242 

243 

244class QueryPlanner(ABC): 

245 """Strategy: expand the user question into a set of retrieval queries.""" 

246 

247 @abstractmethod 

248 async def plan( 

249 self, 

250 query: str, 

251 kb_metadata: str, 

252 cfg: RetrievalConfig, 

253 *, 

254 report: StageReport | None = None, 

255 ) -> QueryPlan: 

256 """The plan. A planner that fails and falls back says why in 

257 ``report.failure``.""" 

258 

259 async def plan_lanes( 

260 self, 

261 query: str, 

262 kb_metadata: str, 

263 cfg: RetrievalConfig, 

264 lanes: Mapping[KnowledgeCategory, int], 

265 *, 

266 report: StageReport | None = None, 

267 ) -> LaneQueries: 

268 """Queries for each lane (``lanes``: each kind that runs, and how 

269 many queries it runs). By default one plan, shared by every lane.""" 

270 plan = await self.plan(query, kb_metadata, cfg, report=report) 

271 return LaneQueries( 

272 queries={kind: list(plan.queries) for kind in lanes}, 

273 entity_hints=list(plan.entity_hints), 

274 ) 

275 

276 

277class PassthroughQueryPlanner(QueryPlanner): 

278 """No LLM: the original question plus its salient keywords as hints.""" 

279 

280 async def plan( 

281 self, 

282 query: str, 

283 kb_metadata: str, 

284 cfg: RetrievalConfig, 

285 *, 

286 report: StageReport | None = None, 

287 ) -> QueryPlan: 

288 return QueryPlan( 

289 queries=[], entity_hints=rag_service.extract_keywords(query, 5) 

290 ) 

291 

292 

293_PLANNER_SYSTEM = ( 

294 "You are a retrieval query planner for a knowledge-base search system. " 

295 "Given a user question (and, when available, a summary of what the knowledge " 

296 "bases contain), produce alternative search queries that maximise recall: " 

297 "rephrase the question, split it into independent sub-questions, and add a " 

298 "compact keyword-only variant. Also list exact entities/identifiers worth " 

299 "matching literally. Keep every query self-contained and specific. Leave " 

300 "dates, years and periods ('this month', 'recent', 'October 2026') out of " 

301 "the queries: how recent the results are is applied apart, and a date in " 

302 "a query matches dated text such as amendment notes rather than the " 

303 "subject. Name a year only when the question names that year." 

304) 

305 

306 

307def _planner_request(query: str, kb_metadata: str) -> str: 

308 """The planner's user message: today's date, the question and what the 

309 knowledge holds. Dated, so "this month" is never read as a month of its 

310 own — the planner wrote "June 2024" for it (scenario run 7) — and in the 

311 user message, so the system prompt stays the same every day.""" 

312 from app.prompts import today 

313 

314 user = f"Today: {today()}\n\nQuestion:\n{query}" 

315 if kb_metadata: 

316 user += f"\n\nAvailable knowledge (summary):\n{kb_metadata[:3000]}" 

317 return user 

318 

319 

320#: Added for a turn whose lanes each get their own queries. 

321_LANE_PLANNER_SYSTEM = ( 

322 "The knowledge is searched by kind, each kind with its own queries: write " 

323 "each field's queries for what that kind holds, as its description says, " 

324 "so a search of one kind finds what it can answer. The literal terms are " 

325 "shared by every search." 

326) 

327 

328 

329class LLMQueryPlanner(QueryPlanner): 

330 """Multi-query expansion via the system LLM's structured output.""" 

331 

332 def __init__(self, llm: Any) -> None: 

333 self._llm = llm 

334 self._fallback = PassthroughQueryPlanner() 

335 

336 async def plan( 

337 self, 

338 query: str, 

339 kb_metadata: str, 

340 cfg: RetrievalConfig, 

341 *, 

342 report: StageReport | None = None, 

343 ) -> QueryPlan: 

344 from langchain_core.messages import HumanMessage, SystemMessage 

345 

346 user = _planner_request(query, kb_metadata) 

347 user += f"\n\nReturn at most {max(cfg.max_queries - 1, 1)} alternative queries." 

348 try: 

349 outcome = await structured_call( 

350 self._llm, 

351 QueryPlan, 

352 [SystemMessage(content=_PLANNER_SYSTEM), HumanMessage(content=user)], 

353 purpose="retrieval.query_planner", 

354 ) 

355 result = outcome.unwrap() 

356 fallback = await self._fallback.plan(query, kb_metadata, cfg) 

357 hints = list(result.entity_hints) 

358 for h in fallback.entity_hints: 

359 if h.lower() not in {x.lower() for x in hints}: 

360 hints.append(h) 

361 return QueryPlan(queries=result.queries, entity_hints=hints) 

362 except Exception as exc: # noqa: BLE001 — even a fatal one: see LLMReranker 

363 failure = model_errors.describe(exc) 

364 logger.warning("LLMQueryPlanner failed, using passthrough: %s", failure) 

365 if report is not None: 

366 report.failure = failure 

367 return await self._fallback.plan(query, kb_metadata, cfg) 

368 

369 async def plan_lanes( 

370 self, 

371 query: str, 

372 kb_metadata: str, 

373 cfg: RetrievalConfig, 

374 lanes: Mapping[KnowledgeCategory, int], 

375 *, 

376 report: StageReport | None = None, 

377 ) -> LaneQueries: 

378 """One call for every lane, on the schema for the kinds that run 

379 (``lane_plan_schema``), each lane's field capped at its own count. A 

380 single lane plans as one search always did. A call that fails leaves 

381 every lane its original question, and says why in ``report``.""" 

382 from langchain_core.messages import HumanMessage, SystemMessage 

383 

384 if len(lanes) < 2: 

385 return await super().plan_lanes( 

386 query, kb_metadata, cfg, lanes, report=report 

387 ) 

388 schema = lane_plan_schema(lanes) 

389 user = _planner_request(query, kb_metadata) 

390 user += ( 

391 "\n\nReturn at most " 

392 + "; ".join( 

393 f"{max(count - 1, 1)} in {LANE_QUERY_FIELDS[kind]}" 

394 for kind, count in lanes.items() 

395 ) 

396 + "." 

397 ) 

398 try: 

399 outcome = await structured_call( 

400 self._llm, 

401 schema, 

402 [ 

403 SystemMessage( 

404 content=f"{_PLANNER_SYSTEM}\n\n{_LANE_PLANNER_SYSTEM}" 

405 ), 

406 HumanMessage(content=user), 

407 ], 

408 purpose="retrieval.query_planner", 

409 ) 

410 result = outcome.unwrap() 

411 fallback = await self._fallback.plan(query, kb_metadata, cfg) 

412 hints = list(getattr(result, "entity_hints", [])) 

413 for h in fallback.entity_hints: 

414 if h.lower() not in {x.lower() for x in hints}: 

415 hints.append(h) 

416 return LaneQueries( 

417 queries={ 

418 kind: list(getattr(result, LANE_QUERY_FIELDS[kind], []) or []) 

419 for kind in lanes 

420 }, 

421 entity_hints=hints, 

422 ) 

423 except Exception as exc: # noqa: BLE001 — even a fatal one: see LLMReranker 

424 failure = model_errors.describe(exc) 

425 logger.warning("LLMQueryPlanner failed, using passthrough: %s", failure) 

426 if report is not None: 

427 report.failure = failure 

428 fallback = await self._fallback.plan(query, kb_metadata, cfg) 

429 return LaneQueries( 

430 queries={kind: [] for kind in lanes}, 

431 entity_hints=list(fallback.entity_hints), 

432 ) 

433 

434 

435def build_query_set( 

436 query: str, plan: QueryPlan, cfg: RetrievalConfig, *, limit: int | None = None 

437) -> list[str]: 

438 """Original question first, then deduplicated variants, capped at 

439 ``limit`` (a lane's own count), else ``max_queries``.""" 

440 cap = limit or cfg.max_queries 

441 out: list[str] = [] 

442 seen: set[str] = set() 

443 for q in [query, *plan.queries]: 

444 q = (q or "").strip() 

445 key = " ".join(q.lower().split()) 

446 if not q or key in seen: 

447 continue 

448 seen.add(key) 

449 out.append(q) 

450 if len(out) >= cap: 

451 break 

452 return out or [query] 

453 

454 

455# ═════════════════════════════════════════════════════════════════════════════ 

456# Reranking 

457# ═════════════════════════════════════════════════════════════════════════════ 

458 

459 

460class RerankScore(ModelOutput): 

461 index: int = Field(description="Index of the passage in the candidate list") 

462 relevance: float = Field( 

463 ge=0.0, le=1.0, description="0 = irrelevant … 1 = directly answers the question" 

464 ) 

465 

466 @field_validator("relevance", mode="before") 

467 @classmethod 

468 def _clamp(cls, v: Any) -> Any: 

469 """One score outside 0–1 (a 0–10 scale, a 1.2) used to fail every 

470 score in the result; out-of-range values are read on the asked scale.""" 

471 if isinstance(v, (int, float)) and not isinstance(v, bool): 

472 if 1 < v <= 10: 

473 v = v / 10 

474 return min(1.0, max(0.0, float(v))) 

475 return v 

476 

477 

478class RerankResult(ModelOutput): 

479 # OnErrorOmit: one malformed score is dropped, not every score. 

480 # Required: the scores are the judge's decision. With a default, a reply 

481 # that held none — one complete score salvaged from inside a cut-off 

482 # list — read as a judge that had judged nothing, and the relevance 

483 # gate let every passage through. 

484 scores: list[OnErrorOmit[RerankScore]] = Field( 

485 description="A score for every numbered passage, by its index" 

486 ) 

487 

488 

489class Reranker(ABC): 

490 """Strategy: rescore fused candidates against the original question.""" 

491 

492 @abstractmethod 

493 async def rerank( 

494 self, 

495 query: str, 

496 passages: list[RetrievedPassage], 

497 cfg: RetrievalConfig, 

498 *, 

499 knowledge: str = "", 

500 report: StageReport | None = None, 

501 ) -> list[RetrievedPassage]: 

502 """The passages, best first. ``knowledge`` says what was searched 

503 (``_knowledge_brief``); a judge that fails says why in 

504 ``report.failure`` and leaves every passage unjudged.""" 

505 

506 

507class NoopReranker(Reranker): 

508 async def rerank( 

509 self, 

510 query: str, 

511 passages: list[RetrievedPassage], 

512 cfg: RetrievalConfig, 

513 *, 

514 knowledge: str = "", 

515 report: StageReport | None = None, 

516 ) -> list[RetrievedPassage]: 

517 return sorted(passages, key=lambda p: p.score, reverse=True) 

518 

519 

520_RERANK_SYSTEM = ( 

521 "You are a relevance judge for a retrieval system. For each numbered passage, " 

522 "rate how useful it is for answering the question as the person means it: " 

523 "1.0 = directly answers or contains the key fact, 0.5 = background that " 

524 "helps answer it, 0.0 = unrelated. A passage that only shares a word or a " 

525 "topic name with the question is unrelated — documentation of a feature " 

526 "called the same thing as the subject of the question, a definition of a " 

527 "term the question uses in passing — unless the question is about that " 

528 "feature or term. You are told which knowledge bases were searched and " 

529 "what each is for: judge a passage against that purpose, so a question " 

530 "about something outside it is not answered by a passage that documents a " 

531 "page or feature named like its subject. What the person wants the answer " 

532 "made into — a PDF, a document, a chart — is not its subject: for 'a PDF " 

533 "of climbing knots', a passage on making PDFs is unrelated. Judge only on " 

534 "content; ignore passage order and length. Return a score for every passage." 

535) 

536 

537#: How much of a knowledge base's description the judge is shown. 

538_KB_BRIEF_CHARS = 300 

539 

540 

541def _knowledge_brief(knowledge_bases: list[dict[str, Any]]) -> str: 

542 """What was searched, for the relevance judge: each knowledge base's 

543 name and what it is for, from its own description. Empty with none. 

544 

545 The judge used to see only the question and the passages, so nothing 

546 told it that CHAINR Bot's user guide is product documentation: it rated 

547 the guide's page on the built-in News repository 1.0 for "whats in the 

548 news". 

549 """ 

550 lines: list[str] = [] 

551 for kb in knowledge_bases: 

552 name = " ".join(str(kb.get("name") or kb.get("id") or "").split()) 

553 if not name: 

554 continue 

555 description = " ".join(str(kb.get("description") or "").split()) 

556 description = description[:_KB_BRIEF_CHARS] 

557 line = f"- {name}: {description}" if description else f"- {name}" 

558 # What its kind means for a rating (a framework is rated for whether 

559 # its method applies); domain adds nothing. 

560 note = categories.behaviour(kb).judge_note 

561 lines.append(f"{line} ({note})" if note else line) 

562 return "Knowledge bases searched:\n" + "\n".join(lines) if lines else "" 

563 

564 

565def _normalise(values: list[float]) -> list[float]: 

566 if not values: 

567 return [] 

568 lo, hi = min(values), max(values) 

569 if hi - lo < 1e-9: 

570 return [1.0 for _ in values] 

571 return [(v - lo) / (hi - lo) for v in values] 

572 

573 

574class LLMReranker(Reranker): 

575 """Listwise LLM reranker: final = 0.7·LLM relevance + 0.3·normalised fused.""" 

576 

577 def __init__(self, llm: Any) -> None: 

578 self._llm = llm 

579 

580 async def rerank( 

581 self, 

582 query: str, 

583 passages: list[RetrievedPassage], 

584 cfg: RetrievalConfig, 

585 *, 

586 knowledge: str = "", 

587 report: StageReport | None = None, 

588 ) -> list[RetrievedPassage]: 

589 """Judge the head. A judge that raised, or answered without a 

590 valid score for any passage, is a failure: the fused order comes back 

591 with every relevance None (so the relevance gate keeps every passage 

592 and the evidence says each is unjudged) and ``report`` says why.""" 

593 from langchain_core.messages import HumanMessage, SystemMessage 

594 

595 # Even a lone passage is judged: unjudged, it passed the relevance 

596 # gate whatever it said. 

597 if not passages: 

598 return [] 

599 

600 ranked = sorted(passages, key=lambda p: p.score, reverse=True) 

601 head = ranked[: cfg.rerank_candidates] 

602 tail = ranked[cfg.rerank_candidates :] 

603 fused_norm = _normalise([p.score for p in head]) 

604 

605 listing = "\n\n".join( 

606 f"[{i}] ({p.source or p.kb_name})\n{p.text[:_RERANK_SNIPPET_CHARS]}" 

607 for i, p in enumerate(head) 

608 ) 

609 searched = f"{knowledge}\n\n" if knowledge else "" 

610 prompt = f"Question:\n{query}\n\n{searched}Passages:\n{listing}" 

611 try: 

612 outcome = await structured_call( 

613 self._llm, 

614 RerankResult, 

615 [SystemMessage(content=_RERANK_SYSTEM), HumanMessage(content=prompt)], 

616 purpose="retrieval.reranker", 

617 ) 

618 result = outcome.unwrap() 

619 except Exception as exc: # noqa: BLE001 

620 # Degrade even on a fatal provider error: retrieval may run 

621 # without a chat model behind it (the knowledge search endpoint), 

622 # and in a turn the gate has already reported one. 

623 return self._unjudged(ranked, model_errors.describe(exc), report) 

624 

625 llm_scores: dict[int, float] = { 

626 s.index: s.relevance for s in result.scores if 0 <= s.index < len(head) 

627 } 

628 if not llm_scores: 

629 # Nothing to apply: blending no ratings would only lower every 

630 # score, and the gate would read the turn as judged. 

631 return self._unjudged( 

632 ranked, "the judge rated none of the passages", report 

633 ) 

634 rescored: list[RetrievedPassage] = [] 

635 for i, p in enumerate(head): 

636 rel = llm_scores.get(i) 

637 final = ( 

638 0.7 * rel + 0.3 * fused_norm[i] 

639 if rel is not None 

640 else 0.3 * fused_norm[i] 

641 ) 

642 # The verdict travels with the passage, for the relevance gate 

643 # (``relevance_gate``); a passage the judge skipped has none. 

644 rescored.append(p.model_copy(update={"score": final, "relevance": rel})) 

645 rescored.sort(key=lambda p: p.score, reverse=True) 

646 # Un-judged tail keeps its (lower) fused ordering behind the judged head. 

647 return rescored + [p.model_copy(update={"score": 0.0}) for p in tail] 

648 

649 @staticmethod 

650 def _unjudged( 

651 ranked: list[RetrievedPassage], failure: str, report: StageReport | None 

652 ) -> list[RetrievedPassage]: 

653 """The fused order, unjudged, with the judge's failure reported.""" 

654 logger.warning("LLMReranker failed, keeping fused order: %s", failure) 

655 if report is not None: 

656 report.failure = failure 

657 return ranked 

658 

659 

660def relevance_gate( 

661 passages: list[RetrievedPassage], cfg: RetrievalConfig 

662) -> tuple[list[RetrievedPassage], int]: 

663 """``(the passages the relevance judge kept, how many it ruled out)``. 

664 

665 Applies only when a judge ran (some passage carries a ``relevance``): 

666 without one there is no verdict to apply. A passage it rated below 

667 ``cfg.min_relevance`` goes, and so does one it never saw (the tail 

668 behind its head, ranked lower still). A passage from a document the 

669 request names stays whatever it was rated: the person asked for it. 

670 

671 Before this, the judge's rating only reordered passages, blended 70/30 

672 with their search rank: the top search hit for "what is in the news" 

673 — the user guide's page on the built-in News repository — kept 0.3 of 

674 a score with a rating of 0, and was packed, cited and shown as a source. 

675 """ 

676 if cfg.min_relevance <= 0 or not any(p.relevance is not None for p in passages): 

677 return passages, 0 

678 kept = [ 

679 p 

680 for p in passages 

681 if p.targeted or (p.relevance is not None and p.relevance >= cfg.min_relevance) 

682 ] 

683 return kept, len(passages) - len(kept) 

684 

685 

686# ═════════════════════════════════════════════════════════════════════════════ 

687# Retrievers 

688# ═════════════════════════════════════════════════════════════════════════════ 

689 

690 

691def _standard_floor(cfg: RetrievalConfig) -> float: 

692 """The pipeline's similarity floor: the config's own, or the embedding 

693 model's ``standard`` one.""" 

694 if cfg.score_threshold is not None: 

695 return cfg.score_threshold 

696 from app.services import embeddings 

697 

698 return embeddings.active().floors.standard 

699 

700 

701class VectorKBRetriever: 

702 """Hybrid (dense + lexical, RRF-fused) retrieval against one vector KB.""" 

703 

704 async def retrieve( 

705 self, 

706 kb: dict[str, Any], 

707 queries: list[str], 

708 lexical_terms: list[str], 

709 cfg: RetrievalConfig, 

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

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

712 ) -> list[RetrievedPassage]: 

713 """Hybrid search of *kb*. A semantic leg that could not run is said 

714 in *failures* (the keyword leg may still have answered).""" 

715 kb_id = str(kb.get("id", "")) 

716 kb_name = str(kb.get("name", kb_id)) 

717 hits = await rag_service.hybrid_hits( 

718 kb_id, 

719 queries, 

720 candidate_k=cfg.candidate_k, 

721 # A document-scoped search is a precision query: no similarity floor, 

722 # the user asked for this document so its best chunks always count. 

723 score_threshold=None if document_ids else _standard_floor(cfg), 

724 lexical=cfg.lexical, 

725 rrf_k=cfg.rrf_k, 

726 lexical_only_queries=lexical_terms if cfg.lexical else None, 

727 document_ids=document_ids, 

728 failures=failures, 

729 ) 

730 passages: list[RetrievedPassage] = [] 

731 for h in hits[: cfg.rerank_candidates]: 

732 payload = h.payload 

733 ci = payload.get("chunk_index") 

734 passages.append( 

735 RetrievedPassage( 

736 kb_id=kb_id, 

737 kb_name=kb_name, 

738 document_id=str(payload.get("document_id") or ""), 

739 source=h.source, 

740 folder_path=str(payload.get("folder_path") or ""), 

741 page_number=payload.get("page_number"), 

742 chunk_index=int(ci) if ci is not None else None, 

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

744 text=passage_text.readable(h.text), 

745 score=float(payload.get("_fused_score", 0.0)), 

746 dense_score=h.dense_score, 

747 lexical_hit=h.lexical_score is not None, 

748 matched_queries=list(h.matched_queries), 

749 targeted=bool(document_ids), 

750 url=str(payload.get("url") or ""), 

751 page_title=str(payload.get("page_title") or ""), 

752 fetched_at=str(payload.get("fetched_at") or ""), 

753 links=_link_list(payload.get("links"), "text"), 

754 via=_link_list(payload.get("via"), "title"), 

755 published=str(payload.get("published") or ""), 

756 author=str(payload.get("author") or ""), 

757 attribution=str(payload.get("attribution") or ""), 

758 licence_url=str(payload.get("licence_url") or ""), 

759 ) 

760 ) 

761 return passages 

762 

763 

764def _link_list(raw: Any, label: str) -> list[dict[str, str]]: 

765 """A payload's ``links`` / ``via`` as clean ``{url, <label>}`` dicts.""" 

766 out: list[dict[str, str]] = [] 

767 for item in raw or []: 

768 if isinstance(item, dict) and str(item.get("url") or "").startswith( 

769 ("http://", "https://") 

770 ): 

771 out.append({"url": str(item["url"]), label: str(item.get(label) or "")}) 

772 return out 

773 

774 

775class GraphKBRetriever: 

776 """Entity search + neighbourhood walk against one Neo4j graph KB.""" 

777 

778 async def retrieve( 

779 self, 

780 kb: dict[str, Any], 

781 queries: list[str], 

782 entity_hints: list[str], 

783 cfg: RetrievalConfig, 

784 ) -> list[GraphFact]: 

785 from app.util import neo4j_client 

786 

787 kb_id = str(kb.get("id", "")) 

788 kb_name = str(kb.get("name", kb_id)) 

789 depth = int(_kb_field(kb, "depth", cfg.graph_depth)) 

790 limit = cfg.graph_entity_limit 

791 

792 # Search with salient terms only: entity hints first (exact names the 

793 # planner extracted), then content keywords of the queries. Raw 

794 # questions would match on stop-words such as "who" or "the". 

795 terms: list[str] = [] 

796 seen_terms: set[str] = set() 

797 for t in [ 

798 *entity_hints, 

799 *(k for q in queries for k in rag_service.extract_keywords(q)), 

800 ]: 

801 key = t.lower().strip() 

802 if key and key not in seen_terms: 

803 seen_terms.add(key) 

804 terms.append(t) 

805 if len(terms) >= _MAX_GRAPH_TERMS: 

806 break 

807 

808 entities: dict[str, dict[str, Any]] = {} 

809 exact_hits: set[str] = set() 

810 for term in terms: 

811 try: 

812 found = await neo4j_client.text_search_entities( 

813 kb_id, term, limit=limit 

814 ) 

815 except Exception as exc: 

816 logger.warning("graph entity search failed kb=%s: %s", kb_id, exc) 

817 break 

818 for e in found: 

819 key = str(e.get("id") or e.get("name")) 

820 entities.setdefault(key, e) 

821 name = str(e.get("name") or "").lower() 

822 label = str(e.get("label") or "").lower() 

823 if name == term.lower() or label == term.lower(): 

824 exact_hits.add(key) 

825 

826 # Exact name / label matches are expanded first so the entity cap never 

827 # drops the very entity the user asked about. 

828 ordered = sorted( 

829 entities.items(), key=lambda kv: (kv[0] not in exact_hits, kv[0]) 

830 ) 

831 

832 facts: list[GraphFact] = [] 

833 seen: set[tuple[str, str, str]] = set() 

834 for _key, ent in ordered[:limit]: 

835 name = str(ent.get("name") or "") 

836 if not name: 

837 continue 

838 props = dict(ent.get("properties") or {}) 

839 try: 

840 rels = await neo4j_client.find_neighbors(kb_id, name, depth=depth) 

841 except Exception as exc: 

842 logger.warning("graph neighbour walk failed kb=%s: %s", kb_id, exc) 

843 rels = [] 

844 if not rels or props: 

845 # Property fact: carries the entity's attributes (dates, roles, 

846 # contact details…) which relationships alone would omit. 

847 facts.append( 

848 GraphFact( 

849 kb_id=kb_id, 

850 kb_name=kb_name, 

851 from_name=name, 

852 from_label=str(ent.get("label") or ""), 

853 properties=props, 

854 ) 

855 ) 

856 for r in rels: 

857 key = (r["from_name"], r["relationship"], r["to_name"]) 

858 if key in seen: 

859 continue 

860 seen.add(key) 

861 facts.append( 

862 GraphFact( 

863 kb_id=kb_id, 

864 kb_name=kb_name, 

865 from_name=r["from_name"], 

866 from_label=r.get("from_label", ""), 

867 relationship=r["relationship"], 

868 to_name=r["to_name"], 

869 to_label=r.get("to_label", ""), 

870 ) 

871 ) 

872 if len(facts) >= _MAX_GRAPH_FACTS: 

873 return facts 

874 return facts 

875 

876 

877# ═════════════════════════════════════════════════════════════════════════════ 

878# Document targeting 

879# ═════════════════════════════════════════════════════════════════════════════ 

880 

881 

882#: How much of the query the evidence header repeats. It repeated it whole, 

883#: and a request that carried a 12,000-token document carried it three times 

884#: more into every answering call (24 October 2026). 

885ECHO_QUERY_CHARS = 300 

886ECHO_SEARCH_CHARS = 200 

887ECHO_SEARCHES = 6 

888 

889 

890def _echo(text: str, limit: int) -> str: 

891 text = " ".join((text or "").split()) 

892 return text if len(text) <= limit else text[: limit - 1].rstrip() + "…" 

893 

894 

895class DocumentTargeter: 

896 """Detects documents the user named and fetches their text when asked for 

897 the whole document.""" 

898 

899 async def detect( 

900 self, 

901 query: str, 

902 entity_hints: list[str], 

903 vector_kbs: list[dict[str, Any]], 

904 cfg: RetrievalConfig, 

905 attached: Sequence[str] = (), 

906 attached_mentions: Sequence[str] = (), 

907 ) -> tuple[dict[str, list[DocumentRef]], list[str]]: 

908 """Return ``{kb_id: [DocumentRef, …]}`` of named documents per KB plus 

909 filename-like mentions that resolved to nothing. A document the 

910 conversation attached (``attached``) is neither: it is not knowledge, 

911 and it was "NOT FOUND" in the knowledge that a report the person had 

912 attached was said to be missing (24 October 2026).""" 

913 exclude = documents_service.attached_refs(attached) 

914 targets: dict[str, list[DocumentRef]] = {} 

915 unresolved: list[str] = [] 

916 total = 0 

917 text = " ".join([query, *entity_hints]) 

918 for kb in vector_kbs: 

919 kb_id = str(kb.get("id", "")) 

920 try: 

921 docs = await documents_service.list_documents( 

922 kb_id, manifest=kb.get("documents") 

923 ) 

924 except Exception as exc: 

925 logger.warning( 

926 "document targeting: listing failed kb=%s: %s", kb_id, exc 

927 ) 

928 continue 

929 found, missing = documents_service.find_mentioned_documents( 

930 text, docs, exclude=exclude, elsewhere=attached_mentions 

931 ) 

932 for m in missing: 

933 if m not in unresolved: 

934 unresolved.append(m) 

935 if found: 

936 room = cfg.max_targeted_documents - total 

937 if room <= 0: 

938 break 

939 targets[kb_id] = found[:room] 

940 total += len(targets[kb_id]) 

941 # A mention is only truly unresolved if no KB could resolve it. 

942 resolved_names = { 

943 documents_service.name_key(d.display_name, drop_ext=True) 

944 for docs in targets.values() 

945 for d in docs 

946 } 

947 unresolved = [ 

948 m 

949 for m in unresolved 

950 if documents_service.name_key(m, drop_ext=True) not in resolved_names 

951 ] 

952 return targets, unresolved 

953 

954 @staticmethod 

955 def wants_whole_document(query: str, targets: dict[str, list[DocumentRef]]) -> bool: 

956 """True when the request is about a document as a whole rather than a 

957 fact inside it — e.g. "summarise report.pdf" or just the filename.""" 

958 if not targets: 

959 return False 

960 if _WHOLE_DOCUMENT_RE.search(query): 

961 return True 

962 # Query that is (almost) only the document name → show the document. 

963 stripped = documents_service.name_key(query) 

964 for docs in targets.values(): 

965 for d in docs: 

966 key = documents_service.name_key(d.display_name, drop_ext=True) 

967 if key in stripped and len(stripped.split()) <= len(key.split()) + 3: 

968 return True 

969 return False 

970 

971 async def full_text_passages( 

972 self, 

973 kb_lookup: dict[str, dict[str, Any]], 

974 targets: dict[str, list[DocumentRef]], 

975 cfg: RetrievalConfig, 

976 ) -> list[RetrievedPassage]: 

977 """One ``full_document`` passage per target, sized to the budget share.""" 

978 n_docs = sum(len(v) for v in targets.values()) or 1 

979 per_doc_chars = int( 

980 cfg.max_context_tokens * cfg.full_document_share * 4 / n_docs 

981 ) 

982 out: list[RetrievedPassage] = [] 

983 for kb_id, docs in targets.items(): 

984 kb_name = str(kb_lookup.get(kb_id, {}).get("name", kb_id)) 

985 for ref in docs: 

986 try: 

987 doc = await documents_service.get_document_text( 

988 kb_id, ref, max_chars=per_doc_chars 

989 ) 

990 except Exception as exc: 

991 logger.warning( 

992 "full document fetch failed %s: %s", ref.display_name, exc 

993 ) 

994 continue 

995 if not doc.text: 

996 continue 

997 out.append( 

998 RetrievedPassage( 

999 kb_id=kb_id, 

1000 kb_name=kb_name, 

1001 document_id=ref.document_id, 

1002 source=ref.display_name, 

1003 folder_path=ref.folder_path, 

1004 chunk_span=(0, max(doc.chunk_count - 1, 0)) 

1005 if doc.chunk_count 

1006 else None, 

1007 text=doc.text, 

1008 score=_FULL_DOCUMENT_SCORE, 

1009 matched_queries=[], 

1010 targeted=True, 

1011 full_document=True, 

1012 ) 

1013 ) 

1014 return out 

1015 

1016 

1017# ═════════════════════════════════════════════════════════════════════════════ 

1018# Evidence already cited 

1019# ═════════════════════════════════════════════════════════════════════════════ 

1020 

1021#: A passage already in a turn's evidence: its knowledge base, its document 

1022#: and the chunks its text holds, ``(first, last)``. 

1023CitedSpan = tuple[str, str, tuple[int, int]] 

1024 

1025 

1026def cited_spans(citations: Iterable[dict[str, Any]]) -> list[CitedSpan]: 

1027 """The chunks a turn's retrieval citations already hold: one span for 

1028 each passage with a knowledge base, a document and its chunk range 

1029 (``chunk_span``; a citation from before that was recorded gives its own 

1030 chunk). Graph facts and passages without chunk provenance hold none.""" 

1031 out: list[CitedSpan] = [] 

1032 for c in citations or []: 

1033 kb_id = str(c.get("kb_id") or "") 

1034 document_id = str(c.get("document_id") or "") 

1035 span, index = c.get("chunk_span"), c.get("chunk_index") 

1036 if not kb_id or not document_id: 

1037 continue 

1038 try: 

1039 if span is not None and len(span) == 2: 

1040 lo, hi = int(span[0]), int(span[1]) 

1041 elif index is not None: 

1042 lo = hi = int(index) 

1043 else: 

1044 continue 

1045 except (TypeError, ValueError): 

1046 continue 

1047 out.append((kb_id, document_id, (min(lo, hi), max(lo, hi)))) 

1048 return out 

1049 

1050 

1051class CitedChunks: 

1052 """The chunks already in the evidence, by document: what a corrective 

1053 pass must not pack again. Packed again, a passage the agent was handed 

1054 and the evaluator found wanting came back under a new ``[S#]`` id as if 

1055 it were new evidence for the gap.""" 

1056 

1057 def __init__(self, spans: Iterable[CitedSpan] = ()) -> None: 

1058 self._spans: dict[tuple[str, str], list[tuple[int, int]]] = {} 

1059 for kb_id, document_id, (lo, hi) in spans: 

1060 self._spans.setdefault((kb_id, document_id), []).append( 

1061 (min(lo, hi), max(lo, hi)) 

1062 ) 

1063 

1064 def __bool__(self) -> bool: 

1065 return bool(self._spans) 

1066 

1067 def _of(self, p: RetrievedPassage) -> list[tuple[int, int]]: 

1068 return self._spans.get((p.kb_id, p.document_id), []) if p.document_id else [] 

1069 

1070 def holds(self, p: RetrievedPassage) -> bool: 

1071 """True when any of ``p``'s text is cited already: its chunk, or the 

1072 window or whole document it spans.""" 

1073 if p.chunk_span is not None: 

1074 lo, hi = p.chunk_span 

1075 elif p.chunk_index is not None: 

1076 lo = hi = p.chunk_index 

1077 else: 

1078 return False 

1079 return any(lo <= b and a <= hi for a, b in self._of(p)) 

1080 

1081 def window(self, p: RetrievedPassage, lo: int, hi: int) -> tuple[int, int] | None: 

1082 """``lo``–``hi``, the window around ``p``'s chunk, narrowed so it 

1083 stops short of every cited range on either side; None when ``p``'s 

1084 own chunk is cited.""" 

1085 centre = p.chunk_index or 0 

1086 for a, b in self._of(p): 

1087 if a <= centre <= b: 

1088 return None 

1089 if b < centre: 

1090 lo = max(lo, b + 1) 

1091 else: 

1092 hi = min(hi, a - 1) 

1093 return lo, hi 

1094 

1095 

1096# ═════════════════════════════════════════════════════════════════════════════ 

1097# Neighbour expansion 

1098# ═════════════════════════════════════════════════════════════════════════════ 

1099 

1100 

1101def _merge_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]: 

1102 """Merge overlapping/adjacent inclusive integer spans.""" 

1103 merged: list[tuple[int, int]] = [] 

1104 for lo, hi in sorted(spans): 

1105 if merged and lo <= merged[-1][1] + 1: 

1106 merged[-1] = (merged[-1][0], max(merged[-1][1], hi)) 

1107 else: 

1108 merged.append((lo, hi)) 

1109 return merged 

1110 

1111 

1112async def expand_neighbours( 

1113 passages: list[RetrievedPassage], 

1114 window: int, 

1115 cited: CitedChunks | None = None, 

1116) -> list[RetrievedPassage]: 

1117 """Widen each passage to ±``window`` adjacent chunks of the same document. 

1118 

1119 Passages of one document whose windows touch are merged into a single 

1120 passage spanning the union, keeping the best score and the union of 

1121 matched queries. Passages without chunk provenance pass through unchanged. 

1122 

1123 ``cited``: chunks already in the evidence. A window stops short of them, 

1124 so a neighbour of a cited passage does not widen back over its text; a 

1125 passage whose own chunk is cited is dropped. 

1126 """ 

1127 if window <= 0: 

1128 return passages 

1129 

1130 groups: dict[tuple[str, str], list[RetrievedPassage]] = {} 

1131 passthrough: list[RetrievedPassage] = [] 

1132 for p in passages: 

1133 if p.document_id and p.chunk_index is not None: 

1134 groups.setdefault((p.kb_id, p.document_id), []).append(p) 

1135 else: 

1136 passthrough.append(p) 

1137 

1138 def _window(p: RetrievedPassage) -> tuple[int, int] | None: 

1139 centre = p.chunk_index or 0 

1140 lo, hi = max(0, centre - window), centre + window 

1141 return cited.window(p, lo, hi) if cited else (lo, hi) 

1142 

1143 async def _expand_group( 

1144 key: tuple[str, str], members: list[RetrievedPassage] 

1145 ) -> list[RetrievedPassage]: 

1146 kb_id, document_id = key 

1147 clipped = [(p, _window(p)) for p in members] 

1148 members = [p for p, w in clipped if w is not None] 

1149 # Windows clipped short of a cited range never touch across it, so 

1150 # merging them cannot either. 

1151 spans = _merge_spans([w for _, w in clipped if w is not None]) 

1152 out: list[RetrievedPassage] = [] 

1153 for lo, hi in spans: 

1154 span_members = [p for p in members if lo <= (p.chunk_index or 0) <= hi] 

1155 best = max(span_members, key=lambda p: p.score) 

1156 payloads = await rag_service.fetch_window(kb_id, document_id, lo, hi) 

1157 if payloads: 

1158 # Joined as stored, then read: a link cut at a chunk's end 

1159 # would stop its overlap with the next from matching. 

1160 text = passage_text.readable( 

1161 documents_service.join_chunks( 

1162 [str(pl.get("text", "")) for pl in payloads], 

1163 [pl.get("chunk_index") for pl in payloads], 

1164 ) 

1165 ) 

1166 lo_actual = int(payloads[0].get("chunk_index") or lo) 

1167 hi_actual = int(payloads[-1].get("chunk_index") or hi) 

1168 page = payloads[0].get("page_number", best.page_number) 

1169 else: 

1170 # Neighbour fetch unavailable — fall back to the members' own text. 

1171 ordered = sorted(span_members, key=lambda p: p.chunk_index or 0) 

1172 text = documents_service.join_chunks( 

1173 [p.text for p in ordered], [p.chunk_index for p in ordered] 

1174 ) 

1175 lo_actual = ordered[0].chunk_index or lo 

1176 hi_actual = ordered[-1].chunk_index or hi 

1177 page = ordered[0].page_number 

1178 queries: list[str] = [] 

1179 for p in span_members: 

1180 for q in p.matched_queries: 

1181 if q not in queries: 

1182 queries.append(q) 

1183 # The merged window's links are every chunk's in it — the window 

1184 # text now holds them all, and a deep citation must be able to 

1185 # resolve any of them. 

1186 links: list[dict[str, str]] = [] 

1187 for source in [*(payloads or []), *span_members]: 

1188 raw = source.get("links") if isinstance(source, dict) else source.links 

1189 for link in _link_list(raw, "text"): 

1190 if all(existing["url"] != link["url"] for existing in links): 

1191 links.append(link) 

1192 out.append( 

1193 best.model_copy( 

1194 update={ 

1195 "text": text or best.text, 

1196 "chunk_span": (lo_actual, hi_actual), 

1197 "page_number": page, 

1198 "matched_queries": queries, 

1199 "lexical_hit": any(p.lexical_hit for p in span_members), 

1200 "links": links, 

1201 } 

1202 ) 

1203 ) 

1204 return out 

1205 

1206 expanded_groups = await asyncio.gather( 

1207 *(_expand_group(k, m) for k, m in groups.items()) 

1208 ) 

1209 expanded = [p for grp in expanded_groups for p in grp] + passthrough 

1210 expanded.sort(key=lambda p: p.score, reverse=True) 

1211 return expanded 

1212 

1213 

1214# ═════════════════════════════════════════════════════════════════════════════ 

1215# Packing + rendering 

1216# ═════════════════════════════════════════════════════════════════════════════ 

1217 

1218 

1219def _relevance_phrase(passage: RetrievedPassage, judge_failed: bool) -> str: 

1220 """How an evidence header states a passage's relevance: the judge's own 

1221 rating; "unjudged" when the judge failed for the run; otherwise nothing. 

1222 

1223 The score shown used to be the blend the passages were ordered by, which 

1224 read as a rating whether or not a judge ran. A passage without a rating 

1225 on a run whose judge worked was not the judge's to rate — the document 

1226 the person named, added whole after it — or no judge ran (``rerank`` 

1227 off). Calling it "unjudged" told the model that the one document the 

1228 person asked for had not been checked, under the note for evidence that 

1229 had been. A document the person named is in the evidence whatever it 

1230 would be rated, so it is never called unjudged. 

1231 """ 

1232 if passage.relevance is not None: 

1233 return f" — relevance {passage.relevance:.2f}" 

1234 if judge_failed and not (passage.targeted or passage.full_document): 

1235 return " — relevance unjudged" 

1236 return "" 

1237 

1238 

1239def _per_kb(items: Iterable[Any]) -> dict[str, int]: 

1240 """How many of ``items`` (passages or graph facts) each knowledge base 

1241 gave, by its id.""" 

1242 counts: dict[str, int] = {} 

1243 for item in items: 

1244 counts[item.kb_id] = counts.get(item.kb_id, 0) + 1 

1245 return counts 

1246 

1247 

1248def _search_cfg(kb: dict[str, Any], cfg: RetrievalConfig) -> RetrievalConfig: 

1249 """The config a search of ``kb`` runs on: more candidates for a kind that 

1250 asks for them (dated knowledge, whose window and recency leave some 

1251 out); ``cfg`` itself otherwise.""" 

1252 factor = categories.behaviour(kb).candidate_factor 

1253 if factor == 1: 

1254 return cfg 

1255 return cfg.model_copy(update={"candidate_k": cfg.candidate_k * factor}) 

1256 

1257 

1258def _by_category( 

1259 passages: list[RetrievedPassage], 

1260 knowledge_bases: list[dict[str, Any]], 

1261 turn: RetrievalTurn, 

1262 on: date, 

1263) -> tuple[list[RetrievedPassage], dict[str, int]]: 

1264 """Each knowledge base's passages after its kind's own reading 

1265 (``Behaviour.adjust``), best first, and how many each left out, by its 

1266 id. Passages of a kind that reads them as they are come back untouched, 

1267 in order.""" 

1268 kbs = {str(kb.get("id", "")): kb for kb in knowledge_bases} 

1269 by_kb: dict[str, list[RetrievedPassage]] = {} 

1270 for p in passages: 

1271 by_kb.setdefault(p.kb_id, []).append(p) 

1272 adjusted: dict[str, list[RetrievedPassage]] = {} 

1273 left_out: dict[str, int] = {} 

1274 for kb_id, own in by_kb.items(): 

1275 kb = kbs.get(kb_id, {}) 

1276 kept, dropped = categories.behaviour(kb).adjust(own, kb, turn, on) 

1277 adjusted[kb_id] = kept 

1278 if dropped: 

1279 left_out[kb_id] = dropped 

1280 if all(adjusted[k] is by_kb[k] for k in by_kb): 

1281 return passages, {} 

1282 out = [p for kb_id in by_kb for p in adjusted[kb_id]] 

1283 out.sort(key=lambda p: p.score, reverse=True) 

1284 return out, left_out 

1285 

1286 

1287def _passage_lines( 

1288 p: RetrievedPassage, judge_failed: bool, *, dated: bool = False 

1289) -> list[str]: 

1290 """One passage as the evidence shows it: its header (id, source, where, 

1291 dates, knowledge base, rating), where it was found, and its text. 

1292 ``dated``: from temporal knowledge, so one with no date says so.""" 

1293 out: list[str] = [] 

1294 loc: list[str] = [] 

1295 if p.page_number is not None: 

1296 loc.append(f"p.{p.page_number}") 

1297 if p.chunk_span and p.chunk_span[0] != p.chunk_span[1]: 

1298 loc.append(f"chunks {p.chunk_span[0]}–{p.chunk_span[1]}") 

1299 elif p.chunk_index is not None: 

1300 loc.append(f"chunk {p.chunk_index}") 

1301 where = f" ({', '.join(loc)})" if loc else "" 

1302 folder = f" · {p.folder_path}/" if p.folder_path else "" 

1303 if p.published: 

1304 # News: when it was published is what dates the claim — 

1305 # "yesterday's announcement" is only answerable with it. 

1306 folder += f" · published {p.published[:10]}" 

1307 if p.fetched_at: 

1308 # A page snapshot, not a document: say how old it is so 

1309 # the answer can be as careful as the evidence is fresh. 

1310 folder += f" · page as of {p.fetched_at[:10]}" 

1311 if dated and not (p.published or p.fetched_at): 

1312 folder += " · date unknown" 

1313 tag = ( 

1314 " · FULL DOCUMENT" 

1315 if p.full_document 

1316 else (" · requested document" if p.targeted else "") 

1317 ) 

1318 out.append( 

1319 f"#### [{p.citation_id}] {p.source or 'untitled'}{where}" 

1320 f"{folder} — KB: {p.kb_name}{tag}" 

1321 f"{_relevance_phrase(p, judge_failed)}" 

1322 ) 

1323 if p.via: 

1324 # A page read because another page linked to it: say where 

1325 # it was found, so a citation can show the whole chain. 

1326 out.append( 

1327 "Linked from: " 

1328 + "; ".join(f"[{v.get('title') or v['url']}]({v['url']})" for v in p.via) 

1329 ) 

1330 out.append(p.text) 

1331 out.append("") 

1332 return out 

1333 

1334 

1335@dataclass 

1336class _Taken: 

1337 """What packing has taken so far, shared by every lane one pack packs: 

1338 no document past its cap, no knowledge base past its own, no text twice 

1339 — whichever lane found it.""" 

1340 

1341 per_doc: dict[str, int] = field(default_factory=dict) 

1342 per_kb: dict[str, int] = field(default_factory=dict) 

1343 seen_text: set[str] = field(default_factory=set) 

1344 full_docs: set[str] = field(default_factory=set) 

1345 #: The passages taken, by identity, so a second round over a lane's 

1346 #: candidates (budget it inherits) does not take one twice. 

1347 ids: set[int] = field(default_factory=set) 

1348 

1349 

1350@dataclass 

1351class LanePacking: 

1352 """How one lane's evidence fared in packing: its share of the budget, 

1353 what it used, how many passages it packed, and the budget other lanes 

1354 left unused that it took up (``spilled_in``).""" 

1355 

1356 category: str 

1357 role: str 

1358 budget: int 

1359 used: int = 0 

1360 packed: int = 0 

1361 spilled_in: int = 0 

1362 

1363 def wire(self) -> dict[str, Any]: 

1364 return { 

1365 "role": self.role, 

1366 "budget": self.budget, 

1367 "used": self.used, 

1368 "packed": self.packed, 

1369 "spilled_in": self.spilled_in, 

1370 } 

1371 

1372 

1373class ContextPacker: 

1374 """Select passages/facts within budget, assign citation ids, render Markdown.""" 

1375 

1376 def select( 

1377 self, 

1378 passages: list[RetrievedPassage], 

1379 facts: list[GraphFact], 

1380 cfg: RetrievalConfig, 

1381 kb_top_k: dict[str, int] | None = None, 

1382 citation_offset: int = 0, 

1383 ) -> tuple[list[RetrievedPassage], list[GraphFact]]: 

1384 fact_budget, passage_budget = self._budgets(facts, cfg) 

1385 chosen, _ = self._choose(passages, passage_budget, cfg, kb_top_k, _Taken()) 

1386 chosen_facts = self._choose_facts(facts, fact_budget) 

1387 self._cite(chosen, chosen_facts, citation_offset) 

1388 return chosen, chosen_facts 

1389 

1390 def select_lanes( 

1391 self, 

1392 lanes: Sequence[tuple[LanePacking, float, list[RetrievedPassage]]], 

1393 facts: list[GraphFact], 

1394 cfg: RetrievalConfig, 

1395 kb_top_k: dict[str, int] | None = None, 

1396 citation_offset: int = 0, 

1397 ) -> tuple[list[RetrievedPassage], list[GraphFact]]: 

1398 """:meth:`select` over evidence from several lanes, each given its 

1399 share of the budget (``(packing, weight, passages)``, the leading 

1400 lane first). What a lane leaves unused goes to the lanes in order, 

1401 the leading one first; caps and duplicates are counted across every 

1402 lane. Each lane's ``packing`` records how it fared. Cited lane by 

1403 lane, then the graph facts.""" 

1404 fact_budget, passage_budget = self._budgets(facts, cfg) 

1405 taken = _Taken() 

1406 total = sum(weight for _, weight, _ in lanes) or 1.0 

1407 chosen_by_lane: list[list[RetrievedPassage]] = [] 

1408 left = passage_budget 

1409 for packing, weight, passages in lanes: 

1410 packing.budget = int(passage_budget * weight / total) 

1411 chosen, used = self._choose(passages, packing.budget, cfg, kb_top_k, taken) 

1412 packing.used, packing.packed = used, len(chosen) 

1413 chosen_by_lane.append(chosen) 

1414 left -= used 

1415 for (packing, _, passages), chosen in zip(lanes, chosen_by_lane): 

1416 if left <= 0: 

1417 break 

1418 more, used = self._choose( 

1419 passages, left, cfg, kb_top_k, taken, keep_one=False 

1420 ) 

1421 chosen.extend(more) 

1422 packing.used += used 

1423 packing.packed += len(more) 

1424 packing.spilled_in = used 

1425 left -= used 

1426 chosen = [p for lane in chosen_by_lane for p in lane] 

1427 chosen_facts = self._choose_facts(facts, fact_budget) 

1428 self._cite(chosen, chosen_facts, citation_offset) 

1429 return chosen, chosen_facts 

1430 

1431 @staticmethod 

1432 def _budgets(facts: list[GraphFact], cfg: RetrievalConfig) -> tuple[int, int]: 

1433 """``(the graph facts' budget, the passages')``: the facts take at 

1434 most a fifth.""" 

1435 budget = cfg.max_context_tokens 

1436 fact_budget = min( 

1437 int(budget * 0.2), sum(approx_tokens(f.as_text()) for f in facts) 

1438 ) 

1439 return fact_budget, budget - fact_budget 

1440 

1441 @staticmethod 

1442 def _choose( 

1443 passages: list[RetrievedPassage], 

1444 budget: int, 

1445 cfg: RetrievalConfig, 

1446 kb_top_k: dict[str, int] | None, 

1447 taken: _Taken, 

1448 *, 

1449 keep_one: bool = True, 

1450 ) -> tuple[list[RetrievedPassage], int]: 

1451 """``(the passages chosen, best first, the tokens they use)`` within 

1452 ``budget``, under the caps ``taken`` counts. ``keep_one``: with 

1453 nothing chosen, the best passage is kept, truncated to the budget.""" 

1454 chosen: list[RetrievedPassage] = [] 

1455 used = 0 

1456 for p in sorted(passages, key=lambda x: x.score, reverse=True): 

1457 if id(p) in taken.ids: 

1458 continue 

1459 original = p 

1460 doc_key = f"{p.kb_id}:{p.document_id or p.source}" 

1461 kb_cap = (kb_top_k or {}).get(p.kb_id, cfg.top_k) 

1462 if doc_key in taken.full_docs: 

1463 continue # whole document already included — chunks are redundant 

1464 if taken.per_doc.get(doc_key, 0) >= cfg.max_passages_per_document: 

1465 continue 

1466 # Passages from a document the user named are never crowded out by 

1467 # the per-KB cap. 

1468 if taken.per_kb.get(p.kb_id, 0) >= kb_cap and not p.targeted: 

1469 continue 

1470 fingerprint = " ".join(p.text.lower().split())[:200] 

1471 if fingerprint in taken.seen_text: 

1472 continue 

1473 cost = approx_tokens(p.text) 

1474 if used + cost > budget: 

1475 if chosen or not keep_one: 

1476 continue 

1477 # Always keep at least one passage, truncated to the budget. 

1478 p = p.model_copy(update={"text": p.text[: budget * 4]}) 

1479 cost = approx_tokens(p.text) 

1480 chosen.append(p) 

1481 used += cost 

1482 taken.ids.add(id(original)) 

1483 taken.per_doc[doc_key] = taken.per_doc.get(doc_key, 0) + 1 

1484 taken.per_kb[p.kb_id] = taken.per_kb.get(p.kb_id, 0) + 1 

1485 taken.seen_text.add(fingerprint) 

1486 if p.full_document: 

1487 taken.full_docs.add(doc_key) 

1488 return chosen, used 

1489 

1490 @staticmethod 

1491 def _choose_facts(facts: list[GraphFact], fact_budget: int) -> list[GraphFact]: 

1492 chosen_facts: list[GraphFact] = [] 

1493 fused = 0 

1494 for f in facts: 

1495 cost = approx_tokens(f.as_text()) 

1496 if fused + cost > fact_budget and chosen_facts: 

1497 break 

1498 chosen_facts.append(f) 

1499 fused += cost 

1500 return chosen_facts 

1501 

1502 @staticmethod 

1503 def _cite( 

1504 chosen: list[RetrievedPassage], 

1505 chosen_facts: list[GraphFact], 

1506 citation_offset: int, 

1507 ) -> None: 

1508 # Within a run every source has one id, shared with what the run's 

1509 # tools show (``util/source_registry``): a document's passages, a 

1510 # page retrieved and also fetched, read as one source. Outside a run 

1511 # (a knowledge search on its own), passages are numbered from the 

1512 # offset. 

1513 registry = source_registry.current() 

1514 if registry is not None: 

1515 for p in chosen: 

1516 p.citation_id = registry.cite(p.citation()) 

1517 for f in chosen_facts: 

1518 f.citation_id = registry.cite(f.citation()) 

1519 return 

1520 n = citation_offset 

1521 for p in chosen: 

1522 n += 1 

1523 p.citation_id = f"S{n}" 

1524 for f in chosen_facts: 

1525 n += 1 

1526 f.citation_id = f"S{n}" 

1527 

1528 @staticmethod 

1529 def render( 

1530 query: str, 

1531 queries: list[str], 

1532 passages: list[RetrievedPassage], 

1533 facts: list[GraphFact], 

1534 skipped_kbs: list[str], 

1535 targeted_documents: list[dict[str, Any]] | None = None, 

1536 unresolved_mentions: list[str] | None = None, 

1537 *, 

1538 judge_failed: bool = False, 

1539 categories_by_kb: dict[str, KnowledgeCategory] | None = None, 

1540 on: date | None = None, 

1541 dated_first: bool = False, 

1542 ) -> str: 

1543 """The evidence as the answering model reads it. ``judge_failed``: 

1544 the relevance judge failed for this run, so a passage without its 

1545 rating is said to be unjudged. ``categories_by_kb`` names each 

1546 knowledge base's kind: a temporal one's passages follow the rest, 

1547 newest first under their dates (as of ``on``) — or come first, with 

1548 ``dated_first``, when the dated knowledge leads the turn.""" 

1549 if not passages and not facts and not unresolved_mentions: 

1550 return "" 

1551 lines: list[str] = [ 

1552 "## Retrieved Knowledge", 

1553 f'Retrieved for: "{_echo(query, ECHO_QUERY_CHARS)}"', 

1554 ] 

1555 if len(queries) > 1: 

1556 lines.append( 

1557 "Search queries used: " 

1558 + " | ".join( 

1559 _echo(q, ECHO_SEARCH_CHARS) for q in queries[:ECHO_SEARCHES] 

1560 ) 

1561 ) 

1562 lines.append( 

1563 "Cite the evidence you use inline by its id, e.g. [S1] — a " 

1564 "document's passages share one — and leave out any passage that " 

1565 "does not bear on the request. Never attribute to this evidence " 

1566 "anything it does not say." 

1567 ) 

1568 lines.append("") 

1569 

1570 if targeted_documents or unresolved_mentions: 

1571 lines.append("### Documents explicitly requested") 

1572 for t in targeted_documents or []: 

1573 cov = t.get("coverage", "none") 

1574 cov_text = { 

1575 "full": "full text included below", 

1576 "partial": "most relevant passages included below", 

1577 }.get(cov, "no matching content found in this document") 

1578 lines.append(f"- {t['name']} — KB: {t['kb_name']} — {cov_text}") 

1579 for m in unresolved_mentions or []: 

1580 lines.append( 

1581 f"- '{m}' — NOT FOUND in any attached knowledge base. Tell the user this " 

1582 "file is not available rather than inferring its contents." 

1583 ) 

1584 lines.append("") 

1585 

1586 kinds = categories_by_kb or {} 

1587 dated = [ 

1588 p for p in passages if kinds.get(p.kb_id) is KnowledgeCategory.temporal 

1589 ] 

1590 evidence = [ 

1591 p for p in passages if kinds.get(p.kb_id) is not KnowledgeCategory.temporal 

1592 ] 

1593 sections: list[list[str]] = [] 

1594 if evidence: 

1595 section = ["### Document evidence"] 

1596 for p in evidence: 

1597 section.extend(_passage_lines(p, judge_failed)) 

1598 sections.append(section) 

1599 if dated: 

1600 as_of = (on or categories.today()).isoformat() 

1601 section = [ 

1602 "### Dated evidence — newest first", 

1603 f"Time-sensitive knowledge, as of {as_of}. Prefer the newest, " 

1604 "and say how current the answer is; a passage whose date is " 

1605 "unknown may be out of date.", 

1606 "", 

1607 ] 

1608 undated = date.min 

1609 for p in sorted( 

1610 dated, key=lambda x: categories.passage_date(x) or undated, reverse=True 

1611 ): 

1612 section.extend(_passage_lines(p, judge_failed, dated=True)) 

1613 # The leading knowledge first: on a turn about what is current, 

1614 # the dated evidence comes before the reference material. 

1615 if dated_first: 

1616 sections.insert(0, section) 

1617 else: 

1618 sections.append(section) 

1619 for section in sections: 

1620 lines.extend(section) 

1621 

1622 if facts: 

1623 by_kb: dict[str, list[GraphFact]] = {} 

1624 for f in facts: 

1625 by_kb.setdefault(f.kb_name, []).append(f) 

1626 for kb_name, kb_facts in by_kb.items(): 

1627 lines.append(f"### Graph facts — KB: {kb_name}") 

1628 for f in kb_facts: 

1629 lines.append(f"- [{f.citation_id}] {f.as_text()}") 

1630 lines.append("") 

1631 

1632 if skipped_kbs: 

1633 lines.append("### Knowledge bases with no matching content") 

1634 for name in skipped_kbs: 

1635 lines.append(f"- {name}") 

1636 lines.append("") 

1637 

1638 return "\n".join(lines).rstrip() 

1639 

1640 @staticmethod 

1641 def render_frameworks( 

1642 passages: list[RetrievedPassage], *, judge_failed: bool = False 

1643 ) -> str: 

1644 """The frameworks (reasoning knowledge) packed apart, as the 

1645 answering node's ``<frameworks>`` holds them: a method to apply, 

1646 each cited by its id like the evidence. Empty with none.""" 

1647 if not passages: 

1648 return "" 

1649 lines = [ 

1650 "## Frameworks to apply", 

1651 "Methods from the agent's reasoning knowledge for approaching this " 

1652 "request. Apply the one that fits, say which you applied, and cite " 

1653 "it by its id, e.g. [S1]. They are not evidence for facts.", 

1654 "", 

1655 ] 

1656 for p in passages: 

1657 lines.extend(_passage_lines(p, judge_failed)) 

1658 return "\n".join(lines).rstrip() 

1659 

1660 

1661# ═════════════════════════════════════════════════════════════════════════════ 

1662# Pipeline 

1663# ═════════════════════════════════════════════════════════════════════════════ 

1664 

1665 

1666@dataclass 

1667class KnowledgePlan: 

1668 """What a turn looks for, decided once for every lane (stages 1 and 

1669 2b): the query set, the terms to match literally, and the documents the 

1670 request names — across every knowledge base, so a document is targeted 

1671 once and a name no knowledge base holds is reported once.""" 

1672 

1673 query: str 

1674 queries: list[str] 

1675 entity_hints: list[str] 

1676 targets: dict[str, list[DocumentRef]] = field(default_factory=dict) 

1677 unresolved: list[str] = field(default_factory=list) 

1678 whole_document: bool = False 

1679 planner_failure: str = "" 

1680 #: Targeting's failure, if any. 

1681 errors: list[str] = field(default_factory=list) 

1682 timings: dict[str, int] = field(default_factory=dict) 

1683 #: Each lane's own query set, by kind, when the turn's lanes were 

1684 #: planned apart (``plan(lanes=…)``); ``queries`` is then all of them. 

1685 #: Empty for one lane: it searches ``queries``. 

1686 lane_queries: dict[str, list[str]] = field(default_factory=dict) 

1687 

1688 def dump(self) -> dict[str, Any]: 

1689 """Plain values, for graph state and its checkpoints.""" 

1690 return { 

1691 "query": self.query, 

1692 "queries": list(self.queries), 

1693 "lane_queries": {k: list(v) for k, v in self.lane_queries.items()}, 

1694 "entity_hints": list(self.entity_hints), 

1695 "targets": { 

1696 kb_id: [asdict(ref) for ref in refs] 

1697 for kb_id, refs in self.targets.items() 

1698 }, 

1699 "unresolved": list(self.unresolved), 

1700 "whole_document": self.whole_document, 

1701 "planner_failure": self.planner_failure, 

1702 "errors": list(self.errors), 

1703 "timings": dict(self.timings), 

1704 } 

1705 

1706 @classmethod 

1707 def load(cls, raw: Any) -> KnowledgePlan | None: 

1708 """:meth:`dump` read back; None for anything else.""" 

1709 if not isinstance(raw, dict) or not isinstance(raw.get("query"), str): 

1710 return None 

1711 return cls( 

1712 query=raw["query"], 

1713 queries=[str(q) for q in raw.get("queries") or []], 

1714 entity_hints=[str(h) for h in raw.get("entity_hints") or []], 

1715 targets={ 

1716 str(kb_id): [DocumentRef(**ref) for ref in refs or []] 

1717 for kb_id, refs in (raw.get("targets") or {}).items() 

1718 }, 

1719 unresolved=[str(u) for u in raw.get("unresolved") or []], 

1720 whole_document=bool(raw.get("whole_document")), 

1721 planner_failure=str(raw.get("planner_failure") or ""), 

1722 errors=[str(e) for e in raw.get("errors") or []], 

1723 timings=dict(raw.get("timings") or {}), 

1724 lane_queries={ 

1725 str(kind): [str(q) for q in queries or []] 

1726 for kind, queries in (raw.get("lane_queries") or {}).items() 

1727 }, 

1728 ) 

1729 

1730 

1731@dataclass 

1732class LaneResult: 

1733 """What one lane's search gave (stages 2–5): its knowledge bases' 

1734 passages — judged, read for their kind, widened — and graph facts, with 

1735 the counts the turn's retrieval record keeps. A lane is a set of 

1736 knowledge bases searched and judged together. 

1737 

1738 ``category``, ``role`` and ``share`` are the turn's mix's 

1739 (``knowledge.mix``) when a graph run searched the lane; a lane ``run`` 

1740 searches has none, and packs as one lane always did.""" 

1741 

1742 kb_ids: list[str] 

1743 passages: list[RetrievedPassage] = field(default_factory=list) 

1744 facts: list[GraphFact] = field(default_factory=list) 

1745 #: Per knowledge base: what its search found, what the judge ruled 

1746 #: out, and what its kind's window left out. 

1747 found: dict[str, int] = field(default_factory=dict) 

1748 ruled_out: dict[str, int] = field(default_factory=dict) 

1749 windowed: dict[str, int] = field(default_factory=dict) 

1750 #: Passages the relevance judge was shown (none when no judge ran). 

1751 judged: int = 0 

1752 judged_out: int = 0 

1753 judge_failure: str = "" 

1754 degraded: list[str] = field(default_factory=list) 

1755 graph_errors: list[str] = field(default_factory=list) 

1756 vector_errors: list[str] = field(default_factory=list) 

1757 timings: dict[str, int] = field(default_factory=dict) 

1758 category: str = "" 

1759 role: str = "" 

1760 share: float = 1.0 

1761 #: The search itself failed (one line, ``model_errors.describe``): the 

1762 #: lane holds nothing, and the turn packs the other lanes. 

1763 failure: str = "" 

1764 

1765 def dump(self) -> dict[str, Any]: 

1766 """Plain values, for graph state and its checkpoints.""" 

1767 return { 

1768 "kb_ids": list(self.kb_ids), 

1769 "passages": [p.model_dump(mode="json") for p in self.passages], 

1770 "facts": [f.model_dump(mode="json") for f in self.facts], 

1771 "found": dict(self.found), 

1772 "ruled_out": dict(self.ruled_out), 

1773 "windowed": dict(self.windowed), 

1774 "judged": self.judged, 

1775 "judged_out": self.judged_out, 

1776 "judge_failure": self.judge_failure, 

1777 "degraded": list(self.degraded), 

1778 "graph_errors": list(self.graph_errors), 

1779 "vector_errors": list(self.vector_errors), 

1780 "timings": dict(self.timings), 

1781 "category": self.category, 

1782 "role": self.role, 

1783 "share": self.share, 

1784 "failure": self.failure, 

1785 } 

1786 

1787 @classmethod 

1788 def load(cls, raw: Any) -> LaneResult | None: 

1789 """:meth:`dump` read back; None for anything else.""" 

1790 if not isinstance(raw, dict) or not isinstance(raw.get("kb_ids"), list): 

1791 return None 

1792 return cls( 

1793 kb_ids=[str(k) for k in raw["kb_ids"]], 

1794 passages=[ 

1795 RetrievedPassage.model_validate(p) for p in raw.get("passages") or [] 

1796 ], 

1797 facts=[GraphFact.model_validate(f) for f in raw.get("facts") or []], 

1798 found=dict(raw.get("found") or {}), 

1799 ruled_out=dict(raw.get("ruled_out") or {}), 

1800 windowed=dict(raw.get("windowed") or {}), 

1801 judged=int(raw.get("judged") or 0), 

1802 judged_out=int(raw.get("judged_out") or 0), 

1803 judge_failure=str(raw.get("judge_failure") or ""), 

1804 degraded=[str(d) for d in raw.get("degraded") or []], 

1805 graph_errors=[str(e) for e in raw.get("graph_errors") or []], 

1806 vector_errors=[str(e) for e in raw.get("vector_errors") or []], 

1807 timings=dict(raw.get("timings") or {}), 

1808 category=str(raw.get("category") or ""), 

1809 role=str(raw.get("role") or ""), 

1810 share=float(raw.get("share", 1.0)), 

1811 failure=str(raw.get("failure") or ""), 

1812 ) 

1813 

1814 

1815def _evidence_lanes( 

1816 lanes: Sequence[LaneResult], evidence: list[RetrievedPassage] 

1817) -> list[tuple[LanePacking, float, list[RetrievedPassage]]]: 

1818 """The evidence lanes that pack apart, the leading one first: two or 

1819 more lanes in an evidence role (``mix.EVIDENCE_SHARES``), each with its 

1820 share and its own evidence passages. None for fewer: one lane packs as 

1821 one lane always did. A passage of a knowledge base no such lane holds 

1822 goes with the leading lane.""" 

1823 order = list(mix.EVIDENCE_SHARES) 

1824 evidence_lanes = sorted( 

1825 (lane for lane in lanes if lane.role in order), 

1826 key=lambda lane: order.index(lane.role), 

1827 ) 

1828 if len(evidence_lanes) < 2: 

1829 return [] 

1830 owner = {kb_id: i for i, lane in enumerate(evidence_lanes) for kb_id in lane.kb_ids} 

1831 own: list[list[RetrievedPassage]] = [[] for _ in evidence_lanes] 

1832 for p in evidence: 

1833 own[owner.get(p.kb_id, 0)].append(p) 

1834 return [ 

1835 (LanePacking(lane.category, lane.role, budget=0), lane.share, mine) 

1836 for lane, mine in zip(evidence_lanes, own) 

1837 ] 

1838 

1839 

1840def _lane_packing( 

1841 lanes: Sequence[LaneResult], 

1842 led: list[tuple[LanePacking, float, list[RetrievedPassage]]], 

1843 chosen: list[RetrievedPassage], 

1844 frameworks: list[RetrievedPassage], 

1845 reserved: dict[KnowledgeCategory, int], 

1846 granted: dict[KnowledgeCategory, int], 

1847 facts: list[GraphFact], 

1848 evidence_cfg: RetrievalConfig, 

1849) -> dict[str, dict[str, Any]]: 

1850 """How each of a turn's lanes fared in packing, by its kind (only lanes 

1851 a turn's mix named): its budget, the tokens it used, the passages it 

1852 packed and the budget it took over from the others. A kind packed apart 

1853 has its share as its budget, and what the evidence left it as 

1854 ``spilled_in``.""" 

1855 packing = {lp.category: lp.wire() for lp, _, _ in led} 

1856 _, passage_budget = ContextPacker._budgets(facts, evidence_cfg) 

1857 for lane in lanes: 

1858 if not lane.category or lane.category in packing: 

1859 continue 

1860 method = lane.role not in mix.EVIDENCE_SHARES 

1861 mine = [p for p in (frameworks if method else chosen) if p.kb_id in lane.kb_ids] 

1862 share = next((n for c, n in reserved.items() if c.value == lane.category), 0) 

1863 given = next((n for c, n in granted.items() if c.value == lane.category), 0) 

1864 used = sum(approx_tokens(p.text) for p in mine) 

1865 packing[lane.category] = LanePacking( 

1866 lane.category, 

1867 lane.role, 

1868 budget=share if method else passage_budget, 

1869 used=used, 

1870 packed=len(mine), 

1871 spilled_in=max(0, min(used, given) - share) if method else 0, 

1872 ).wire() 

1873 return packing 

1874 

1875 

1876class RetrievalPipeline: 

1877 """Orchestrates the retrieval stages into a ``RetrievalBundle``. 

1878 

1879 Three steps, which ``run`` composes over one lane holding every 

1880 knowledge base: :meth:`plan` (what to look for), :meth:`search` (one 

1881 lane's knowledge bases, searched and judged together) and :meth:`pack` 

1882 (the lanes' passages within one budget, rendered). 

1883 """ 

1884 

1885 def __init__( 

1886 self, 

1887 cfg: RetrievalConfig, 

1888 planner: QueryPlanner, 

1889 reranker: Reranker, 

1890 vector_retriever: VectorKBRetriever | None = None, 

1891 graph_retriever: GraphKBRetriever | None = None, 

1892 packer: ContextPacker | None = None, 

1893 targeter: DocumentTargeter | None = None, 

1894 ) -> None: 

1895 self.cfg = cfg 

1896 self.planner = planner 

1897 self.reranker = reranker 

1898 self.vector_retriever = vector_retriever or VectorKBRetriever() 

1899 self.graph_retriever = graph_retriever or GraphKBRetriever() 

1900 self.packer = packer or ContextPacker() 

1901 self.targeter = targeter or DocumentTargeter() 

1902 

1903 @classmethod 

1904 def from_config( 

1905 cls, cfg: RetrievalConfig, llm: Any = None, reranker_llm: Any = None 

1906 ) -> RetrievalPipeline: 

1907 """Factory: LLM-backed planner/reranker when an LLM is available and enabled. 

1908 

1909 ``reranker_llm`` judges relevance in place of ``llm`` — in a graph 

1910 run, the same model with more room to answer than the planner has 

1911 (``graph._retrieval_step_llm``). Without it ``llm`` does both. 

1912 """ 

1913 judge = reranker_llm if reranker_llm is not None else llm 

1914 planner: QueryPlanner = ( 

1915 LLMQueryPlanner(llm) 

1916 if (llm is not None and cfg.multi_query) 

1917 else PassthroughQueryPlanner() 

1918 ) 

1919 reranker: Reranker = ( 

1920 LLMReranker(judge) if (judge is not None and cfg.rerank) else NoopReranker() 

1921 ) 

1922 return cls(cfg, planner, reranker) 

1923 

1924 async def run( 

1925 self, 

1926 query: str, 

1927 knowledge_bases: list[dict[str, Any]], 

1928 kb_metadata: str = "", 

1929 citation_offset: int = 0, 

1930 exclude: Iterable[CitedSpan] = (), 

1931 attached: Sequence[str] = (), 

1932 attached_mentions: Sequence[str] = (), 

1933 turn: RetrievalTurn | None = None, 

1934 on: date | None = None, 

1935 ) -> RetrievalBundle: 

1936 """Run the pipeline: plan, one lane over every knowledge base, pack. 

1937 

1938 ``turn`` is what triage said that changes how each kind of knowledge 

1939 is read (``app/knowledge/categories.py``): a temporal base's window, 

1940 say. ``on`` is the day dated passages are aged against (today). 

1941 

1942 ``citation_offset`` starts ``[S#]`` numbering after ids already handed 

1943 out (corrective re-retrieval appends to an existing evidence block). 

1944 ``exclude`` names the chunks that block already holds 

1945 (``cited_spans``): none of them is packed again — not as a hit, not 

1946 inside a neighbour's expanded window, not in a whole document. 

1947 ``attached`` names the documents the conversation attached: a file 

1948 they name is not looked for in the knowledge, nor reported missing 

1949 from it; nor is one those documents mention (``attached_mentions``) 

1950 reported missing. 

1951 """ 

1952 if not knowledge_bases or not query.strip(): 

1953 return RetrievalBundle( 

1954 query=query, kb_ids=[str(kb.get("id", "")) for kb in knowledge_bases] 

1955 ) 

1956 on = on or categories.today() 

1957 plan = await self.plan( 

1958 query, 

1959 knowledge_bases, 

1960 kb_metadata, 

1961 attached=attached, 

1962 attached_mentions=attached_mentions, 

1963 ) 

1964 lane = await self.search( 

1965 plan, knowledge_bases, exclude=exclude, turn=turn, on=on 

1966 ) 

1967 return self.pack( 

1968 plan, [lane], knowledge_bases, citation_offset=citation_offset, on=on 

1969 ) 

1970 

1971 async def plan( 

1972 self, 

1973 query: str, 

1974 knowledge_bases: list[dict[str, Any]], 

1975 kb_metadata: str = "", 

1976 *, 

1977 attached: Sequence[str] = (), 

1978 attached_mentions: Sequence[str] = (), 

1979 lanes: Mapping[KnowledgeCategory, int] | None = None, 

1980 ) -> KnowledgePlan: 

1981 """Stages 1 and 2b: the query set, and the documents the request 

1982 names, across every knowledge base given. 

1983 

1984 ``lanes`` names the kinds a turn's lanes search, each with how many 

1985 queries it runs: with two or more, one planner call writes each its 

1986 own (``QueryPlanner.plan_lanes``), and ``queries`` is all of them. 

1987 One lane, or none named, plans one set as one search always did.""" 

1988 cfg = self.cfg 

1989 timings: dict[str, int] = {} 

1990 errors: list[str] = [] 

1991 

1992 # 1. Query planning 

1993 t = time.monotonic() 

1994 plan_report = StageReport() 

1995 lane_queries: dict[str, list[str]] = {} 

1996 if cfg.multi_query and lanes and len(lanes) > 1: 

1997 planned = await self.planner.plan_lanes( 

1998 query, kb_metadata, cfg, lanes, report=plan_report 

1999 ) 

2000 lane_queries = { 

2001 kind.value: build_query_set( 

2002 query, 

2003 QueryPlan(queries=planned.queries.get(kind, [])), 

2004 cfg, 

2005 limit=lanes[kind], 

2006 ) 

2007 for kind in lanes 

2008 } 

2009 queries = list( 

2010 dict.fromkeys(q for each in lane_queries.values() for q in each) 

2011 ) 

2012 plan = QueryPlan(queries=queries[1:], entity_hints=planned.entity_hints) 

2013 else: 

2014 plan = ( 

2015 await self.planner.plan(query, kb_metadata, cfg, report=plan_report) 

2016 if cfg.multi_query 

2017 else await PassthroughQueryPlanner().plan(query, kb_metadata, cfg) 

2018 ) 

2019 queries = build_query_set(query, plan, cfg) 

2020 timings["plan"] = int((time.monotonic() - t) * 1000) 

2021 

2022 # 2b. Document targeting — did the user name a stored file? It reads 

2023 # the plan's literal terms, never the graph's, so it runs here, once. 

2024 vector_kbs = [kb for kb in knowledge_bases if kb.get("source_type") != "graph"] 

2025 t = time.monotonic() 

2026 targets: dict[str, list[DocumentRef]] = {} 

2027 unresolved: list[str] = [] 

2028 if cfg.document_targeting and vector_kbs: 

2029 try: 

2030 targets, unresolved = await self.targeter.detect( 

2031 query, 

2032 plan.entity_hints, 

2033 vector_kbs, 

2034 cfg, 

2035 attached=attached, 

2036 attached_mentions=attached_mentions, 

2037 ) 

2038 except Exception as exc: 

2039 errors.append(f"targeting: {exc}") 

2040 timings["target"] = int((time.monotonic() - t) * 1000) 

2041 return KnowledgePlan( 

2042 query=query, 

2043 queries=queries, 

2044 entity_hints=list(plan.entity_hints), 

2045 targets=targets, 

2046 unresolved=unresolved, 

2047 whole_document=self.targeter.wants_whole_document(query, targets), 

2048 planner_failure=plan_report.failure, 

2049 errors=errors, 

2050 timings=timings, 

2051 lane_queries=lane_queries, 

2052 ) 

2053 

2054 async def search( 

2055 self, 

2056 plan: KnowledgePlan, 

2057 knowledge_bases: list[dict[str, Any]], 

2058 *, 

2059 exclude: Iterable[CitedSpan] = (), 

2060 turn: RetrievalTurn | None = None, 

2061 on: date | None = None, 

2062 cfg: RetrievalConfig | None = None, 

2063 ) -> LaneResult: 

2064 """Stages 2–5 for one lane: its knowledge bases searched for the 

2065 plan's queries, judged together, read for their kind, widened to 

2066 their neighbours. ``cfg`` is the lane's (its candidates and judge 

2067 slots); the pipeline's otherwise.""" 

2068 cfg = cfg or self.cfg 

2069 turn = turn or RetrievalTurn() 

2070 on = on or categories.today() 

2071 cited = CitedChunks(exclude) 

2072 queries = plan.queries 

2073 targets = plan.targets 

2074 lane = LaneResult(kb_ids=[str(kb.get("id", "")) for kb in knowledge_bases]) 

2075 timings = lane.timings 

2076 judge_report = StageReport() 

2077 

2078 vector_kbs = [kb for kb in knowledge_bases if kb.get("source_type") != "graph"] 

2079 graph_kbs = [kb for kb in knowledge_bases if kb.get("source_type") == "graph"] 

2080 

2081 # 2. Graph retrieval (first — entity names seed lexical vector queries) 

2082 t = time.monotonic() 

2083 facts: list[GraphFact] = [] 

2084 if graph_kbs: 

2085 graph_results = await asyncio.gather( 

2086 *( 

2087 self.graph_retriever.retrieve(kb, queries, plan.entity_hints, cfg) 

2088 for kb in graph_kbs 

2089 ), 

2090 return_exceptions=True, 

2091 ) 

2092 for kb, res in zip(graph_kbs, graph_results): 

2093 if isinstance(res, BaseException): 

2094 lane.graph_errors.append( 

2095 f"graph:{kb.get('name', kb.get('id'))}: {res}" 

2096 ) 

2097 continue 

2098 facts.extend(res) 

2099 timings["graph"] = int((time.monotonic() - t) * 1000) 

2100 

2101 lexical_terms = list(plan.entity_hints) 

2102 if cfg.graph_seeds_vector_queries: 

2103 for f in facts: 

2104 for name in (f.from_name, f.to_name): 

2105 if name and name.lower() not in {x.lower() for x in lexical_terms}: 

2106 lexical_terms.append(name) 

2107 if len(lexical_terms) >= len(plan.entity_hints) + _MAX_ENTITY_SEEDS: 

2108 break 

2109 if len(lexical_terms) >= len(plan.entity_hints) + _MAX_ENTITY_SEEDS: 

2110 break 

2111 

2112 # 3. Vector retrieval (unscoped for every KB + scoped to named documents) 

2113 t = time.monotonic() 

2114 passages: list[RetrievedPassage] = [] 

2115 degraded = lane.degraded 

2116 if vector_kbs: 

2117 jobs: list[tuple[dict[str, Any], Any]] = [ 

2118 ( 

2119 kb, 

2120 self.vector_retriever.retrieve( 

2121 kb, 

2122 queries, 

2123 lexical_terms, 

2124 _search_cfg(kb, cfg), 

2125 failures=degraded, 

2126 ), 

2127 ) 

2128 for kb in vector_kbs 

2129 ] 

2130 for kb in vector_kbs: 

2131 kb_targets = targets.get(str(kb.get("id", ""))) 

2132 doc_ids = [d.document_id for d in (kb_targets or []) if d.document_id] 

2133 if doc_ids: 

2134 jobs.append( 

2135 ( 

2136 kb, 

2137 self.vector_retriever.retrieve( 

2138 kb, 

2139 queries, 

2140 lexical_terms, 

2141 _search_cfg(kb, cfg), 

2142 document_ids=doc_ids, 

2143 failures=degraded, 

2144 ), 

2145 ) 

2146 ) 

2147 vector_results = await asyncio.gather( 

2148 *(job for _, job in jobs), return_exceptions=True 

2149 ) 

2150 seen_points: set[tuple[str, str, int | None]] = set() 

2151 for (kb, _), res in zip(jobs, vector_results): 

2152 if isinstance(res, BaseException): 

2153 lane.vector_errors.append( 

2154 f"vector:{kb.get('name', kb.get('id'))}: {res}" 

2155 ) 

2156 continue 

2157 for p in res: 

2158 key = (p.kb_id, p.document_id, p.chunk_index) 

2159 if key in seen_points: 

2160 # Scoped hit duplicates an unscoped one → keep the targeted flag. 

2161 for existing in passages: 

2162 if ( 

2163 existing.kb_id, 

2164 existing.document_id, 

2165 existing.chunk_index, 

2166 ) == key: 

2167 existing.targeted = existing.targeted or p.targeted 

2168 break 

2169 continue 

2170 seen_points.add(key) 

2171 passages.append(p) 

2172 if cited: 

2173 # Before the judge: what it would rate is already in the evidence. 

2174 passages = [p for p in passages if not cited.holds(p)] 

2175 timings["vector"] = int((time.monotonic() - t) * 1000) 

2176 

2177 # 4. Rerank, drop what the judge ruled out, then boost passages from 

2178 # explicitly named documents 

2179 t = time.monotonic() 

2180 # What each knowledge base's search found, before anything is ruled 

2181 # out: the turn's retrieval record. 

2182 lane.found = _per_kb([*passages, *facts]) 

2183 if passages: 

2184 if not isinstance(self.reranker, NoopReranker): 

2185 lane.judged = min(len(passages), cfg.rerank_candidates) 

2186 passages = await self.reranker.rerank( 

2187 plan.query, 

2188 passages, 

2189 cfg, 

2190 knowledge=_knowledge_brief(vector_kbs), 

2191 report=judge_report, 

2192 ) 

2193 judged = _per_kb(passages) 

2194 passages, lane.judged_out = relevance_gate(passages, cfg) 

2195 after = _per_kb(passages) 

2196 lane.ruled_out = { 

2197 kb_id: n - after.get(kb_id, 0) 

2198 for kb_id, n in judged.items() 

2199 if n > after.get(kb_id, 0) 

2200 } 

2201 # Each kind's own reading: dated passages kept to the turn's 

2202 # window and weighed for recency. Domain's is none. 

2203 passages, lane.windowed = _by_category(passages, vector_kbs, turn, on) 

2204 if targets: 

2205 passages = [ 

2206 p.model_copy(update={"score": p.score + _TARGET_BOOST}) 

2207 if p.targeted 

2208 else p 

2209 for p in passages 

2210 ] 

2211 passages.sort(key=lambda p: p.score, reverse=True) 

2212 lane.judge_failure = judge_report.failure 

2213 timings["rerank"] = int((time.monotonic() - t) * 1000) 

2214 

2215 # 4b. Whole-document requests: prepend the document text itself — the 

2216 # documents this lane's knowledge bases hold. 

2217 kb_lookup = {str(kb.get("id", "")): kb for kb in vector_kbs} 

2218 own_targets = {k: v for k, v in targets.items() if k in kb_lookup} 

2219 if plan.whole_document and own_targets: 

2220 full_passages = await self.targeter.full_text_passages( 

2221 kb_lookup, own_targets, cfg 

2222 ) 

2223 passages = full_passages + passages 

2224 

2225 # 5. Neighbour expansion of the leading candidates only 

2226 t = time.monotonic() 

2227 kb_top_k = { 

2228 str(kb.get("id", "")): int(_kb_field(kb, "top_k", cfg.top_k)) 

2229 for kb in vector_kbs 

2230 } 

2231 head_n = max(sum(kb_top_k.values()), cfg.top_k) * 2 

2232 head = await expand_neighbours( 

2233 passages[:head_n], cfg.neighbour_window, cited=cited 

2234 ) 

2235 passages = head + passages[head_n:] 

2236 if cited: 

2237 # The windows stop short of cited chunks already. This drops what 

2238 # spans them anyway: a whole document, whose text has no window 

2239 # to clip (its uncited chunks may still come as hits). 

2240 passages = [p for p in passages if not cited.holds(p)] 

2241 timings["expand"] = int((time.monotonic() - t) * 1000) 

2242 

2243 lane.passages = passages 

2244 lane.facts = facts 

2245 return lane 

2246 

2247 def pack( 

2248 self, 

2249 plan: KnowledgePlan, 

2250 lanes: Sequence[LaneResult], 

2251 knowledge_bases: list[dict[str, Any]], 

2252 *, 

2253 citation_offset: int = 0, 

2254 on: date | None = None, 

2255 ) -> RetrievalBundle: 

2256 """Stage 6: the lanes' passages and facts within the budget, cited 

2257 and rendered, with the bundle's counts. ``knowledge_bases`` is every 

2258 knowledge base the lanes searched.""" 

2259 cfg = self.cfg 

2260 on = on or categories.today() 

2261 bundle = RetrievalBundle( 

2262 query=plan.query, kb_ids=[str(kb.get("id", "")) for kb in knowledge_bases] 

2263 ) 

2264 query, queries, targets = plan.query, plan.queries, plan.targets 

2265 passages = [p for lane in lanes for p in lane.passages] 

2266 facts = [f for lane in lanes for f in lane.facts] 

2267 # Each lane's judge is its own: with several, a failure names its lane. 

2268 judge_failure = "; ".join( 

2269 f"{lane.category}: {lane.judge_failure}" 

2270 if lane.category and len(lanes) > 1 

2271 else lane.judge_failure 

2272 for lane in lanes 

2273 if lane.judge_failure 

2274 ) 

2275 vector_kbs = [kb for kb in knowledge_bases if kb.get("source_type") != "graph"] 

2276 kb_lookup = {str(kb.get("id", "")): kb for kb in vector_kbs} 

2277 kb_top_k = { 

2278 str(kb.get("id", "")): int(_kb_field(kb, "top_k", cfg.top_k)) 

2279 for kb in vector_kbs 

2280 } 

2281 

2282 # 6. Pack + render. A kind packed apart (frameworks) takes its share 

2283 # of the budget only when it has passages, and is cited after the 

2284 # evidence, so knowledge that is all domain packs exactly as before. 

2285 # It also takes what the evidence leaves: frameworks alone had their 

2286 # 30% share and the rest of the budget went unused, so an agent of 

2287 # methods only was handed two of the sixteen it found. 

2288 by_kb = { 

2289 str(kb.get("id", "")): categories.category_of(kb) for kb in knowledge_bases 

2290 } 

2291 parts = categories.split(passages, by_kb) 

2292 reserved = { 

2293 category: min( 

2294 int( 

2295 cfg.max_context_tokens * categories.REGISTRY[category].budget_share 

2296 ), 

2297 sum(approx_tokens(p.text) for p in apart), 

2298 ) 

2299 for category, apart in parts.apart.items() 

2300 } 

2301 evidence_cfg = ( 

2302 cfg.model_copy( 

2303 update={ 

2304 "max_context_tokens": cfg.max_context_tokens 

2305 - sum(reserved.values()) 

2306 } 

2307 ) 

2308 if reserved 

2309 else cfg 

2310 ) 

2311 # Two or more evidence lanes (a turn's mix: Domain and Temporal) each 

2312 # take their share of the evidence budget; one lane packs as it 

2313 # always did. 

2314 led = _evidence_lanes(lanes, parts.evidence) 

2315 if led: 

2316 chosen, chosen_facts = self.packer.select_lanes( 

2317 led, facts, evidence_cfg, kb_top_k, citation_offset=citation_offset 

2318 ) 

2319 else: 

2320 chosen, chosen_facts = self.packer.select( 

2321 parts.evidence, 

2322 facts, 

2323 evidence_cfg, 

2324 kb_top_k, 

2325 citation_offset=citation_offset, 

2326 ) 

2327 left = max( 

2328 0, 

2329 evidence_cfg.max_context_tokens 

2330 - sum(approx_tokens(p.text) for p in chosen) 

2331 - sum(approx_tokens(f.as_text()) for f in chosen_facts), 

2332 ) 

2333 granted: dict[KnowledgeCategory, int] = {} 

2334 frameworks: list[RetrievedPassage] = [] 

2335 for category, apart in parts.apart.items(): 

2336 granted[category] = reserved[category] + left 

2337 picked, _ = self.packer.select( 

2338 apart, 

2339 [], 

2340 cfg.model_copy(update={"max_context_tokens": granted[category]}), 

2341 kb_top_k, 

2342 citation_offset=citation_offset 

2343 + len(chosen) 

2344 + len(chosen_facts) 

2345 + len(frameworks), 

2346 ) 

2347 used = sum(approx_tokens(p.text) for p in picked) 

2348 left = max(0, left - max(0, used - reserved[category])) 

2349 frameworks.extend(picked) 

2350 hit_kbs = ( 

2351 {p.kb_id for p in chosen} 

2352 | {f.kb_id for f in chosen_facts} 

2353 | {p.kb_id for p in frameworks} 

2354 ) 

2355 skipped = [ 

2356 str(kb.get("name", kb.get("id", ""))) 

2357 for kb in knowledge_bases 

2358 if str(kb.get("id", "")) not in hit_kbs 

2359 ] 

2360 targeted_documents: list[dict[str, Any]] = [] 

2361 for kb_id, docs in targets.items(): 

2362 for d in docs: 

2363 mine = [ 

2364 p 

2365 for p in chosen 

2366 if p.kb_id == kb_id 

2367 and (p.document_id == d.document_id or p.source == d.display_name) 

2368 ] 

2369 coverage = ( 

2370 "full" 

2371 if any(p.full_document for p in mine) 

2372 else "partial" 

2373 if mine 

2374 else "none" 

2375 ) 

2376 targeted_documents.append( 

2377 { 

2378 "kb_id": kb_id, 

2379 "kb_name": str(kb_lookup.get(kb_id, {}).get("name", kb_id)), 

2380 "document_id": d.document_id, 

2381 "name": d.display_name, 

2382 "coverage": coverage, 

2383 } 

2384 ) 

2385 markdown = self.packer.render( 

2386 query, 

2387 queries, 

2388 chosen, 

2389 chosen_facts, 

2390 skipped, 

2391 targeted_documents, 

2392 plan.unresolved, 

2393 judge_failed=bool(judge_failure), 

2394 categories_by_kb=by_kb, 

2395 on=on, 

2396 dated_first=bool(led) 

2397 and led[0][0].category == KnowledgeCategory.temporal.value, 

2398 ) 

2399 frameworks_markdown = self.packer.render_frameworks( 

2400 frameworks, judge_failed=bool(judge_failure) 

2401 ) 

2402 

2403 found = {k: n for lane in lanes for k, n in lane.found.items()} 

2404 ruled_out = {k: n for lane in lanes for k, n in lane.ruled_out.items()} 

2405 windowed = {k: n for lane in lanes for k, n in lane.windowed.items()} 

2406 bundle.queries = queries 

2407 bundle.passages = chosen + frameworks 

2408 bundle.graph_facts = chosen_facts 

2409 bundle.skipped_kbs = skipped 

2410 bundle.targeted_documents = targeted_documents 

2411 bundle.unresolved_mentions = plan.unresolved 

2412 # As the stages ran: graph lookups, targeting, then vector search — 

2413 # and a lane whose search failed outright. 

2414 bundle.errors = [ 

2415 *(e for lane in lanes for e in lane.graph_errors), 

2416 *plan.errors, 

2417 *(e for lane in lanes for e in lane.vector_errors), 

2418 *( 

2419 f"{lane.category or 'search'}: {lane.failure}" 

2420 for lane in lanes 

2421 if lane.failure 

2422 ), 

2423 ] 

2424 bundle.degraded = list( 

2425 dict.fromkeys(d for lane in lanes for d in lane.degraded) 

2426 ) 

2427 if bundle.degraded: 

2428 logger.warning( 

2429 "retrieval pipeline degraded: %s", "; ".join(bundle.degraded) 

2430 ) 

2431 bundle.judged_out = sum(lane.judged_out for lane in lanes) 

2432 bundle.out_of_window = sum(windowed.values()) 

2433 kept = _per_kb([*chosen, *frameworks, *chosen_facts]) 

2434 bundle.kb_counts = { 

2435 kb_id: { 

2436 "found": found.get(kb_id, 0), 

2437 "kept": kept.get(kb_id, 0), 

2438 "ruled_out": ruled_out.get(kb_id, 0), 

2439 "out_of_window": windowed.get(kb_id, 0), 

2440 } 

2441 for kb_id in [str(kb.get("id", "")) for kb in knowledge_bases] 

2442 } 

2443 bundle.dated_passages = sum( 

2444 1 for p in chosen if by_kb.get(p.kb_id) is KnowledgeCategory.temporal 

2445 ) 

2446 bundle.frameworks_markdown = frameworks_markdown 

2447 bundle.lanes = _lane_packing( 

2448 lanes, led, chosen, frameworks, reserved, granted, facts, evidence_cfg 

2449 ) 

2450 bundle.planner_failure = plan.planner_failure 

2451 bundle.judge_failure = judge_failure 

2452 bundle.context_markdown = markdown 

2453 bundle.approx_tokens = approx_tokens(markdown) if markdown else 0 

2454 # In the order the stages ran; lanes run side by side, so a lane 

2455 # stage takes the longest lane's time. 

2456 timings: dict[str, int] = {"plan": plan.timings.get("plan", 0)} 

2457 for stage in ("graph", "target", "vector", "rerank", "expand"): 

2458 timings[stage] = ( 

2459 plan.timings.get(stage, 0) 

2460 if stage == "target" 

2461 else max((lane.timings.get(stage, 0) for lane in lanes), default=0) 

2462 ) 

2463 bundle.timings_ms = timings 

2464 logger.info( 

2465 "retrieval pipeline queries=%d kbs=%d passages=%d facts=%d tokens≈%d timings=%s", 

2466 len(queries), 

2467 len(knowledge_bases), 

2468 len(chosen), 

2469 len(chosen_facts), 

2470 bundle.approx_tokens, 

2471 timings, 

2472 ) 

2473 return bundle 

2474 

2475 

2476async def retrieve_context( 

2477 query: str, 

2478 knowledge_bases: list[dict[str, Any]], 

2479 cfg: RetrievalConfig | dict[str, Any] | None = None, 

2480 llm: Any = None, 

2481 kb_metadata: str = "", 

2482) -> RetrievalBundle: 

2483 """Convenience entry point: build a pipeline from config and run it.""" 

2484 if not isinstance(cfg, RetrievalConfig): 

2485 cfg = RetrievalConfig(**(cfg or {})) 

2486 return await RetrievalPipeline.from_config(cfg, llm).run( 

2487 query, knowledge_bases, kb_metadata 

2488 )