Coverage for app / knowledge / documents.py: 93%

354 statements  

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

1""" 

2Document resolution and full-text access for knowledge bases. 

3 

4svc-core stores each uploaded file twice-named: the MinIO object uses a 

5*sanitised* filename (``Annual Report 2024.pdf`` → ``Annual_Report_2024.pdf``, 

6plus a short suffix when a name collides) while the Qdrant payload — and hence 

7everything an agent sees in metadata and search results — carries the 

8*original* filename. Agents therefore need a resolver that accepts whatever 

9the user or model typed and maps it to the stored document. 

10 

11This module provides: 

12 

13* ``list_documents`` — one ``DocumentRef`` per indexed document 

14 (TTL-cached; MinIO fallback for un-indexed KBs) 

15* ``match_document`` / 

16 ``resolve_document`` — tolerant name matching ladder 

17 (exact → case-insensitive → sanitised → stem → 

18 substring → token overlap) 

19* ``find_mentioned_documents`` — detect documents referenced in a user query 

20* ``get_document_text`` — full document text assembled from the parsed 

21 chunks in Qdrant (works for PDF/DOCX/…), with a 

22 MinIO fallback for plain-text formats only 

23""" 

24 

25from __future__ import annotations 

26 

27import asyncio 

28import logging 

29import os 

30import re 

31import time 

32from dataclasses import dataclass 

33from collections.abc import Sequence 

34from typing import Any 

35 

36from app.knowledge import passage_text 

37from app.services import rag as rag_service 

38 

39logger = logging.getLogger(__name__) 

40 

41_CACHE_TTL: float = 120.0 

42_cache: dict[str, tuple[float, list[DocumentRef]]] = {} 

43 

44_TEXT_EXTENSIONS = frozenset( 

45 {".txt", ".md", ".csv", ".json", ".xml", ".yaml", ".yml", ".html", ".htm", ".rst"} 

46) 

47_KNOWN_EXTENSIONS = _TEXT_EXTENSIONS | frozenset( 

48 {".pdf", ".docx", ".doc", ".xlsx", ".xls", ".pptx", ".ppt"} 

49) 

50_SEP_RE = re.compile(r"[\s_\-]+") 

51_NON_WORD_RE = re.compile(r"[^\w.\-]") 

52_QUOTED_RE = re.compile(r"[\"'“”‘’`]([^\"'“”‘’`]{2,120})[\"'“”‘’`]") 

53# Bare filenames never contain spaces here — names with spaces are caught by 

54# the quoted-string pattern or by known-name matching in find_mentioned_documents. 

55_FILENAME_TOKEN_RE = re.compile( 

56 r"[\w][\w\-.]{0,100}?\.(?:pdf|docx?|xlsx?|pptx?|txt|md|csv|json|xml|ya?ml|html?|rst)\b", 

57 re.IGNORECASE, 

58) 

59_DEDUPE_SUFFIX_RE = re.compile(r"_[0-9a-f]{8}$") 

60_DOC_CUE_RE = re.compile( 

61 r"\b(file|files|document|documents|doc|docs|attachment|upload(ed)?|readme|" 

62 r"report|spec|specification|manual|guide|pdf|docx|spreadsheet|slides|deck)\b", 

63 re.IGNORECASE, 

64) 

65 

66# Minimum token-overlap ratio for a fuzzy match to count. 

67_FUZZY_MIN_RATIO = 0.6 

68 

69 

70@dataclass 

71class DocumentRef: 

72 """A stored document as seen by the retrieval layer.""" 

73 

74 kb_id: str 

75 document_id: str = "" 

76 original_filename: str = "" 

77 source_id: str = "" # sanitised MinIO object name 

78 folder_path: str = "" 

79 mime_type: str = "" 

80 chunk_count: int = 0 

81 max_page: int | None = None 

82 # "indexed" | "pending" | "failed" | "unknown" — from svc-core's manifest; 

83 # "indexed" is also inferred when chunks are present in the vector store. 

84 index_status: str = "unknown" 

85 index_error: str = "" 

86 

87 @property 

