Coverage for app / services / knowledge / reindex.py: 85%
282 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2The search-index rebuild after the embedding model changes.
4Knowledge is searched by comparing vectors, and vectors from two embedding
5models cannot be compared: Titan's have 1024 dimensions, OpenAI's 1536, and
6even two models of one size answer in different spaces. So when svc-ai's
7embedding model changes (``INFERENCE_BACKEND``, ``app/services/embeddings.py``
8there), every collection built with the old one is rebuilt: recreated empty
9at the new size, stamped with the new model, and every document re-embedded
10from what is already stored — an upload's file, a web page's newest snapshot,
11the guide on disk. Nothing is fetched again.
13Until a collection is rebuilt its documents wait (``pending``): svc-ai skips
14its dense search rather than query it with the wrong vectors, and indexing
15into it is refused before anything is spent
16(``qdrant_client.CollectionNeedsRebuild``).
18The job is idempotent and resumable because it keeps no state of its own:
19each tick asks Qdrant which collections are stale and the documents which
20embedding model made their vectors (``document_metadata.embedding``). A crash
21between marking a collection's documents and recreating it leaves the
22collection stale (the next tick recreates it); a crash after leaves it
23current with documents still pending (the next tick carries on).
25Gentle by design: a tick works for ``BUDGET_S`` and stops; it waits while
26the deployment has spent ``SPEND_SHARE`` of its ceiling; it probes the new
27model before replacing anything, so a deployment that may not call it (Bedrock
28model access) keeps its old index rather than losing it; and a document that
29fails ``MAX_ATTEMPTS`` times is left alone.
30"""
32from __future__ import annotations
34import asyncio
35import logging
36import time
37from abc import ABC, abstractmethod
38from dataclasses import dataclass, field
39from typing import Any, ClassVar
41from sqlalchemy import func
42from sqlalchemy.orm import Session
44from app.db.postgres.enums import BackgroundEnum
45from app.db.postgres.models import Knowledge, KnowledgeCrawl, KnowledgeDocument
46from app.services import ai_client
47from app.util import embedding, qdrant_client
48from app.util.embedding import LEGACY, EmbeddingIdentity
50logger = logging.getLogger(__name__)
52#: Seconds of work per tick; the job runs every minute, so a large index is
53#: rebuilt over several ticks and never holds up the scheduler.
54BUDGET_S = 45.0
55#: The share of the deployment's spending ceiling the rebuild may reach.
56SPEND_SHARE = 0.9
57#: Attempts per document per embedding model before it is left alone.
58MAX_ATTEMPTS = 3
59#: Consecutive document failures that end a tick early.
60MAX_CONSECUTIVE_FAILURES = 2
62#: What a document says while it waits for its collection's rebuild.
63REINDEXING = "Re-indexing for the new search model."
65#: Documents the rebuild never touches: a gone web page's chunks were
66#: removed on purpose, and a document still being imported from a URL has
67#: nothing stored to rebuild from yet (``knowledge/imports.py``).
68_LEFT_ALONE = frozenset({"not_indexed", "importing"})
71def _nothing_stored_from_a_link(meta: dict) -> bool:
72 """An import from a URL that never stored its download — it failed
73 before that (robots.txt, a type a file source cannot hold, the document
74 service down). It has nothing to rebuild from: its reindex is a fresh
75 import, a person's call. The rebuild used to take it, find no stored
76 file and overwrite its reason with "upload it again"."""
77 return bool(meta.get("source_url")) and not meta.get("minio_object")
80def _meta(doc: KnowledgeDocument) -> dict:
81 return dict(doc.document_metadata or {})
84def document_key(doc: KnowledgeDocument) -> str:
85 """The embedding model a document's vectors came from — the platform's
86 only one before documents recorded it."""
87 return _meta(doc).get("embedding") or LEGACY.key
90def _attempts(doc: KnowledgeDocument, identity: EmbeddingIdentity) -> int:
91 return int((_meta(doc).get("reindex_attempts") or {}).get(identity.key, 0))
94def _count_attempt(doc: KnowledgeDocument, identity: EmbeddingIdentity) -> None:
95 meta = _meta(doc)
96 attempts = dict(meta.get("reindex_attempts") or {})
97 attempts[identity.key] = attempts.get(identity.key, 0) + 1
98 meta["reindex_attempts"] = attempts
99 doc.document_metadata = meta
102def is_stale(doc: KnowledgeDocument, identity: EmbeddingIdentity) -> bool:
103 """Whether a document still needs vectors from ``identity``. Never one a
104 budget held: it was never indexed, so the rebuild restores nothing by
105 indexing it, and it waits for its budget (``knowledge/held.py``)."""
106 from app.services.knowledge import held
108 meta = _meta(doc)
109 return (
110 meta.get("index_status") not in _LEFT_ALONE
111 and not _nothing_stored_from_a_link(meta)
112 and not held.is_held(doc)
113 and document_key(doc) != identity.key
114 and _attempts(doc, identity) < MAX_ATTEMPTS
115 )
118# ── Sources: how each kind of knowledge is re-indexed ────────────────────────
121@dataclass
122class Outcome:
123 """What re-indexing one knowledge base's documents came to this tick."""
125 indexed: int = 0
126 failed: int = 0
127 #: A refusal a person must act on (the spending ceiling, model access).
128 refusal: str | None = None
129 #: The tick's time ran out before every document was done.
130 out_of_time: bool = False
133class Source(ABC):
134 """One kind of knowledge, and how its stored content is re-embedded."""
136 #: Lower runs first.
137 priority: ClassVar[int] = 1
139 @classmethod
140 @abstractmethod
141 def handles(cls, knowledge: Knowledge) -> bool: ...
143 @abstractmethod
144 def reindex(
145 self,
146 db: Session,
147 knowledge: Knowledge,
148 docs: list[KnowledgeDocument],
149 identity: EmbeddingIdentity,
150 deadline: float,
151 ) -> Outcome: ...
153 def busy(self, db: Session, knowledge: Knowledge) -> bool:
154 """Whether to leave the source for a later tick."""
155 return False
158_SOURCES: list[type[Source]] = []
161def register(cls: type[Source]) -> type[Source]:
162 _SOURCES.append(cls)
163 return cls
166def source_for(knowledge: Knowledge) -> Source:
167 for cls in sorted(_SOURCES, key=lambda c: c.priority):
168 if cls.handles(knowledge):
169 return cls()
170 return UploadedFiles()
173def _outcome_of(
174 db: Session, doc: KnowledgeDocument, identity: EmbeddingIdentity
175) -> str:
176 """``indexed``, ``refused`` or ``failed``, read back from the row the
177 indexing wrote (in a session of its own)."""
178 db.refresh(doc)
179 meta = _meta(doc)
180 if meta.get("index_status") == "indexed" and meta.get("embedding") == identity.key:
181 return "indexed"
182 if meta.get("index_refusal"):
183 return "refused"
184 return "failed"
187def _settle(
188 db: Session,
189 doc: KnowledgeDocument,
190 identity: EmbeddingIdentity,
191 outcome: Outcome,
192 streak: list[int],
193) -> bool:
194 """Count one document's result; True when the tick should stop."""
195 result = _outcome_of(db, doc, identity)
196 if result == "indexed":
197 outcome.indexed += 1
198 streak[0] = 0
199 return False
200 if result == "refused":
201 outcome.refusal = str(_meta(doc).get("index_error") or "refused")
202 return True
203 outcome.failed += 1
204 _count_attempt(doc, identity)
205 db.commit()
206 streak[0] += 1
207 return streak[0] >= MAX_CONSECUTIVE_FAILURES
210def _written_source(knowledge: Knowledge):
211 """The written built-in source ``knowledge`` is, or None."""
212 from app.services.system_resources.knowledge import (
213 WrittenSourceSpec,
214 source_spec,
215 )
217 spec = source_spec(getattr(knowledge, "id", None))
218 return spec if isinstance(spec, WrittenSourceSpec) else None
221@register
222class GuideSource(Source):
223 """Knowledge CHAIN-R writes — CHAINR Bot's user guide and every other
224 written built-in source: re-indexed from disk by its own sync."""
226 priority = 0
228 @classmethod
229 def handles(cls, knowledge: Knowledge) -> bool:
230 return _written_source(knowledge) is not None
232 def reindex(self, db, knowledge, docs, identity, deadline) -> Outcome:
233 from app.services import system_resources
235 for doc in docs:
236 doc.document_metadata = {
237 **_meta(doc),
238 "index_status": "pending",
239 "index_error": REINDEXING,
240 }
241 db.commit()
242 # Re-indexes every document of it not marked indexed; its spend is
243 # the platform's (a built-in source has no owner).
244 synced = system_resources.sync_written(db, [_written_source(knowledge)])
245 outcome = Outcome()
246 for doc in docs:
247 result = _outcome_of(db, doc, identity)
248 if result == "indexed":
249 outcome.indexed += 1
250 elif result == "refused":
251 outcome.refusal = str(_meta(doc).get("index_error") or "refused")
252 else:
253 outcome.failed += 1
254 _count_attempt(doc, identity)
255 db.commit()
256 if synced.failed and not outcome.failed:
257 outcome.failed = len(synced.failed)
258 return outcome
261@register
262class WebsitePages(Source):
263 """A website source (the built-in News included): each page's newest
264 stored snapshot is re-embedded; nothing is fetched."""
266 @classmethod
267 def handles(cls, knowledge: Knowledge) -> bool:
268 from app.services.knowledge import web_crawl
270 return knowledge.source_type == web_crawl.SOURCE_TYPE
272 def busy(self, db: Session, knowledge: Knowledge) -> bool:
273 from app.services.knowledge.web_crawl import CrawlStatus
275 # A crawl in progress indexes its own pages; re-embedding beside it
276 # could leave a page one version behind.
277 return (
278 db.query(KnowledgeCrawl.id)
279 .filter(
280 KnowledgeCrawl.knowledge_id == knowledge.id,
281 KnowledgeCrawl.status == CrawlStatus.running.value,
282 )
283 .first()
284 is not None
285 )
287 def reindex(self, db, knowledge, docs, identity, deadline) -> Outcome:
288 from app.router.app.knowledge.router import _ledger_indexing
289 from app.services import workspace as workspace_service
290 from app.services.knowledge import web_crawl
291 from app.services.knowledge.web_config import parse_web_config
292 from app.util import minio_client
294 outcome = Outcome()
295 try:
296 config = parse_web_config(knowledge.source_config)
297 except ValueError as exc:
298 logger.warning("Rebuild skips %s: invalid settings (%s)", knowledge.id, exc)
299 outcome.failed = len(docs)
300 for doc in docs:
301 _count_attempt(doc, identity)
302 db.commit()
303 return outcome
304 storage = web_crawl.PageStorage()
305 home = workspace_service.home_of(db, knowledge)
306 streak = [0]
307 with (
308 ai_client.in_workspace(home.key if home is not None else None),
309 ai_client.usage_capture() as used,
310 ai_client.attributed(knowledge.owner_user_id, knowledge_id=knowledge.id),
311 ):
312 try:
313 for doc in docs:
314 if time.monotonic() > deadline:
315 outcome.out_of_time = True
316 break
317 version = web_crawl.latest_version(db, doc)
318 markdown = (
319 minio_client.read_named(version.markdown_object)
320 if version is not None
321 else None
322 )
323 if version is None or markdown is None:
324 doc.document_metadata = {
325 **_meta(doc),
326 "index_status": "failed",
327 "index_error": "No stored snapshot of this page; it is "
328 "indexed again on the next crawl.",
329 }
330 db.commit()
331 if _settle(db, doc, identity, outcome, streak):
332 break
333 continue
334 web_crawl.index_page_version(
335 storage,
336 str(knowledge.id),
337 config,
338 doc,
339 version,
340 markdown.decode("utf-8", errors="replace"),
341 )
342 db.commit()
343 if _settle(db, doc, identity, outcome, streak):
344 break
345 finally:
346 # Owner spend on the ledger, as indexing; a built-in source
347 # has no owner, and its spend is the platform's.
348 _ledger_indexing(str(knowledge.id), used)
349 return outcome
352class UploadedFiles(Source):
353 """Uploaded documents (any source whose documents are stored files):
354 each is parsed and embedded again from its stored file, through the same
355 routine an upload uses, which ledgers its own spend."""
357 priority = 2
359 @classmethod
360 def handles(cls, knowledge: Knowledge) -> bool:
361 return True
363 def reindex(self, db, knowledge, docs, identity, deadline) -> Outcome:
364 from app.router.app.knowledge.router import (
365 STORED_FILE_MISSING,
366 _index_document,
367 stored_index_kwargs,
368 )
369 from app.services import workspace as workspace_service
371 outcome = Outcome()
372 streak = [0]
373 home = workspace_service.home_of(db, knowledge)
374 with ai_client.in_workspace(home.key if home is not None else None):
375 for doc in docs:
376 if time.monotonic() > deadline:
377 outcome.out_of_time = True
378 break
379 kwargs = stored_index_kwargs(knowledge.id, doc)
380 if kwargs is None:
381 doc.document_metadata = {
382 **_meta(doc),
383 "index_status": "failed",
384 "index_error": STORED_FILE_MISSING,
385 }
386 db.commit()
387 else:
388 # The platform's doing, restoring search a person
389 # already had: ledgered, never refused by a budget.
390 asyncio.run(_index_document(**kwargs, gated=False))
391 if _settle(db, doc, identity, outcome, streak):
392 break
393 return outcome
396# ── The tick ─────────────────────────────────────────────────────────────────
399@dataclass
400class TickResult:
401 started: bool
402 detail: str
403 failed: bool = False
404 #: Per knowledge base this tick touched (tests read it).
405 rebuilt: list[str] = field(default_factory=list)
408def _knowledge_with_documents(db: Session) -> list[Knowledge]:
409 ids = [
410 row[0]
411 for row in db.query(KnowledgeDocument.knowledge_id)
412 .group_by(KnowledgeDocument.knowledge_id)
413 .having(func.count(KnowledgeDocument.id) > 0)
414 .all()
415 ]
416 if not ids:
417 return []
418 rows = db.query(Knowledge).filter(Knowledge.id.in_(ids)).all()
419 return sorted(rows, key=lambda k: (source_for(k).priority, str(k.created_at or "")))
422def _documents(db: Session, knowledge: Knowledge) -> list[KnowledgeDocument]:
423 return (
424 db.query(KnowledgeDocument)
425 .filter(KnowledgeDocument.knowledge_id == knowledge.id)
426 .order_by(KnowledgeDocument.id)
427 .all()
428 )
431def _spend_hold() -> str | None:
432 from app.services.evaluation import benchmark
434 return benchmark.over_spend_share(
435 ai_client.spend_status(), share=SPEND_SHARE, who="the search-index rebuild"
436 )
439def _record(
440 db: Session,
441 knowledge: Knowledge,
442 outcome: Outcome,
443 left: int,
444 from_key: str,
445 identity: EmbeddingIdentity,
446 started_at: Any,
447) -> None:
448 from app.services import background_activity
450 done = outcome.indexed
451 if outcome.refusal:
452 summary = f"Search index rebuild paused: {outcome.refusal}"
453 elif left:
454 summary = (
455 f"Re-indexed {done} document(s) for the new search model; {left} left."
456 )
457 else:
458 summary = f"Search index rebuilt for the new search model: {done} document(s)."
459 background_activity.record(
460 db,
461 kind=BackgroundEnum.Kind.knowledge_reindex,
462 trigger=BackgroundEnum.Trigger.model_changed,
463 status=(
464 BackgroundEnum.Status.failed
465 if outcome.refusal or (outcome.failed and not done)
466 else BackgroundEnum.Status.ok
467 ),
468 summary=summary,
469 owner=knowledge,
470 subject_type="knowledge",
471 subject_id=knowledge.id,
472 subject_name=knowledge.name,
473 detail={
474 "documents": done,
475 "failed": outcome.failed,
476 "left": left,
477 "from_key": from_key,
478 "to_key": identity.key,
479 },
480 error=outcome.refusal,
481 started_at=started_at,
482 )
485def tick(db: Session, *, budget_s: float = BUDGET_S) -> TickResult:
486 """Rebuild what the current embedding model needs, for up to
487 ``budget_s`` seconds. Never raises for one knowledge base's failure."""
488 from app.services.knowledge import held
489 from app.util.time import aware_utcnow
491 identity = embedding.active(refresh=True)
492 if not identity.available:
493 return TickResult(
494 False,
495 f"The search model ({identity.model}) cannot be called on this "
496 "deployment: add `amazon` to BEDROCK_MODEL_ACCESS.",
497 failed=True,
498 )
500 plan: list[tuple[Knowledge, str, list[KnowledgeDocument]]] = []
501 for knowledge in _knowledge_with_documents(db):
502 try:
503 state = qdrant_client.state(str(knowledge.id), identity)
504 except Exception as exc: # noqa: BLE001 — Qdrant unreachable: try later
505 return TickResult(
506 False, f"Qdrant could not be read: {exc}"[:300], failed=True
507 )
508 docs = _documents(db, knowledge)
509 if state == qdrant_client.STALE:
510 todo = [
511 d
512 for d in docs
513 if _meta(d).get("index_status") not in _LEFT_ALONE
514 and not held.is_held(d)
515 ]
516 else:
517 todo = [d for d in docs if is_stale(d, identity)]
518 if state == qdrant_client.STALE or todo:
519 plan.append((knowledge, state, todo))
520 if not plan:
521 return TickResult(False, f"Every search index is built with {identity.model}.")
523 hold = _spend_hold()
524 if hold:
525 return TickResult(False, f"Waiting: {hold}.")
527 if any(state == qdrant_client.STALE for _, state, _ in plan):
528 # Prove the new model answers before replacing anything: a
529 # deployment that may not call it keeps the index it has.
530 try:
531 embedding.embed_texts(["search index rebuild"])
532 except (ai_client.AIServiceError, embedding.EmbeddingError) as exc:
533 return TickResult(
534 False,
535 f"The search model could not be reached, so nothing was "
536 f"replaced: {getattr(exc, 'user_message', exc)}"[:500],
537 failed=True,
538 )
540 deadline = time.monotonic() + budget_s
541 result = TickResult(True, "")
542 total_done = total_left = 0
543 for knowledge, state, todo in plan:
544 if time.monotonic() > deadline:
545 break
546 source = source_for(knowledge)
547 if source.busy(db, knowledge):
548 continue
549 started_at = aware_utcnow()
550 from_key = qdrant_client.collection_key(str(knowledge.id)) or LEGACY.key
551 if state == qdrant_client.STALE:
552 for doc in todo:
553 doc.document_metadata = {
554 **_meta(doc),
555 "index_status": "pending",
556 "index_error": REINDEXING,
557 }
558 db.commit()
559 qdrant_client.recreate_collection(str(knowledge.id), identity)
560 try:
561 outcome = source.reindex(db, knowledge, todo, identity, deadline)
562 except Exception as exc: # noqa: BLE001 — one source never stops the rest
563 logger.exception("Rebuilding %s failed", knowledge.id)
564 db.rollback()
565 outcome = Outcome(failed=1)
566 result.failed = True
567 result.detail = f"{type(exc).__name__}: {exc}"[:300]
568 left = sum(1 for d in _documents(db, knowledge) if is_stale(d, identity))
569 _record(db, knowledge, outcome, left, from_key, identity, started_at)
570 db.commit()
571 result.rebuilt.append(str(knowledge.id))
572 total_done += outcome.indexed
573 total_left += left
574 if outcome.refusal:
575 result.failed = True
576 result.detail = f"Paused: {outcome.refusal}"[:500]
577 return result
578 if not result.rebuilt:
579 return TickResult(False, "Every source due a rebuild is being crawled; later.")
580 if not result.detail:
581 result.detail = (
582 f"Re-indexed {total_done} document(s) in {len(result.rebuilt)} "
583 f"knowledge base(s) for {identity.model}"
584 + (f"; {total_left} left." if total_left else ".")
585 )
586 return result
589def guide_pending(db: Session) -> bool:
590 """Whether CHAINR Bot's guide is still waiting for vectors from the
591 current model — the benchmark waits rather than score an empty index.
592 False when it cannot tell."""
593 from app.services.system_resources.definition import GUIDE_KNOWLEDGE
595 try:
596 identity = embedding.active()
597 except embedding.EmbeddingError:
598 return False
599 docs = (
600 db.query(KnowledgeDocument)
601 .filter(KnowledgeDocument.knowledge_id == GUIDE_KNOWLEDGE.id)
602 .all()
603 )
604 return any(is_stale(d, identity) for d in docs)