Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(bk): extract crawled pages as markdown and reuse discovery fetches (#63185)

Alex V17e7fbd5e6cb
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.py
index 5deffafd7573..1c867f12438e 100644
--- a/products/business_knowledge/backend/constants.py
+++ b/products/business_knowledge/backend/constants.py
@@ -54,6 +54,10 @@ CRAWL_HARD_MAX_DEPTH = 5
# hammering an origin. In-process (threading.Semaphore), not cross-worker;
# cross-worker rate limiting is Stage 5 Temporal work.
PER_HOST_CONCURRENCY = 2
+# Total bytes of page bodies the same-origin BFS may carry over to the fetch
+# phase (so traversed pages aren't downloaded twice). Past the budget the
+# fetch phase re-downloads — a bounded-memory tradeoff, not a correctness one.
+PREFETCH_CACHE_MAX_BYTES = 64 * 1024 * 1024
# --- Stage 3: file upload tunables ---
# Hard cap on uploaded file size (compressed). Above this the serializer
diff --git a/products/business_knowledge/backend/crawl.py b/products/business_knowledge/backend/crawl.py
index 7b200ca81787..67c5cd5aefbd 100644
--- a/products/business_knowledge/backend/crawl.py
+++ b/products/business_knowledge/backend/crawl.py
@@ -79,13 +79,26 @@ class _PerHostSemaphoreRegistry:
return sem
-def _fetch_one(url: str, *, etag: str | None, registry: _PerHostSemaphoreRegistry) -> CrawlOutcome:
+def _fetch_one(
+ url: str,
+ *,
+ etag: str | None,
+ registry: _PerHostSemaphoreRegistry,
+ prefetched: dict[str, url_fetch.FetchResult],
+) -> CrawlOutcome:
"""
Fetch + parse a single URL. Never raises — all failures return a
CrawlOutcome(status="error", error=...). Matches the `url_fetch.fetch_url`
contract for SSRF re-validation per-hop.
+
+ Pages already downloaded during discovery (`prefetched`) skip the network
+ round-trip entirely and go straight to parsing.
"""
+ result = prefetched.get(url_fetch.prefetch_key(url))
+ if result is not None:
+ return _parse_outcome(url, result)
+
sem = registry.get(_host_of(url))
sem.acquire()
try:
@@ -102,36 +115,40 @@ def _fetch_one(url: str, *, etag: str | None, registry: _PerHostSemaphoreRegistr
etag=result.etag or (etag or ""),
)
- if not result.body:
- return CrawlOutcome(url=url, final_url=result.final_url, status="error", error="Remote response was empty.")
+ return _parse_outcome(url, result)
+ finally:
+ sem.release()
- if not url_fetch.is_html_content_type(result.content_type):
- return CrawlOutcome(url=url, final_url=result.final_url, status="error", error="Unsupported content type.")
- title, text = html_parse.parse_html(result.body, result.final_url)
- if not text.strip():
- return CrawlOutcome(
- url=url, final_url=result.final_url, status="error", error="Could not extract any text."
- )
- # Per-page byte cap — trimming beats rejecting a huge wiki page.
- if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:
- return CrawlOutcome(
- url=url,
- final_url=result.final_url,
- status="error",
- error="Page content exceeds the maximum allowed size.",
- )
+def _parse_outcome(url: str, result: url_fetch.FetchResult) -> CrawlOutcome:
+ """Parse a fetched body into a CrawlOutcome. Network-free."""
+
+ if not result.body:
+ return CrawlOutcome(url=url, final_url=result.final_url, status="error", error="Remote response was empty.")
+
+ if not url_fetch.is_html_content_type(result.content_type):
+ return CrawlOutcome(url=url, final_url=result.final_url, status="error", error="Unsupported content type.")
+
+ title, text = html_parse.parse_html(result.body, result.final_url, content_type=result.content_type)
+ if not text.strip():
+ return CrawlOutcome(url=url, final_url=result.final_url, status="error", error="Could not extract any text.")
+ # Per-page byte cap — trimming beats rejecting a huge wiki page.
+ if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:
return CrawlOutcome(
url=url,
final_url=result.final_url,
- status="ok",
- title=title,
- text=text,
- etag=result.etag or "",
- content_hash=sha256_of(text),
+ status="error",
+ error="Page content exceeds the maximum allowed size.",
)
- finally:
- sem.release()
+ return CrawlOutcome(
+ url=url,
+ final_url=result.final_url,
+ status="ok",
+ title=title,
+ text=text,
+ etag=result.etag or "",
+ content_hash=sha256_of(text),
+ )
def fetch_many(
@@ -140,6 +157,7 @@ def fetch_many(
etag_for: Callable[[str], str | None] | None = None,
per_host: int = PER_HOST_CONCURRENCY,
max_workers: int | None = None,
+ prefetched: dict[str, url_fetch.FetchResult] | None = None,
) -> list[CrawlOutcome]:
"""
Fetch all `urls` in parallel, capped per-host by a threading semaphore.
@@ -147,6 +165,9 @@ def fetch_many(
`etag_for(url)` — optional; called once per URL to pull a stored ETag
for conditional GET. Returns None when we don't have one yet.
+ `prefetched` — optional bodies already downloaded during discovery
+ (keyed by normalized URL); matching URLs skip the network entirely.
+
`max_workers` — defaults to `max(PER_HOST_CONCURRENCY * 4, 8)`. We want
enough threads to saturate the per-host semaphore without going wild;
the semaphore is the real throttle.
@@ -157,12 +178,19 @@ def fetch_many(
registry = _PerHostSemaphoreRegistry(per_host)
workers = max_workers if max_workers is not None else max(per_host * 4, 8)
+ cache = prefetched or {}
results: list[CrawlOutcome] = []
pool = ThreadPoolExecutor(max_workers=workers)
try:
futures = {
- pool.submit(_fetch_one, url, etag=(etag_for(url) if etag_for else None), registry=registry): url
+ pool.submit(
+ _fetch_one,
+ url,
+ etag=(etag_for(url) if etag_for else None),
+ registry=registry,
+ prefetched=cache,
+ ): url
for url in urls
}
done, not_done = wait(futures, timeout=CRAWL_TOTAL_TIMEOUT_SECONDS, return_when=ALL_COMPLETED)
diff --git a/products/business_knowledge/backend/discover.py b/products/business_knowledge/backend/discover.py
index 1b7bed5583d7..f77abc6be126 100644
--- a/products/business_knowledge/backend/discover.py
+++ b/products/business_knowledge/backend/discover.py
@@ -28,8 +28,15 @@ import defusedxml.ElementTree as ET
from bs4 import BeautifulSoup
from defusedxml.ElementTree import ParseError as DefusedParseError
-from .constants import CRAWL_HARD_MAX_DEPTH, DEFAULT_CRAWL_MAX_DEPTH, HARD_DISCOVER_CAP, URL_BOT_NAME, URL_MAX_BYTES
-from .url_fetch import UrlFetchError, fetch_text
+from .constants import (
+ CRAWL_HARD_MAX_DEPTH,
+ DEFAULT_CRAWL_MAX_DEPTH,
+ HARD_DISCOVER_CAP,
+ PREFETCH_CACHE_MAX_BYTES,
+ URL_BOT_NAME,
+ URL_MAX_BYTES,
+)
+from .url_fetch import FetchResult, UrlFetchError, fetch_text, fetch_url, prefetch_key
logger = structlog.get_logger(__name__)
@@ -38,6 +45,20 @@ class DiscoverError(Exception):
"""User-safe discover failure. No server detail in the message."""
+@dataclass(frozen=True)
+class DiscoverResult:
+ """
+ Discovery output: the deduped/filtered/capped URL list, plus the pages we
+ already fetched while traversing (same-origin BFS fetches every
+ intermediate page to extract links). `prefetched` is keyed by normalized
+ URL so the crawl fetch phase can reuse those bodies instead of hitting
+ the origin a second time.
+ """
+
+ urls: list[str]
+ prefetched: dict[str, FetchResult]
+
+
@dataclass(frozen=True)
class CrawlConfig:
"""
@@ -226,12 +247,15 @@ def _load_robots(origin: str) -> urllib.robotparser.RobotFileParser | None:
return parser
-def _discover_same_origin(entry_url: str, *, config: CrawlConfig) -> list[str]:
+def _discover_same_origin(entry_url: str, *, config: CrawlConfig) -> tuple[list[str], dict[str, FetchResult]]:
"""
BFS crawler scoped to the entry URL's (scheme, host, port). Respects
robots.txt when available. Stops at `config.max_depth`, once `max_pages`
matching URLs are collected, or at `HARD_DISCOVER_CAP` fetches.
+ Returns (urls, prefetched). Every traversed page's `FetchResult` is kept
+ in `prefetched` so the content fetch phase doesn't re-download it.
+
Glob filtering happens *here*, not after, so `max_pages` counts pages that
actually match the include globs — otherwise the budget gets spent on
non-matching pages (e.g. crawling `/` for `/handbook/*` would collect 50
@@ -250,6 +274,8 @@ def _discover_same_origin(entry_url: str, *, config: CrawlConfig) -> list[str]:
seen: set[str] = {entry_url}
out: list[str] = []
+ prefetched: dict[str, FetchResult] = {}
+ prefetched_bytes = 0
visited = 0
queue: deque[tuple[str, int]] = deque([(entry_url, 0)])
while queue and len(out) < page_cap and visited < HARD_DISCOVER_CAP:
@@ -270,10 +296,25 @@ def _discover_same_origin(entry_url: str, *, config: CrawlConfig) -> list[str]:
continue
try:
visited += 1
- html = _http_get_text(url)
- except DiscoverError:
+ # fetch_url (not fetch_text): content Accept headers, and the full
+ # FetchResult (body/etag/content-type) is reusable downstream.
+ result = fetch_url(url)
+ except UrlFetchError:
# One bad page shouldn't tank the crawl.
continue
+ if result.body is None:
+ continue
+ # Cache only pages the fetch phase will actually request (collected
+ # ones), within a total byte budget — beyond it the fetch phase just
+ # re-downloads, trading a request for bounded memory.
+ # `excluded` pages never reach here — the depth/exclusion guard above
+ # already skipped them before the fetch.
+ if included and prefetched_bytes + len(result.body) <= PREFETCH_CACHE_MAX_BYTES:
+ prefetched[prefetch_key(url)] = result
+ prefetched_bytes += len(result.body)
+ # Decode for link extraction only — hrefs are effectively ASCII, so
+ # utf-8/replace is good enough here.
+ html = result.body.decode("utf-8", errors="replace")
for link in _extract_links(html, url, origin_tuple):
if link in seen:
continue
@@ -282,7 +323,7 @@ def _discover_same_origin(entry_url: str, *, config: CrawlConfig) -> list[str]:
if not _should_traverse(link_path, include_prefixes):
continue
queue.append((link, depth + 1))
- return out
+ return out, prefetched
# --- Glob filter + public entry point ---------------------------------------
@@ -327,19 +368,21 @@ def _dedupe_preserving_order(urls: list[str]) -> list[str]:
return out
-def discover(mode: str, entry_url: str, config: CrawlConfig) -> list[str]:
+def discover(mode: str, entry_url: str, config: CrawlConfig) -> DiscoverResult:
"""
Entry point for `logic.py`. Dispatches on `mode`, dedupes, applies
- include/exclude globs, truncates to `max_pages`, and returns a list of
- absolute URLs ready for the fetch loop.
+ include/exclude globs, truncates to `max_pages`, and returns the URLs
+ ready for the fetch loop plus any page bodies already fetched during
+ traversal (same-origin mode only).
Never returns more than `min(max_pages, MAX_URLS_PER_SOURCE)` URLs.
"""
+ prefetched: dict[str, FetchResult] = {}
if mode == "sitemap":
raw = _discover_sitemap(entry_url, config=config)
elif mode == "same_origin":
- raw = _discover_same_origin(entry_url, config=config)
+ raw, prefetched = _discover_same_origin(entry_url, config=config)
elif mode == "github_repo":
raise NotImplementedError("github_repo crawl mode is not yet supported")
else:
@@ -347,4 +390,4 @@ def discover(mode: str, entry_url: str, config: CrawlConfig) -> list[str]:
deduped = _dedupe_preserving_order(raw)
filtered = _apply_globs(deduped, config)
- return filtered[: config.max_pages]
+ return DiscoverResult(urls=filtered[: config.max_pages], prefetched=prefetched)
diff --git a/products/business_knowledge/backend/html_parse.py b/products/business_knowledge/backend/html_parse.py
index a4aa2e044fa5..a973bc2523dc 100644
--- a/products/business_knowledge/backend/html_parse.py
+++ b/products/business_knowledge/backend/html_parse.py
@@ -1,26 +1,64 @@
"""
-HTML -> plain text normalization for URL-backed knowledge sources.
+HTML -> markdown-ish plain text normalization for URL-backed knowledge sources.
Primary extractor is trafilatura — it's specifically designed to strip
boilerplate (nav, footer, cookie banners) from article-style pages while
preserving semantic structure. Falls back to BeautifulSoup for pages where
trafilatura returns nothing (error pages, SPA shells, very minimal HTML).
+Output is markdown: blocks are separated by blank lines (which the chunker
+in `logic.py` relies on as paragraph boundaries) and headings/lists/code
+survive extraction, which improves both chunk boundaries and retrieval.
+
Only `logic.py` is allowed to import this module.
"""
from __future__ import annotations
+import re
+
import structlog
from bs4 import BeautifulSoup
logger = structlog.get_logger(__name__)
+_CHARSET_RE = re.compile(r"charset=[\"']?([\w.-]+)", re.IGNORECASE)
+
+# Boilerplate containers stripped before text extraction in the bs4 fallback.
+# script/style/etc carry no prose; nav/header/footer/aside/form/button are the
+# classic nav-bar / cookie-banner / footer-link noise we must keep out of
+# searchable content.
+_FALLBACK_DROP_TAGS = (
+ "script",
+ "style",
+ "template",
+ "noscript",
+ "iframe",
+ "nav",
+ "header",
+ "footer",
+ "aside",
+ "form",
+ "button",
+)
+
+
+def _decode(body: bytes, content_type: str | None) -> str:
+ """
+ Decode a response body for the bs4 fallback paths. Honors the charset
+ declared in the Content-Type header when present and valid; otherwise
+ utf-8 with errors='replace' as the floor — we'd rather get partial
+ garbled text than drop the whole page. (trafilatura is fed raw bytes
+ and does its own encoding detection.)
+ """
-def _decode(body: bytes) -> str:
- # trafilatura handles encoding detection internally, but the bs4 fallback
- # needs us to pick something. utf-8 with errors='replace' is a sensible
- # floor — we'd rather get partial garbled text than drop the whole page.
+ if content_type:
+ match = _CHARSET_RE.search(content_type)
+ if match:
+ try:
+ return body.decode(match.group(1))
+ except (UnicodeDecodeError, LookupError):
+ pass
try:
return body.decode("utf-8")
except UnicodeDecodeError:
@@ -29,25 +67,31 @@ def _decode(body: bytes) -> str:
def _bs4_fallback(html: str) -> str:
"""
- Last-resort extractor. Strips script/style/template nodes, then collapses
- runs of whitespace. We never return raw attributes or inline event
- handlers — those are prompt-injection vectors when shown to the LLM.
+ Last-resort extractor. Strips boilerplate containers (nav, header,
+ footer, ...) plus script/style nodes, prefers <main>/<article> when the
+ page has one, then collapses runs of whitespace. We never return raw
+ attributes or inline event handlers — those are prompt-injection vectors
+ when shown to the LLM.
"""
soup = BeautifulSoup(html, "html.parser")
- for node in soup(["script", "style", "template", "noscript", "iframe"]):
+ for node in soup(_FALLBACK_DROP_TAGS):
node.decompose()
- text = soup.get_text(separator="\n")
+ root = soup.find("main") or soup.find("article") or soup
+ text = root.get_text(separator="\n")
# Collapse whitespace runs without losing paragraph breaks.
lines = [line.strip() for line in text.splitlines()]
joined = "\n".join(line for line in lines if line)
return joined
-def parse_html(body: bytes, url: str) -> tuple[str, str]:
+def parse_html(body: bytes, url: str, content_type: str | None = None) -> tuple[str, str]:
"""
Extract (title, text) from an HTML response body.
+ `content_type` is the raw Content-Type header, used for charset hints in
+ the fallback paths.
+
Returns empty strings if extraction produced nothing usable — callers
should treat that as a soft failure and store an error on the source.
"""
@@ -56,30 +100,32 @@ def parse_html(body: bytes, url: str) -> tuple[str, str]:
# and only needed when actually parsing a page, not at API/module load.
import trafilatura
- html = _decode(body)
-
- # trafilatura.extract returns the main-content text only. We ask for
- # plain output (not XML/JSON) to keep downstream chunking dead simple.
+ # trafilatura.extract returns the main-content text only. We pass raw
+ # bytes so its internal encoding detection runs (meta charset, BOM, ...)
+ # instead of forcing utf-8. Markdown output keeps blank lines between
+ # blocks — the chunker's paragraph boundary — and preserves headings.
extracted = trafilatura.extract(
- html,
+ body,
url=url,
include_comments=False,
include_tables=True,
favor_precision=True,
- output_format="txt",
+ output_format="markdown",
)
title = ""
try:
- metadata = trafilatura.extract_metadata(html)
+ metadata = trafilatura.extract_metadata(body)
if metadata and metadata.title:
title = metadata.title.strip()[:512]
except Exception: # noqa: BLE001 — trafilatura metadata parsing can crash on malformed HTML
logger.info("business_knowledge.html_parse.metadata_failed", url=url)
+ html: str | None = None
text = (extracted or "").strip()
if not text:
try:
+ html = _decode(body, content_type)
text = _bs4_fallback(html)
except Exception: # noqa: BLE001 — bs4 is a best-effort fallback
logger.info("business_knowledge.html_parse.bs4_failed", url=url)
@@ -89,6 +135,8 @@ def parse_html(body: bytes, url: str) -> tuple[str, str]:
# Extract a title from <title> as a secondary fallback — some pages
# have no og:title / articleTitle but do have <title>.
try:
+ if html is None:
+ html = _decode(body, content_type)
soup = BeautifulSoup(html, "html.parser")
if soup.title and soup.title.string:
title = soup.title.string.strip()[:512]
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 3ed8829cec6f..6c2827c70ec9 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -719,7 +719,7 @@ def _fetch_and_parse(url: str, *, etag: str | None) -> tuple[url_fetch.FetchResu
if not url_fetch.is_html_content_type(result.content_type):
raise UrlFetchFailedError("Unsupported content type.")
- title, text = html_parse.parse_html(result.body, result.final_url)
+ title, text = html_parse.parse_html(result.body, result.final_url, content_type=result.content_type)
if not text.strip():
raise EmptyContentError("Could not extract any text from the URL.")
if len(text.encode("utf-8")) > MAX_TEXT_SIZE_BYTES:
@@ -1263,10 +1263,11 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeS
return _mark_error(str(exc))
try:
- candidate_urls = discover.discover(source.crawl_mode, normalized, config)
+ discovery = discover.discover(source.crawl_mode, normalized, config)
except discover.DiscoverError as exc:
return _mark_error(str(exc))
+ candidate_urls = discovery.urls
if not candidate_urls:
return _mark_error("Crawl discovered no URLs. Check the entry URL and globs.")
@@ -1281,7 +1282,7 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeS
if not safe_urls:
return _mark_error("Crawl discovered no safe URLs to fetch.")
- outcomes = crawl.fetch_many(safe_urls)
+ outcomes = crawl.fetch_many(safe_urls, prefetched=discovery.prefetched)
ok_outcomes = [o for o in outcomes if o.status == "ok"]
if not ok_outcomes:
@@ -1348,7 +1349,8 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledge
config = _resolve_crawl_config(source.crawl_config)
normalized = _validate_url(source.source_url)
try:
- discovered = discover.discover(source.crawl_mode, normalized, config)
+ discovery = discover.discover(source.crawl_mode, normalized, config)
+ discovered = discovery.urls
except discover.DiscoverError as exc:
raise UrlFetchFailedError(str(exc)) from exc
except (InvalidUrlError, UrlFetchFailedError) as exc:
@@ -1391,7 +1393,7 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledge
existing = existing_by_url.get(u)
return existing.etag if existing and existing.etag else None
- outcomes = crawl.fetch_many(safe_urls, etag_for=_etag_for)
+ outcomes = crawl.fetch_many(safe_urls, etag_for=_etag_for, prefetched=discovery.prefetched)
# `discovered_set` is built by normalizing the raw discovered URLs (lowercased
# scheme+host, no fragment) so keys match `existing_by_url` (which uses the
# normalized stable_id). We do NOT use `safe_urls` here — that would tombstone
diff --git a/products/business_knowledge/backend/tests/test_crawl_ingest.py b/products/business_knowledge/backend/tests/test_crawl_ingest.py
index 5bed3e95e9ba..1e9eab56092f 100644
--- a/products/business_knowledge/backend/tests/test_crawl_ingest.py
+++ b/products/business_knowledge/backend/tests/test_crawl_ingest.py
@@ -11,8 +11,9 @@ Scope:
- SSRF on a URL that appears in a sitemap but points at a blocked host.
Design notes:
-- We patch `discover._http_get_text` for discover tests — exercising real
- XML parsing without needing HTTP. For fetch tests we patch
+- We patch `discover._http_get_text` for sitemap/robots fetches and
+ `discover.fetch_url` for BFS page fetches — exercising real XML/link
+ parsing without needing HTTP. For fetch tests we patch
`url_fetch.fetch_url` so the crawl module's parallel ThreadPoolExecutor
is exercised end-to-end but with deterministic content.
- `requests.Session.get` is intentionally NOT patched globally — each
@@ -63,7 +64,7 @@ class TestDiscoverSitemap(BaseTest):
"sitemap",
"https://example.com/sitemap.xml",
discover.CrawlConfig(max_pages=10),
- )
+ ).urls
assert urls == ["https://example.com/a", "https://example.com/b", "https://example.com/c"]
def test_unfurls_sitemap_index(self) -> None:
@@ -85,7 +86,7 @@ class TestDiscoverSitemap(BaseTest):
"sitemap",
"https://example.com/sitemap.xml",
discover.CrawlConfig(max_pages=10),
- )
+ ).urls
assert urls == [
"https://example.com/1",
"https://example.com/2",
@@ -110,7 +111,7 @@ class TestDiscoverSitemap(BaseTest):
exclude_globs=("/docs/private/*",),
max_pages=10,
),
- )
+ ).urls
assert urls == ["https://example.com/docs/one", "https://example.com/docs/two"]
def test_max_pages_caps_output(self) -> None:
@@ -120,7 +121,7 @@ class TestDiscoverSitemap(BaseTest):
"sitemap",
"https://example.com/sitemap.xml",
discover.CrawlConfig(max_pages=5),
- )
+ ).urls
assert len(urls) == 5
def test_rejects_malformed_xml(self) -> None:
@@ -137,6 +138,27 @@ class TestDiscoverSitemap(BaseTest):
raise AssertionError("expected DiscoverError")
+def _page_fetcher(pages: Mapping[str, str]):
+ """Stand-in for `discover.fetch_url` (BFS page fetches), driven by url -> html."""
+
+ def _fake(url: str, *, etag: str | None = None) -> url_fetch.FetchResult:
+ return url_fetch.FetchResult(
+ status=200,
+ body=pages.get(url, "").encode(),
+ content_type="text/html",
+ etag=None,
+ final_url=url,
+ )
+
+ return _fake
+
+
+def _no_robots(url: str, max_bytes: int = 0) -> str:
+ if url.endswith("/robots.txt"):
+ raise discover.DiscoverError("not found")
+ raise AssertionError(f"unexpected metadata fetch: {url}")
+
+
class TestDiscoverSameOrigin(BaseTest):
def test_stays_on_origin_and_respects_depth(self) -> None:
pages = {
@@ -145,18 +167,18 @@ class TestDiscoverSameOrigin(BaseTest):
"https://ex.com/c": "",
}
- def _fake(url: str, max_bytes: int = 0) -> str:
- if url == "https://ex.com/robots.txt":
- raise discover.DiscoverError("not found")
- return pages.get(url, "")
-
- with patch.object(discover, "_http_get_text", side_effect=_fake):
- urls = discover.discover(
+ with (
+ patch.object(discover, "_http_get_text", side_effect=_no_robots),
+ patch.object(discover, "fetch_url", side_effect=_page_fetcher(pages)),
+ ):
+ result = discover.discover(
"same_origin",
"https://ex.com/a",
discover.CrawlConfig(max_depth=1, max_pages=10),
)
- assert urls == ["https://ex.com/a", "https://ex.com/b"]
+ assert result.urls == ["https://ex.com/a", "https://ex.com/b"]
+ # Traversed pages (those we fetched for links) are carried over for reuse.
+ assert "https://ex.com/a" in result.prefetched
def test_include_glob_collects_matching_pages_not_just_entry_links(self) -> None:
# Mirrors the reported bug: crawl `/` for `/handbook/*`. The cap must
@@ -174,19 +196,21 @@ class TestDiscoverSameOrigin(BaseTest):
"https://ex.com/docs": '<a href="/docs/y">y</a>',
}
fetched: list[str] = []
+ page_fetch = _page_fetcher(pages)
- def _fake(url: str, max_bytes: int = 0) -> str:
- if url == "https://ex.com/robots.txt":
- raise discover.DiscoverError("not found")
+ def _fake(url: str, *, etag: str | None = None) -> url_fetch.FetchResult:
fetched.append(url)
- return pages.get(url, "")
+ return page_fetch(url, etag=etag)
- with patch.object(discover, "_http_get_text", side_effect=_fake):
+ with (
+ patch.object(discover, "_http_get_text", side_effect=_no_robots),
+ patch.object(discover, "fetch_url", side_effect=_fake),
+ ):
urls = discover.discover(
"same_origin",
"https://ex.com/",
discover.CrawlConfig(include_globs=("/handbook/*",), max_depth=3, max_pages=50),
- )
+ ).urls
assert set(urls) == {
"https://ex.com/handbook/a",
@@ -205,17 +229,15 @@ class TestDiscoverSameOrigin(BaseTest):
**{f"https://ex.com/handbook/{i}": "" for i in range(5)},
}
- def _fake(url: str, max_bytes: int = 0) -> str:
- if url == "https://ex.com/robots.txt":
- raise discover.DiscoverError("not found")
- return pages.get(url, "")
-
- with patch.object(discover, "_http_get_text", side_effect=_fake):
+ with (
+ patch.object(discover, "_http_get_text", side_effect=_no_robots),
+ patch.object(discover, "fetch_url", side_effect=_page_fetcher(pages)),
+ ):
urls = discover.discover(
"same_origin",
"https://ex.com/handbook",
discover.CrawlConfig(include_globs=("/handbook/*",), max_depth=2, max_pages=3),
- )
+ ).urls
assert len(urls) == 3
assert all(u.startswith("https://ex.com/handbook/") for u in urls)
diff --git a/products/business_knowledge/backend/tests/test_url_ingest.py b/products/business_knowledge/backend/tests/test_url_ingest.py
index f212f4e15ba5..a48e42a6c8ff 100644
--- a/products/business_knowledge/backend/tests/test_url_ingest.py
+++ b/products/business_knowledge/backend/tests/test_url_ingest.py
@@ -18,10 +18,12 @@ from parameterized import parameterized
from rest_framework import status
from products.business_knowledge.backend import url_fetch
+from products.business_knowledge.backend.html_parse import _bs4_fallback, parse_html
from products.business_knowledge.backend.logic import (
InvalidUrlError,
QuotaExceededError,
SourceBusyError,
+ chunk_text,
create_url_source,
refresh_source,
update_url_source,
@@ -144,6 +146,54 @@ _BASIC_HTML = b"""<!doctype html>
</body></html>"""
+class TestParseHtml(BaseTest):
+ def test_blocks_are_blank_line_separated_and_chunk_on_paragraphs(self) -> None:
+ # Regression: txt extraction separated blocks with single newlines, so
+ # the chunker (which splits on blank lines) saw one mega-paragraph and
+ # hard-split mid-sentence. Markdown output must keep blank lines.
+ paragraphs = "".join(
+ f"<h2>Section {i}</h2><p>Paragraph {i} with realistic prose content that runs long enough "
+ f"to matter for chunk packing and boundary checks in this regression test.</p>"
+ for i in range(30)
+ )
+ html = f"<html><head><title>Doc</title></head><body><article>{paragraphs}</article></body></html>".encode()
+
+ title, text = parse_html(html, "https://example.com/doc", content_type="text/html")
+ assert title
+ assert "\n\n" in text
+ chunks = chunk_text(text)
+ assert len(chunks) > 1
+ # Paragraph-aligned packing — every chunk ends on a block boundary
+ # (a full sentence or a heading line), never a mid-sentence hard split.
+ for chunk in chunks:
+ last_line = chunk.content.rstrip().splitlines()[-1]
+ assert last_line.startswith("#") or last_line.endswith((".", "?", "!"))
+
+ def test_fallback_strips_nav_and_footer(self) -> None:
+ html = (
+ "<html><body>"
+ '<nav><a href="/pricing">Pricing</a><a href="/docs">Docs</a></nav>'
+ "<main><p>Actual page content.</p></main>"
+ '<footer><a href="/privacy">Privacy</a> Copyright</footer>'
+ "</body></html>"
+ )
+ text = _bs4_fallback(html)
+ assert "Actual page content." in text
+ assert "Pricing" not in text
+ assert "Privacy" not in text
+
+ def test_non_utf8_page_decodes_correctly(self) -> None:
+ html_str = (
+ '<html><head><meta charset="windows-1251"><title>Тест</title></head>'
+ "<body><article><p>Первый абзац с настоящим содержимым, достаточно длинный для извлечения.</p>"
+ "<p>Второй абзац тоже с настоящим содержимым для проверки декодирования.</p></article></body></html>"
+ )
+ title, text = parse_html(html_str.encode("windows-1251"), "https://example.com/ru")
+ assert "Первый абзац" in text
+ assert "\ufffd" not in text
+ assert title == "Тест"
+
+
class TestCreateUrlSource(BaseTest):
@patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")
@patch("products.business_knowledge.backend.logic.is_url_allowed", return_value=(True, None))
diff --git a/products/business_knowledge/backend/url_fetch.py b/products/business_knowledge/backend/url_fetch.py
index a68051d0627a..2ed366583d7d 100644
--- a/products/business_knowledge/backend/url_fetch.py
+++ b/products/business_knowledge/backend/url_fetch.py
@@ -87,6 +87,19 @@ def sha256_of(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
+def prefetch_key(url: str) -> str:
+ """
+ Stable cache key for a URL, shared by the crawl prefetch path. Discovery
+ caches fetched bodies under this key and the fetch phase looks them up by
+ it — they MUST agree, so both go through this one function.
+ """
+
+ try:
+ return normalize_url(url)
+ except UrlFetchError:
+ return url
+
+
# --- DNS-pinning adapter — eliminates TOCTOU rebinding window ----------------