88 def display_name(self) -> str: 

89 return self.original_filename or self.source_id 

90 

91 @property 

92 def is_indexed(self) -> bool: 

93 return self.chunk_count > 0 or self.index_status == "indexed" 

94 

95 @property 

96 def names(self) -> list[str]: 

97 return [n for n in (self.original_filename, self.source_id) if n] 

98 

99 def describe(self) -> str: 

100 bits = [] 

101 if self.folder_path: 

102 bits.append(f"folder {self.folder_path}/") 

103 if self.max_page: 

104 bits.append(f"{self.max_page} page{'s' if self.max_page != 1 else ''}") 

105 if self.chunk_count: 

106 bits.append( 

107 f"{self.chunk_count} chunk{'s' if self.chunk_count != 1 else ''}" 

108 ) 

109 elif self.index_status == "failed": 

110 bits.append("indexing failed — full text still readable") 

111 elif not self.is_indexed: 

112 bits.append("indexing pending — full text still readable") 

113 return f"{self.display_name}" + (f" ({', '.join(bits)})" if bits else "") 

114 

115 

116@dataclass 

117class DocumentText: 

118 ref: DocumentRef 

119 text: str 

120 truncated: bool = False 

121 chunk_count: int = 0 

122 origin: str = ( 

123 "index" # "index" (Qdrant chunks) | "storage" (MinIO bytes) | "unavailable" 

124 ) 

125 note: str = "" 

126 

127 

128# ── Name normalisation ──────────────────────────────────────────────────────── 

129 

130 

131def sanitise_filename(name: str) -> str: 

132 """Mirror svc-core's ``_safe_filename`` so we can compare against MinIO names.""" 

133 base = os.path.basename(name or "") 

134 return _NON_WORD_RE.sub("_", base) or "upload" 

135 

136 

137def split_ext(name: str) -> tuple[str, str]: 

138 stem, ext = os.path.splitext(name or "") 

139 return stem, ext.lower() 

140 

141 

142def name_key(name: str, *, drop_ext: bool = False, drop_suffix: bool = False) -> str: 

143 """Canonical comparison key: lower-case, separators collapsed to one space.""" 

144 base = os.path.basename((name or "").strip()) 

145 if drop_ext: 

146 base, _ = split_ext(base) 

147 if drop_suffix: 

148 base = _DEDUPE_SUFFIX_RE.sub("", base) 

149 return _SEP_RE.sub(" ", base.lower()).strip() 

150 

151 

152def _tokens(name: str) -> set[str]: 

153 return {t for t in name_key(name, drop_ext=True).split() if len(t) > 1} 

154 

155 

156# ── Listing ─────────────────────────────────────────────────────────────────── 

157 

158 

159def invalidate_cache(kb_id: str | None = None) -> None: 

160 if kb_id is None: 

161 _cache.clear() 

162 else: 

163 _cache.pop(kb_id, None) 

164 

165 

166def _refs_from_payloads( 

167 kb_id: str, payloads: list[dict[str, Any]] 

168) -> list[DocumentRef]: 

169 by_doc: dict[str, DocumentRef] = {} 

170 for pl in payloads: 

171 doc_id = str(pl.get("document_id") or "") 

172 key = doc_id or str(pl.get("original_filename") or pl.get("source_id") or "") 

173 if not key: 

174 continue 

175 ref = by_doc.get(key) 

176 if ref is None: 

177 ref = DocumentRef( 

178 kb_id=kb_id, 

179 document_id=doc_id, 

180 original_filename=str(pl.get("original_filename") or ""), 

181 source_id=str(pl.get("source_id") or ""), 

182 folder_path=str(pl.get("folder_path") or ""), 

183 mime_type=str(pl.get("mime_type") or ""), 

184 ) 

185 by_doc[key] = ref 

186 ref.chunk_count += 1 

187 page = pl.get("page_number") 

188 if isinstance(page, int) and (ref.max_page is None or page > ref.max_page): 

189 ref.max_page = page 

190 return sorted(by_doc.values(), key=lambda r: r.display_name.lower()) 

191 

