Coverage for app / knowledge / discovery.py: 92%
212 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""Discovery: the real sources a generated knowledge repository is built on.
3Generative knowledge setup used to propose empty stubs — a model inventing a
4URL would point the platform at an address nobody chose. It now finds them:
61. **plan** — a model writes the searches that would find the material
7 (``DiscoveryPlan``: official, primary sources; sites to crawl and
8 documents to keep);
92. **search** — they run through the platform's web search (Brave, else
10 DuckDuckGo), filtered by the safety policy and ranked, de-duplicated
11 across searches and capped per site (:func:`search`);
123. **check** — each result is probed, never downloaded whole: robots.txt
13 for CHAINR's crawler, the public https guard on every hop, its status
14 and final address, and what it is — a page, a feed or a document
15 (:func:`check`).
17What survives is offered to the design call by handle, and the model picks
18from it: it never writes a URL. svc-core runs the steps as separate calls
19(``services/knowledge/generation_job.py``), so each is well inside a
20request's time and the person sees which one the run is on.
21"""
23from __future__ import annotations
25import asyncio
26import functools
27import html
28import logging
29import re
30from dataclasses import dataclass, field
31from typing import Literal
33from pydantic import Field, OnErrorOmit, create_model, field_validator
35from app.common.settings import get_settings
36from app.knowledge.web import (
37 DOCUMENT_IMPORT_MIMES,
38 RobotsCache,
39 _defaults as _page_defaults,
40 canonical_url,
41 filename_from,
42 sniff_mime,
43)
44from app.knowledge.web_extract import classify_link
45from app.services.structured_output import ModelOutput
46from app.tools.web.fetch import FetchError, ProbedResource, UnsafeUrlError, UrlFetcher
47from app.tools.web.models import SafeSearch, SearchRequest, SearchType
48from app.tools.web.policy import DomainPolicy, canonical_key, hostname_of
49from app.tools.web.providers import ProviderConfigError, build_provider_chain
50from app.tools.web.search import (
51 SearchUnavailableError,
52 WebSearchService,
53 get_search_cache,
54 permitted_ranked,
55)
56from app.util import vocab
58logger = logging.getLogger(__name__)
60#: What a search looks for — the model chooses one per search.
61LOOKING_FOR: dict[str, str] = {
62 "sites": (
63 "the official website pages that state and maintain the material — a "
64 "regulator's guidance hub, a programme's home, a law's official page; "
65 "kept current by a crawl"
66 ),
67 "documents": (
68 "published documents to keep — the text of a law, a government policy, "
69 "a standard, a framework or a report as a PDF"
70 ),
71 "feeds": (
72 "the RSS or Atom feeds and news or updates pages a publisher keeps "
73 "current — a regulator's news feed, a programme's announcements; read "
74 "often, newest first"
75 ),
76}
78#: What a checked result is, by what its address answered with.
79CANDIDATE_KINDS: dict[str, str] = {
80 "page": "a web page, for a website source",
81 "feed": "an RSS or Atom feed, for a website source",
82 "document": "a PDF or office document, for a file source",
83}
85Kind = Literal["page", "feed", "document"]
87#: Searches one plan may make.
88MAX_SEARCHES = 8
89#: Results kept from each search, after the safety filter and ranking.
90RESULTS_PER_SEARCH = 8
91#: Results kept from one site across every search.
92MAX_PER_HOST = 3
93#: Results checked at most.
94MAX_CHECK = 32
95#: Added by the server to a search for documents. Brave documents the
96#: operator; DuckDuckGo's own index honours it, its other engines read it as
97#: a word — so whether a result *is* a document is the check's to decide.
98DOCUMENT_OPERATOR = "filetype:pdf"
99#: Added by the server to a search for feeds that names none: what a
100#: publisher calls the page its feed is on.
101FEED_WORDS = "RSS feed"
102#: Searches running at once (DuckDuckGo limits bursts).
103SEARCH_CONCURRENCY = 3
104#: Probes running at once, and per site.
105CHECK_CONCURRENCY = 6
106CHECK_PER_HOST = 2
107#: How long the whole check may take.
108CHECK_BUDGET_S = 30.0
109#: The most of a body a probe reads.
110PROBE_HEAD_BYTES = 65_536
111#: The longest query a plan may write.
112MAX_QUERY_CHARS = 200
114#: What a document a file source can hold is, by its bytes. Text documents
115#: are left out: a result that answers with text is a page or a feed.
116_DOCUMENT_TYPES = frozenset(
117 mime for mime in DOCUMENT_IMPORT_MIMES if not mime.startswith("text/")
118) - {"application/json", "application/xml"}
121# ---------------------------------------------------------------------------
122# Plan — the one model call of discovery
123# ---------------------------------------------------------------------------
126class PlannedSearch(ModelOutput):
127 """One web search that would find material the repository needs."""
129 query: str = Field(description="The search, as a person would type it")
130 looking_for: Literal[vocab.values(LOOKING_FOR)] = Field( # type: ignore[valid-type]
131 description="What the search should find"
132 )
134 @field_validator("query")
135 @classmethod
136 def _bounded(cls, value: str) -> str:
137 value = " ".join(str(value).split())
138 if not value:
139 raise ValueError("a search needs words")
140 return value[:MAX_QUERY_CHARS]
143class DiscoveryPlan(ModelOutput):
144 """The searches the model would run to find the knowledge described."""
146 searches: list[OnErrorOmit[PlannedSearch]] = Field(
147 default=[], description=f"Between 3 and {MAX_SEARCHES} web searches"
148 )
151@functools.lru_cache(maxsize=8)
152def plan_schema(looking_for: tuple[str, ...]) -> type[DiscoveryPlan]:
153 """``DiscoveryPlan`` whose searches may look for ``looking_for`` only —
154 the kinds of search a kind of knowledge needs
155 (``categories.Behaviour.looking_for``). Every kind: ``DiscoveryPlan``."""
156 kinds = vocab.members(LOOKING_FOR, looking_for)
157 if set(kinds) == set(LOOKING_FOR):
158 return DiscoveryPlan
159 search = create_model(
160 f"PlannedSearch_{'_'.join(kinds)}",
161 __base__=PlannedSearch,
162 __module__=__name__,
163 looking_for=(
164 Literal[kinds], # type: ignore[valid-type]
165 Field(description="What the search should find"),
166 ),
167 )
168 return create_model(
169 f"DiscoveryPlan_{'_'.join(kinds)}",
170 __base__=DiscoveryPlan,
171 __module__=__name__,
172 searches=(
173 list[OnErrorOmit[search]], # type: ignore[valid-type]
174 Field(default=[], description=f"Between 3 and {MAX_SEARCHES} web searches"),
175 ),
176 )
179# ---------------------------------------------------------------------------
180# Search
181# ---------------------------------------------------------------------------
184@dataclass
185class Found:
186 """A search result worth checking."""
188 url: str
189 title: str
190 snippet: str = ""
191 host: str = ""
192 published: str | None = None
193 publisher: str | None = None
194 looking_for: str = "sites"
197@dataclass
198class SearchOutcome:
199 found: list[Found] = field(default_factory=list)
200 made: int = 0
201 failed: int = 0
202 provider: str | None = None
203 #: Safe to show: why nothing could be searched at all.
204 unavailable: str | None = None
207def _service() -> WebSearchService:
208 return WebSearchService(
209 build_provider_chain(get_settings(), {}), cache=get_search_cache()
210 )
213def _policy() -> DomainPolicy:
214 # No allowlist — the person chose the topic, not the sites — but the
215 # safety blocklists (shorteners, disposable TLDs) still apply.
216 return DomainPolicy(allowed_domains=[], blocked_domains=[], require_https=True)
219async def search(
220 searches: list[PlannedSearch],
221 *,
222 service: WebSearchService | None = None,
223 policy: DomainPolicy | None = None,
224) -> SearchOutcome:
225 """Run a plan's searches and merge what they found: tracking stripped,
226 the safety policy applied, each search's results ranked, then taken in
227 turn across the searches (so one broad search cannot crowd out the
228 rest), de-duplicated by address and capped per site."""
229 searches = searches[:MAX_SEARCHES]
230 if not searches:
231 return SearchOutcome()
232 try:
233 service = service or _service()
234 except ProviderConfigError:
235 return SearchOutcome(
236 made=len(searches),
237 failed=len(searches),
238 unavailable="Web search is not configured on this deployment.",
239 )
240 policy = policy or _policy()
241 settings = get_settings()
242 gate = asyncio.Semaphore(SEARCH_CONCURRENCY)
243 provider: list[str] = []
245 async def one(planned: PlannedSearch) -> list[Found] | None:
246 query = planned.query
247 if planned.looking_for == "documents" and DOCUMENT_OPERATOR not in query:
248 query = f"{query} {DOCUMENT_OPERATOR}"
249 if planned.looking_for == "feeds" and not re.search(
250 r"\b(rss|atom|feed)\b", query, re.IGNORECASE
251 ):
252 query = f"{query} {FEED_WORDS}"
253 request = SearchRequest(
254 query=query,
255 search_type=SearchType.TEXT,
256 count=RESULTS_PER_SEARCH + 4,
257 country=settings.web_search_country,
258 language=settings.web_search_language,
259 safesearch=SafeSearch.MODERATE,
260 )
261 async with gate:
262 try:
263 response = await service.search(request)
264 except SearchUnavailableError:
265 return None
266 except Exception: # noqa: BLE001 — one search never fails the rest
267 logger.warning("[discovery] a search failed unexpectedly")
268 return None
269 if response.provider:
270 provider.append(response.provider)
271 return [
272 Found(
273 url=r.url,
274 title=r.title,
275 snippet=r.snippet,
276 host=hostname_of(r.url).removeprefix("www."),
277 published=r.published,
278 publisher=r.source,
279 looking_for=planned.looking_for,
280 )
281 for r in permitted_ranked(response.results, policy, RESULTS_PER_SEARCH)
282 ]
284 results = await asyncio.gather(*(one(s) for s in searches))
285 outcome = SearchOutcome(
286 made=len(searches),
287 failed=sum(1 for r in results if r is None),
288 provider=provider[0] if provider else None,
289 )
290 if outcome.failed == outcome.made:
291 outcome.unavailable = "Web search did not answer. Try again shortly."
292 return outcome
294 lists = [r for r in results if r]
295 seen: set[str] = set()
296 per_host: dict[str, int] = {}
297 for rank in range(RESULTS_PER_SEARCH):
298 for found in lists:
299 if rank >= len(found) or len(outcome.found) >= MAX_CHECK:
300 continue
301 item = found[rank]
302 key = canonical_key(item.url)
303 if key in seen or per_host.get(item.host, 0) >= MAX_PER_HOST:
304 continue
305 seen.add(key)
306 per_host[item.host] = per_host.get(item.host, 0) + 1
307 outcome.found.append(item)
308 return outcome
311# ---------------------------------------------------------------------------
312# Check
313# ---------------------------------------------------------------------------
316CheckStatus = Literal[
317 "ok",
318 "unsafe",
319 "blocked_by_robots",
320 "http_error",
321 "auth_required",
322 "unsupported",
323 "too_large",
324 "error",
325]
328@dataclass
329class Checked:
330 """What a candidate's address answered with."""
332 requested_url: str
333 status: CheckStatus
334 url: str = ""
335 kind: Kind | None = None
336 title: str | None = None
337 content_type: str | None = None
338 size_bytes: int | None = None
341_TITLE = re.compile(rb"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)
344def _page_title(head: bytes, encoding: str | None) -> str | None:
345 match = _TITLE.search(head)
346 if not match:
347 return None
348 raw = match.group(1).decode(encoding or "utf-8", errors="replace")
349 title = " ".join(html.unescape(raw).split())
350 return title[:300] or None
353def classify(probed: ProbedResource) -> tuple[Kind | None, str | None]:
354 """What a probed address is — ``(kind, title)`` — or ``(None, None)``
355 when it is nothing a source could hold (a sitemap, an image, a script)."""
356 mime = probed.content_type.split(";", 1)[0].strip()
357 head = probed.head
358 lead = head[:2048].lstrip().lower()
359 filename = filename_from(probed.disposition, probed.url)
360 document = sniff_mime(head, mime, filename)
361 if document in _DOCUMENT_TYPES:
362 return "document", None
363 if b"<urlset" in lead or b"<sitemapindex" in lead:
364 return None, None
365 if (
366 "rss" in mime
367 or "atom" in mime
368 or lead.startswith(b"<rss")
369 or b"<rss" in lead[:400]
370 or (b"<feed" in lead[:400] and b"xmlns" in lead)
371 ):
372 return "feed", _page_title(head, probed.encoding)
373 if "html" in mime or (not mime and b"<html" in lead):
374 return "page", _page_title(head, probed.encoding)
375 return None, None
378async def check(
379 urls: list[str],
380 *,
381 fetcher: UrlFetcher | None = None,
382 robots: RobotsCache | None = None,
383 budget_s: float = CHECK_BUDGET_S,
384) -> list[Checked]:
385 """Probe each URL — robots.txt, the public https guard, what it is — a
386 few at a time and at most :data:`CHECK_PER_HOST` per site. A probe still
387 running when ``budget_s`` runs out is reported as an error, not waited
388 for. Results are in the order of ``urls``."""
389 if fetcher is None or robots is None:
390 fetcher, robots = _page_defaults()
391 import_cap = get_settings().knowledge_import_max_bytes
392 overall = asyncio.Semaphore(CHECK_CONCURRENCY)
393 hosts: dict[str, asyncio.Semaphore] = {}
395 async def one(raw: str) -> Checked:
396 url = canonical_url(raw)
397 if url is None:
398 return Checked(raw, "unsafe")
399 host = hostname_of(url)
400 per_host = hosts.setdefault(host, asyncio.Semaphore(CHECK_PER_HOST))
401 async with overall, per_host:
402 try:
403 await fetcher.check(url)
404 except UnsafeUrlError:
405 return Checked(raw, "unsafe", url=url)
406 try:
407 allowed, _ = await robots.check(url)
408 except Exception: # noqa: BLE001 — robots failing refuses
409 allowed = False
410 if not allowed:
411 return Checked(raw, "blocked_by_robots", url=url)
412 try:
413 probed = await fetcher.probe(url, head_bytes=PROBE_HEAD_BYTES)
414 except UnsafeUrlError:
415 return Checked(raw, "unsafe", url=url)
416 except FetchError:
417 return Checked(raw, "http_error", url=url)
418 except Exception: # noqa: BLE001 — a probe failing is a result
419 return Checked(raw, "error", url=url)
420 final = canonical_url(probed.url) or url
421 if final != url and classify_link(final, url) in ("account", "action"):
422 return Checked(raw, "auth_required", url=final)
423 kind, title = classify(probed)
424 mime = probed.content_type.split(";", 1)[0].strip() or None
425 if kind is None:
426 return Checked(raw, "unsupported", url=final, content_type=mime)
427 size = probed.content_length
428 if kind == "document" and size is not None and size > import_cap:
429 return Checked(raw, "too_large", url=final, kind=kind, size_bytes=size)
430 return Checked(
431 raw,
432 "ok",
433 url=final,
434 kind=kind,
435 title=title,
436 content_type=mime,
437 size_bytes=size,
438 )
440 tasks = [asyncio.ensure_future(one(u)) for u in urls[:MAX_CHECK]]
441 if not tasks:
442 return []
443 done, pending = await asyncio.wait(tasks, timeout=budget_s)
444 for task in pending:
445 task.cancel()
446 out: list[Checked] = []
447 for raw, task in zip(urls, tasks):
448 if task in done and not task.cancelled() and task.exception() is None:
449 out.append(task.result())
450 else:
451 out.append(Checked(raw, "error"))
452 return out