Coverage for app / services / knowledge / imports.py: 92%
159 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"""Documents imported into a file knowledge source from a URL.
3Generative knowledge setup finds a repository's documents on the web — a
4government policy, a standard, a regulator's guidance — and a person can add
5one by its link ("Add from URL"). Both land here.
7svc-core has no route to the open web: svc-ai downloads the document
8(``ai_client.fetch_document``) under the crawler's rules and hands back its
9bytes, which are stored and indexed as an upload is. The document then
10carries where it came from on every chunk (``document_payload``), so a
11citation links to the original.
13Lifecycle of one document row::
15 placeholders() index_status=importing the URL is on the source
16 │ (created with the source, or
17 │ by "Add from URL")
18 ├─ run() ok index_status=pending stored in MinIO, then indexed
19 │ by ``_index_document``
20 └─ run() no index_status=failed the reason, safe to show:
21 robots, a page, too large…
23A download runs on its own pool, after the request that asked for it has
24committed; one the process lost with a restart is failed when the source's
25documents are next listed (``expire_abandoned``).
26"""
28from __future__ import annotations
30import asyncio
31import hashlib
32import logging
33from concurrent.futures import ThreadPoolExecutor
34from dataclasses import dataclass
35from datetime import datetime, timedelta
36from typing import Any, Callable, Iterable
37from uuid import UUID, uuid4
39from sqlalchemy.orm import Session
41from app.db.postgres.models import Knowledge, KnowledgeDocument
42from app.services import ai_client
43from app.services.knowledge import file_types
44from app.util.time import aware_utcnow, utc_isoformat
46logger = logging.getLogger(__name__)
48#: The most documents one request (or one generated source) imports.
49MAX_IMPORTS_PER_SOURCE = 10
51#: A document still importing this long after its download started went
52#: with the process that was downloading it.
53ABANDONED_AFTER = timedelta(minutes=30)
54#: How long a document may wait for a worker before its download starts. The
55#: pool is two workers, and one document can take minutes (the download,
56#: then docling and the embeddings), so a queue of them outlasts
57#: ``ABANDONED_AFTER``; the clock used to run from the request and failed
58#: documents still waiting their turn. Past this, the queue went with a
59#: restart.
60QUEUED_AFTER = timedelta(hours=2)
62IMPORTING = "importing"
64#: Origins of an import, kept on the document.
65ORIGIN_GENERATION = "generation"
66ORIGIN_USER = "user"
68#: What a person reads when svc-ai could not be reached at all.
69UNREACHABLE = "Could not reach the document service. Reindex it to try again."
70ABANDONED = "The import did not finish. Reindex it to try again."
71#: What a person reads when the import failed in a way none of the above
72#: describes (the log has why).
73FAILED = "The import failed. Reindex it to try again."
75_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="knowledge-import")
78@dataclass(frozen=True)
79class DocumentRef:
80 """A document to import: its link and what is known of it already."""
82 url: str
83 title: str = ""
84 publisher: str = ""
85 published: str | None = None
86 origin: str = ORIGIN_USER
89def _known_urls(db: Session, knowledge_id: Any) -> set[str]:
90 rows = (
91 db.query(KnowledgeDocument.document_metadata)
92 .filter(KnowledgeDocument.knowledge_id == knowledge_id)
93 .all()
94 )
95 urls: set[str] = set()
96 for (meta,) in rows:
97 meta = meta or {}
98 urls.update(u for u in (meta.get("source_url"), meta.get("requested_url")) if u)
99 return urls
102def placeholders(
103 db: Session,
104 knowledge: Knowledge,
105 refs: Iterable[DocumentRef],
106 *,
107 folder_path: str = "",
108 existing: bool = True,
109) -> tuple[list[KnowledgeDocument], list[dict]]:
110 """One ``importing`` row per document to fetch, added (not committed),
111 and the URLs skipped with why — one already in the source, or a repeat.
113 ``existing`` False skips the lookup, for a source created in the same
114 transaction (it holds nothing yet).
115 """
116 known = _known_urls(db, knowledge.id) if existing else set()
117 now = utc_isoformat(aware_utcnow())
118 docs: list[KnowledgeDocument] = []
119 skipped: list[dict] = []
120 for ref in refs:
121 if ref.url in known:
122 skipped.append({"url": ref.url, "reason": "Already in this source."})
123 continue
124 known.add(ref.url)
125 meta = {
126 "index_status": IMPORTING,
127 "source_url": ref.url,
128 "requested_url": ref.url,
129 "import_origin": ref.origin,
130 "import_requested_at": now,
131 "folder_path": folder_path,
132 }
133 for key, value in (
134 ("title", ref.title),
135 ("publisher", ref.publisher),
136 ("published", ref.published),
137 ):
138 if value:
139 meta[key] = value
140 doc = KnowledgeDocument(
141 id=uuid4(),
142 knowledge_id=knowledge.id,
143 source_id=ref.url,
144 folder_path=folder_path,
145 document_metadata=meta,
146 )
147 db.add(doc)
148 docs.append(doc)
149 return docs, skipped
152def submit(document_ids: Iterable[UUID | str], actor_user_id: Any) -> None:
153 """Start each import on the import pool. Called after the rows commit."""
154 for document_id in document_ids:
155 _executor.submit(
156 run,
157 document_id,
158 actor_user_id=str(actor_user_id) if actor_user_id else None,
159 )
162def _fail(session: Session, doc: KnowledgeDocument, message: str) -> None:
163 doc.document_metadata = {
164 **(doc.document_metadata or {}),
165 "index_status": "failed",
166 "index_error": message,
167 }
168 session.commit()
171def run(
172 document_id: UUID | str,
173 *,
174 actor_user_id: str | None = None,
175 session_factory: Callable[[], Session] | None = None,
176 fetch: Callable[[str], ai_client.FetchedDocument] | None = None,
177 store: Callable[[str, str, bytes, str], str] | None = None,
178 index: Callable[..., Any] | None = None,
179) -> None:
180 """Download one ``importing`` document, store it and index it. Never
181 raises: what went wrong is on the row, safe to show.
183 In the source's workspace (svc-ai names it on its traces), and indexed
184 as ``actor_user_id``'s work — the indexing budget asks, as for an
185 upload.
186 """
187 from app.db.postgres.engine import SessionLocal
188 from app.router.app.knowledge.router import _index_document, document_payload
189 from app.services import workspace as workspace_service
190 from app.util import minio_client
192 session = (session_factory or SessionLocal)()
193 try:
194 doc = session.get(KnowledgeDocument, UUID(str(document_id)))
195 meta = dict(doc.document_metadata or {}) if doc is not None else {}
196 if doc is None or meta.get("index_status") != IMPORTING:
197 return
198 knowledge = session.get(Knowledge, doc.knowledge_id)
199 if knowledge is None:
200 return
201 # From here the abandon clock runs (``expire_abandoned``).
202 meta["import_started_at"] = utc_isoformat(aware_utcnow())
203 doc.document_metadata = meta
204 session.commit()
205 home = workspace_service.home_of(session, knowledge)
206 with ai_client.in_workspace(home.key if home is not None else None):
207 try:
208 fetched = (fetch or ai_client.fetch_document)(meta["source_url"])
209 except ai_client.DocumentFetchRefused as exc:
210 _fail(session, doc, exc.message)
211 return
212 except ai_client.AIServiceError as exc:
213 cause = exc.__cause__
214 status = getattr(getattr(cause, "response", None), "status_code", None)
215 logger.warning(
216 "Document service failed import %s (%s)",
217 doc.id,
218 f"HTTP {status}" if status else type(cause or exc).__name__,
219 )
220 _fail(session, doc, UNREACHABLE)
221 return
223 ext = file_types.extension_for(fetched.mime_type, fetched.filename)
224 if ext is None:
225 _fail(
226 session, doc, "The link is not a document a file source can hold."
227 )
228 return
229 if len(fetched.content) > file_types.MAX_IMPORT_BYTES:
230 limit = file_types.MAX_IMPORT_BYTES // (1024 * 1024)
231 _fail(session, doc, f"The document is larger than {limit} MB.")
232 return
234 name = file_types.with_extension(
235 file_types.safe_filename(fetched.filename), ext
236 )
237 name = file_types.unique_object_name(str(knowledge.id), name)
238 try:
239 stored = (store or minio_client.upload)(
240 str(knowledge.id), name, fetched.content, fetched.mime_type
241 )
242 except Exception:
243 logger.exception("Could not store imported document %s", doc.id)
244 _fail(session, doc, "The document could not be stored. Try again.")
245 return
247 meta.update(
248 {
249 "original_filename": fetched.filename,
250 "size_bytes": len(fetched.content),
251 "sha256": hashlib.sha256(fetched.content).hexdigest(),
252 "mime_type": fetched.mime_type,
253 "minio_object": stored,
254 "source_url": fetched.url,
255 "fetched_at": utc_isoformat(aware_utcnow()),
256 "index_status": "pending",
257 "index_error": None,
258 }
259 )
260 if fetched.last_modified:
261 meta["last_modified"] = fetched.last_modified
262 doc.source_id = name
263 doc.document_metadata = meta
264 session.commit()
266 asyncio.run(
267 (index or _index_document)(
268 document_id=str(doc.id),
269 knowledge_id=str(knowledge.id),
270 content=fetched.content,
271 filename=fetched.filename,
272 mime_type=fetched.mime_type,
273 file_extension=ext,
274 source_id=name,
275 folder_path=doc.folder_path or "",
276 actor_user_id=actor_user_id,
277 extra_payload=document_payload(meta),
278 )
279 )
280 except Exception:
281 logger.exception("Import of document %s failed unexpectedly", document_id)
282 session.rollback()
283 _fail_if_importing(session, document_id)
284 finally:
285 session.close()
288def _fail_if_importing(session: Session, document_id: UUID | str) -> None:
289 """Record an import that broke before indexing took it over, rather than
290 leave it ``importing`` until it reads as abandoned. Indexing records its
291 own failures, so a document past ``importing`` is left as it says."""
292 try:
293 doc = session.get(KnowledgeDocument, UUID(str(document_id)))
294 if (
295 doc is not None
296 and (doc.document_metadata or {}).get("index_status") == IMPORTING
297 ):
298 _fail(session, doc, FAILED)
299 except Exception:
300 logger.exception("Could not record the failed import of %s", document_id)
301 session.rollback()
304def expire_abandoned(
305 db: Session, docs: Iterable[KnowledgeDocument], now: datetime | None = None
306) -> bool:
307 """Fail every document still importing :data:`ABANDONED_AFTER` after its
308 download started, or :data:`QUEUED_AFTER` after it was asked for when it
309 never started — its download, or its place in the queue, went with a
310 restart. True when any changed."""
311 now = now or aware_utcnow()
312 changed = False
313 for doc in docs:
314 meta = doc.document_metadata or {}
315 if meta.get("index_status") != IMPORTING:
316 continue
317 started = _when(meta.get("import_started_at"))
318 if started is not None:
319 if now - started <= ABANDONED_AFTER:
320 continue
321 else:
322 asked = _when(meta.get("import_requested_at"))
323 if asked is not None and now - asked <= QUEUED_AFTER:
324 continue
325 doc.document_metadata = {
326 **meta,
327 "index_status": "failed",
328 "index_error": ABANDONED,
329 }
330 changed = True
331 if changed:
332 db.commit()
333 return changed
336def _when(value: Any) -> datetime | None:
337 try:
338 return datetime.fromisoformat(str(value)) if value else None
339 except ValueError:
340 return None
343def requeue(doc: KnowledgeDocument) -> bool:
344 """Put a document whose stored file is missing but whose source is known
345 back to ``importing`` (a reindex re-imports it). False when it has no
346 source to import from."""
347 meta = doc.document_metadata or {}
348 if not meta.get("source_url"):
349 return False
350 doc.document_metadata = {
351 **meta,
352 "index_status": IMPORTING,
353 "index_error": None,
354 "import_requested_at": utc_isoformat(aware_utcnow()),
355 "import_started_at": None,
356 }
357 return True