192 

193def _refs_from_manifest( 

194 kb_id: str, manifest: list[dict[str, Any]] 

195) -> list[DocumentRef]: 

196 refs: list[DocumentRef] = [] 

197 for entry in manifest or []: 

198 if not isinstance(entry, dict): 

199 continue 

200 name = str(entry.get("name") or entry.get("original_filename") or "") 

201 source_id = str(entry.get("source_id") or name) 

202 if not (name or source_id): 

203 continue 

204 refs.append( 

205 DocumentRef( 

206 kb_id=kb_id, 

207 document_id=str(entry.get("id") or entry.get("document_id") or ""), 

208 original_filename=name, 

209 source_id=source_id, 

210 folder_path=str(entry.get("folder_path") or ""), 

211 mime_type=str(entry.get("mime_type") or ""), 

212 chunk_count=int(entry.get("chunk_count") or 0), 

213 index_status=str(entry.get("index_status") or "unknown"), 

214 index_error=str(entry.get("index_error") or ""), 

215 ) 

216 ) 

217 return refs 

218 

219 

220def _merge_refs( 

221 primary: list[DocumentRef], secondary: list[DocumentRef] 

222) -> list[DocumentRef]: 

223 """Union of two listings keyed by document id (else sanitised name). 

224 

225 ``primary`` entries win on conflicts but inherit chunk counts / pages the 

226 secondary source knows about. 

227 """ 

228 

229 def _key(r: DocumentRef) -> str: 

230 return r.document_id or sanitise_filename(r.display_name).lower() 

231 

232 merged: dict[str, DocumentRef] = {_key(r): r for r in primary} 

233 for r in secondary: 

234 k = _key(r) 

235 cur = merged.get(k) 

236 if cur is None: 

237 merged[k] = r 

238 continue 

239 if not cur.chunk_count and r.chunk_count: 

240 cur.chunk_count = r.chunk_count 

241 if cur.max_page is None and r.max_page is not None: 

242 cur.max_page = r.max_page 

243 if not cur.original_filename and r.original_filename: 

244 cur.original_filename = r.original_filename 

245 if not cur.document_id and r.document_id: 

246 cur.document_id = r.document_id 

247 if cur.index_status == "unknown" and r.index_status != "unknown": 

248 cur.index_status = r.index_status 

249 return sorted(merged.values(), key=lambda r: r.display_name.lower()) 

250 

251 

252async def list_documents( 

253 kb_id: str, 

254 *, 

255 force: bool = False, 

256 manifest: list[dict[str, Any]] | None = None, 

257) -> list[DocumentRef]: 

258 """All documents of a knowledge base. 

259 

260 Sources, merged in priority order: 

261 1. ``manifest`` — svc-core's document rows passed with the KB spec. 

262 Authoritative for *what exists*; independent of indexing or storage. 

263 2. The vector index (chunk counts, pages, folder) — TTL-cached scan. 

264 3. The MinIO listing (sanitised names only) when 1 and 2 are both empty, 

265 so a KB whose manifest was not supplied is still browsable. 

266 """ 

267 manifest_refs = _refs_from_manifest(kb_id, manifest or []) 

268 

269 index_refs: list[DocumentRef] | None = None 

270 if not force: 

271 cached = _cache.get(kb_id) 

272 if cached and time.monotonic() - cached[0] < _CACHE_TTL: 

273 index_refs = cached[1] 

274 if index_refs is None: 

275 try: 

276 payloads = await rag_service.scan_document_index(kb_id) 

277 index_refs = _refs_from_payloads(kb_id, payloads) 

278 except Exception as exc: # noqa: BLE001 — degrade to other sources 

279 logger.warning("list_documents: index scan failed for %s: %s", kb_id, exc) 

280 index_refs = [] 

281 _cache[kb_id] = (time.monotonic(), index_refs) 

282 

283 refs = _merge_refs(manifest_refs, index_refs) 

284 if not refs: 

285 try: 

286 from app.util import minio_client 

287 

288 # The client is synchronous: list off the event loop. 

289 names = await asyncio.to_thread(minio_client.list_documents, kb_id) 

290 refs = [ 

291 DocumentRef(kb_id=kb_id, source_id=name, original_filename="") 

292 for name in names 

293 ] 

294 except Exception as exc: # noqa: BLE001 

295 logger.warning( 

296 "list_documents: storage listing failed for %s: %s", kb_id, exc 

297 ) 

298 refs = [] 

299 return refs 

300 

301 

302# ── Matching ────────────────────────────────────────────────────────────────── 

303 

304 

305def match_document( 

306 name: str, docs: list[DocumentRef] 

307) -> tuple[DocumentRef | None, list[DocumentRef]]: 

308 """Resolve *name* against *docs* with a tolerant ladder. 

309 

310 Returns ``(best, alternatives)``. ``alternatives`` holds other plausible 

311 matches (for "did you mean" messages) when no exact match exists. 

312 """ 

313 query = (name or "").strip() 

314 if not query or not docs: 

315 return None, [] 

316 

317 q_exact = query 

318 q_ci = query.lower() 

319 q_san = sanitise_filename(query).lower() 

320 q_key = name_key(query) 

321 q_key_noext = name_key(query, drop_ext=True) 

322 q_tokens = _tokens(query) 

323 

324 def _score(doc: DocumentRef) -> float: 

325 best = 0.0 

326 for n in doc.names: 

327 if n == q_exact: 

328 return 100.0 

329 if n.lower() == q_ci: 

330 best = max(best, 95.0) 

331 if sanitise_filename(n).lower() == q_san: 

332 best = max(best, 90.0) 

333 if name_key(n) == q_key or name_key(n, drop_suffix=True) == q_key: 

334 best = max(best, 85.0) 

335 if name_key(n, drop_ext=True, drop_suffix=True) == q_key_noext: 

336 best = max(best, 80.0) 

337 nk = name_key(n, drop_suffix=True) 

338 if ( 

339 q_key_noext 

340 and (q_key_noext in nk or nk in q_key_noext) 

341 and len(q_key_noext) >= 4 

342 ): 

343 best = max(best, 60.0) 

344 if q_tokens: 

345 overlap = len(q_tokens & _tokens(n)) / len(q_tokens) 

346 if overlap >= _FUZZY_MIN_RATIO: 

347 best = max(best, 30.0 + 25.0 * overlap) 

348 return best 

349 

350 scored = sorted( 

351 ((s, d) for d in docs if (s := _score(d)) > 0), key=lambda x: x[0], reverse=True 

352 ) 

353 if not scored: 

354 return None, [] 

355 top_score, best = scored[0] 

356 # Ambiguity guard: two different docs tied on a fuzzy score → no single best. 

357 if top_score < 80 and len(scored) > 1 and scored[1][0] == top_score: 

358 return None, [d for _, d in scored[:5]] 

359 alternatives = [d for s, d in scored[1:5] if s >= 30] 

360 return best, alternatives 

361 

362 

363async def resolve_document( 

364 kb_id: str, name: str, manifest: list[dict[str, Any]] | None = None 

365) -> tuple[DocumentRef | None, list[DocumentRef]]: 

366 docs = await list_documents(kb_id, manifest=manifest) 

367 best, alts = match_document(name, docs) 

368 if best is None: 

369 # Cache may be stale right after an upload — retry once with a fresh scan. 

370 docs = await list_documents(kb_id, force=True, manifest=manifest) 

371 best, alts = match_document(name, docs) 

372 return best, alts 

373 

374 

375def filename_mentions(text: str) -> list[str]: 

376 """Strings in *text* that look like filenames (extension) or quoted titles.""" 

377 found: list[str] = [] 

378 for m in _FILENAME_TOKEN_RE.finditer(text or ""): 

379 cand = m.group(0).strip() 

380 if cand and cand not in found: 

381 found.append(cand) 

382 for m in _QUOTED_RE.finditer(text or ""): 

383 cand = m.group(1).strip() 

384 if cand and cand not in found: 

385 found.append(cand) 

386 return found 

387 

388 

389def _mentioned_as_identifier(stem_key: str, cased_text: str) -> bool: 

390 """True when *stem_key* occurs in *cased_text* in a non-lowercase form.""" 

391 pattern = re.compile( 

392 r"(?<![\w])" + re.escape(stem_key) + r"(?![\w])", re.IGNORECASE 

393 ) 

394 return any(m.group(0) != m.group(0).lower() for m in pattern.finditer(cased_text)) 

395 

396 

397#: The namespace the conversation's attached documents are matched in. 

398ATTACHED_KB = "attachments" 

399 

400 

401def attached_refs(names: Sequence[str]) -> list[DocumentRef]: 

402 """The documents attached to the conversation, as refs to match a 

403 mention against (``find_mentioned_documents(exclude=)``).""" 

404 return [DocumentRef(kb_id=ATTACHED_KB, original_filename=n) for n in names if n] 

405 

406 

407def find_mentioned_documents( 

408 text: str, 

409 docs: list[DocumentRef], 

410 *, 

411 exclude: Sequence[DocumentRef] = (), 

412 elsewhere: Sequence[str] = (), 

413) -> tuple[list[DocumentRef], list[str]]: 

414 """Documents referenced in *text*, plus filename-like mentions that resolved 

415 to nothing (so callers can say so instead of guessing). 

416 

417 Two detection strategies are combined: 

418 1. every known document whose (normalised) name or stem appears in the 

419 normalised text — catches "summarise the annual report 2024"; 

420 2. explicit filename / quoted mentions resolved through ``match_document`` 

421 — catches misspellings and sanitised variants. 

422 

423 ``exclude`` are documents that are not knowledge — the ones the 

424 conversation attached (``attached_refs``). A mention of one is neither a 

425 hit nor unresolved, and a stored document sharing its name is not found 

426 by that name: the person means the one they attached. 

427 

428 ``elsewhere`` are file names the attached documents themselves mention: 

429 one the knowledge does not hold is what a document talks about, not a 

430 missing file to report ("what does it say about manifest.json?" of a 

431 report that lists its data in manifest.json). 

432 """ 

433 if not text or not docs: 

434 return [], [] 

435 excluded_keys = {name_key(n, drop_suffix=True) for d in exclude for n in d.names} 

436 elsewhere_keys = {name_key(n, drop_suffix=True) for n in elsewhere} 

437 norm_text = f" {_SEP_RE.sub(' ', text.lower())} " 

438 # Same normalisation but case-preserved, to spot identifier-style mentions 

439 # such as "README" or "CHANGELOG" that are short but clearly a file name. 

440 cased_text = f" {_SEP_RE.sub(' ', text)} " 

441 cue_words = bool(_DOC_CUE_RE.search(text)) 

442 hits: dict[str, DocumentRef] = {} 

443 

444 for doc in docs: 

445 for n in doc.names: 

446 full_key = name_key(n, drop_suffix=True) 

447 if full_key in excluded_keys: 

448 continue 

449 stem_key = name_key(n, drop_ext=True, drop_suffix=True) 

450 if len(full_key) >= 4 and f" {full_key} " in norm_text: 

451 hits.setdefault(doc.document_id or doc.display_name, doc) 

452 break 

453 if not stem_key or f" {stem_key} " not in norm_text: 

454 continue 

455 # A bare stem only counts when it is distinctive — several words, 

456 # a long token, written as an identifier (README, not "readme"), 

457 # or accompanied by a document cue ("the … file") — so a document 

458 # called "Notes.md" is not triggered by "take notes" in chat. 

459 distinctive = ( 

460 len(stem_key.split()) >= 2 

461 or len(stem_key) >= 8 

462 or cue_words 

463 or _mentioned_as_identifier(stem_key, cased_text) 

464 ) 

465 if distinctive: 

466 hits.setdefault(doc.document_id or doc.display_name, doc) 

467 break 

468 

469 unresolved: list[str] = [] 

470 for mention in filename_mentions(text): 

471 if exclude and match_document(mention, list(exclude))[0] is not None: 

472 continue 

473 best, _ = match_document(mention, docs) 

474 if best is not None: 

475 hits.setdefault(best.document_id or best.display_name, best) 

476 elif ( 

477 split_ext(mention)[1] in _KNOWN_EXTENSIONS 

478 and name_key(mention, drop_suffix=True) not in elsewhere_keys 

479 ): 

480 unresolved.append(mention) 

481 return list(hits.values()), unresolved 

482 

483 

484# ── Full text ───────────────────────────────────────────────────────────────── 

485 

486 

487# ── Joining neighbouring chunks ─────────────────────────────────────────────── 

488 

489#: svc-core's chunker (``app/util/docling_client.py``) starts every chunk with 

490#: the last 64 tokens of the one before, so neighbours joined back into one 

491#: text repeated about 300 characters at every boundary — 8–12% of a merged 

492#: window, counted against the context budget. The repeat is found as the 

493#: *shortest* exact match of at least ``_MIN_OVERLAP_CHARS``: in repetitive 

494#: text (a table's identical rows) a coincidence then leaves a little text 

495#: repeated, where the longest match would delete real rows. 

496_MIN_OVERLAP_CHARS = 24 

497#: 64 tokens of English run to about 300 characters; long URLs or CJK more. 

498_MAX_OVERLAP_CHARS = 1_200 

499 

500 

501def overlap_length(prev: str, cur: str) -> int: 

502 """How many leading characters of *cur* repeat the end of *prev* — the 

503 chunker's carried overlap — or 0 when it does not start with one.""" 

504 if len(prev) < _MIN_OVERLAP_CHARS or len(cur) < _MIN_OVERLAP_CHARS: 

505 return 0 

506 # A carried overlap that starts mid-character decodes as U+FFFD. 

507 lead = len(cur) - len(cur.lstrip("\ufffd")) 

508 body = cur[lead:] 

509 tail = prev[-_MIN_OVERLAP_CHARS:] 

510 limit = min(len(body), _MAX_OVERLAP_CHARS) 

511 start = 0 

512 while (pos := body.find(tail, start, limit)) >= 0: 

513 cut = pos + _MIN_OVERLAP_CHARS 

514 if prev.endswith(body[:cut]): 

515 return lead + cut 

516 start = pos + 1 

517 return 0 

518 

519 

520def _consecutive(prev_index: Any, index: Any) -> bool: 

521 try: 

522 return int(index) == int(prev_index) + 1 

523 except (TypeError, ValueError): 

524 return False 

525 

526 

527def join_chunks(texts: list[str], indexes: list[Any] | None = None) -> str: 

528 """Neighbouring chunks' texts as one text, each chunk's repeat of the one 

529 before it dropped. With *indexes* (the chunks' ``chunk_index``), only 

530 consecutive chunks are compared: chunks with a gap between them share no 

531 overlap. Chunks with no overlap are joined by a newline.""" 

532 out = "" 

533 prev: str | None = None 

534 prev_index: Any = None 

535 for i, raw in enumerate(texts): 

536 text = str(raw or "").strip() 

537 if not text: 

538 continue 

539 index = indexes[i] if indexes is not None else None 

540 adjacent = prev is not None and ( 

541 indexes is None or _consecutive(prev_index, index) 

542 ) 

543 cut = overlap_length(prev, text) if adjacent and prev is not None else 0 

544 if not out: 

545 out = text 

546 elif cut: 

547 out += text[cut:] 

548 else: 

549 out += "\n" + text 

550 prev, prev_index = text, index 

551 return out 

552 

553 

554def _assemble(chunks: list[dict[str, Any]]) -> str: 

555 """Join ordered chunk payloads, inserting page markers where pages change 

556 and dropping each chunk's repeat of the one before (``join_chunks``).""" 

557 parts: list[str] = [] 

558 current_page: Any = object() 

559 prev: str | None = None 

560 prev_index: Any = None 

561 ends_in_text = False # whether parts[-1] is chunk text (not a page marker) 

562 for pl in chunks: 

563 text = str(pl.get("text") or "").strip() 

564 if not text: 

565 continue 

566 index = pl.get("chunk_index") 

567 cut = ( 

568 overlap_length(prev, text) 

569 if prev is not None and _consecutive(prev_index, index) 

570 else 0 

571 ) 

572 prev, prev_index = text, index 

573 rest = text[cut:] 

574 page = pl.get("page_number") 

575 if page is not None and page != current_page: 

576 parts.append(f"\n--- page {page} ---") 

577 current_page = page 

578 ends_in_text = False 

579 rest = rest.lstrip() # the marker separates; no blank lines after it 

580 if not rest: 

581 continue 

582 if cut and ends_in_text: 

583 parts[-1] += rest # a continuation of the previous chunk's text 

584 else: 

585 parts.append(rest.lstrip() if cut else rest) 

586 ends_in_text = True 

587 return "\n".join(parts).strip() 

588 

589 

590async def get_document_text( 

591 kb_id: str, ref: DocumentRef, max_chars: int = 60_000 

592) -> DocumentText: 

593 """Full text of *ref*. 

594 

595 Prefers the parsed chunks in the vector index (correct for PDF, Office and 

596 HTML files). Falls back to decoding the stored bytes for plain-text 

597 formats when the document has not been indexed yet. 

598 """ 

599 if ref.document_id: 

600 try: 

601 chunks = await rag_service.fetch_document_chunks(kb_id, ref.document_id) 

602 except Exception as exc: # noqa: BLE001 

603 logger.warning( 

604 "get_document_text: chunk fetch failed for %s: %s", ref.document_id, exc 

605 ) 

606 chunks = [] 

607 if chunks: 

608 # Read as a search's passages are (``passage_text``): a page of 

609 # legislation was mostly link addresses. 

610 text = passage_text.readable(_assemble(chunks)) 

611 truncated = len(text) > max_chars 

612 if truncated: 

613 text = text[:max_chars].rstrip() + "\n\n[… truncated …]" 

614 return DocumentText( 

615 ref=ref, 

616 text=text, 

617 truncated=truncated, 

618 chunk_count=len(chunks), 

619 origin="index", 

620 ) 

621 

622 # Not indexed (yet / failed): read the stored bytes and convert on demand. 

623 try: 

624 from app.util import minio_client 

625 

626 raw = minio_client.get_document(kb_id, ref.source_id or ref.original_filename) 

627 except Exception as exc: # noqa: BLE001 

628 logger.warning( 

629 "get_document_text: storage fetch failed for %s: %s", ref.display_name, exc 

630 ) 

631 raw = None 

632 if raw: 

633 from app.util import docling_client 

634 

635 ext = split_ext(ref.source_id or ref.original_filename)[1] 

636 mime = ref.mime_type or ( 

637 "text/plain" if ext in _TEXT_EXTENSIONS else "application/octet-stream" 

638 ) 

639 text = passage_text.readable( 

640 await docling_client.document_to_text(raw, ref.display_name, mime) 

641 ) 

642 if text: 

643 truncated = len(text) > max_chars 

644 if truncated: 

645 text = text[:max_chars].rstrip() + "\n\n[… truncated …]" 

646 if ref.index_status == "failed": 

647 status_note = "indexing failed" + ( 

648 f" ({ref.index_error})" if ref.index_error else "" 

649 ) 

650 else: 

651 status_note = "not indexed for search yet" 

652 return DocumentText( 

653 ref=ref, 

654 text=text, 

655 truncated=truncated, 

656 origin="storage", 

657 note=( 

658 f"Read directly from storage — {status_note}; semantic search " 

659 "will not find it." 

660 ), 

661 ) 

662 

663 reason = ( 

664 f"indexing failed ({ref.index_error})" 

665 if ref.index_status == "failed" and ref.index_error 

666 else "indexing has not completed" 

667 ) 

668 return DocumentText( 

669 ref=ref, 

670 text="", 

671 origin="unavailable", 

672 note=( 

673 f"'{ref.display_name}' exists in the knowledge base but its content could " 

674 f"not be read: {reason} and the stored file could not be converted to text." 

675 ), 

676 )