: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(business-knowledge): load whole crawl sources within the deadline (#116607)
John C. Watersd769d22ebff2
diff --git a/products/business_knowledge/backend/html_parse.py b/products/business_knowledge/backend/html_parse.pyindex a973bc2523dc..b95bbc4c091c 100644--- a/products/business_knowledge/backend/html_parse.py+++ b/products/business_knowledge/backend/html_parse.py@@ -99,27 +99,41 @@ def parse_html(body: bytes, url: str, content_type: str | None = None) -> tuple[# Deferred import: trafilatura (and its dateparser/htmldate deps) is slow to import# and only needed when actually parsing a page, not at API/module load.import trafilatura+ from trafilatura.metadata import examine_meta, extract_meta_json, extract_title+ from trafilatura.utils import load_html- # trafilatura.extract returns the main-content text only. We pass raw+ # trafilatura.extract returns the main-content text only. load_html gets 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(- body,- url=url,- include_comments=False,- include_tables=True,- favor_precision=True,- output_format="markdown",- )+ tree = load_html(body)title = ""- try:- 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)+ if tree is not None:+ try:+ metadata = examine_meta(tree)+ try:+ metadata = extract_meta_json(tree, metadata)+ except Exception:+ logger.info("business_knowledge.html_parse.json_ld_failed", url=url)+ metadata.title = metadata.title or extract_title(tree)+ metadata.clean_and_trim()+ title = (metadata.title or "").strip()[:512]+ except Exception: # noqa: BLE001 — trafilatura metadata parsing can crash on malformed HTML+ logger.info("business_knowledge.html_parse.metadata_failed", url=url)++ extracted = (+ trafilatura.extract(+ tree,+ url=url,+ include_comments=False,+ include_tables=True,+ favor_precision=True,+ output_format="markdown",+ )+ if tree is not None+ else None+ )html: str | None = Nonetext = (extracted or "").strip()diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex 68b2ee70aee3..cbc5ec3ae70c 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -11,7 +11,7 @@ import datetimefrom collections import defaultdictfrom dataclasses import dataclassfrom functools import reduce-from itertools import batched+from itertools import batched, zip_longestfrom operator import or_from typing import Literalfrom urllib.parse import urlsplit@@ -2049,6 +2049,10 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledge# Each URL is written once. A second outcome for a new URL would insert the same chunk ids again.safe_urls = list(dict.fromkeys(safe_urls))+ new_urls = [u for u in safe_urls if u not in existing_by_url]+ stored_urls = [u for u in safe_urls if u in existing_by_url]+ safe_urls = [u for pair in zip_longest(new_urls, stored_urls) for u in pair if u is not None]+def _etag_for(u: str) -> str | None:existing = existing_by_url.get(u)return existing.etag if existing and existing.etag else Nonediff --git a/products/business_knowledge/backend/tests/test_crawl_ingest.py b/products/business_knowledge/backend/tests/test_crawl_ingest.pyindex 54913ea95f26..2f842baf613b 100644--- a/products/business_knowledge/backend/tests/test_crawl_ingest.py+++ b/products/business_knowledge/backend/tests/test_crawl_ingest.py@@ -20,7 +20,8 @@ Design notes:test patches the narrowest layer it needs."""-from collections.abc import Mapping+from collections.abc import Iterator, Mapping+from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -669,6 +670,36 @@ class TestRefreshCrawlSource(APIBaseTest):assert doc_b.tombstoned_at is not Noneassert KnowledgeDocument.objects.unscoped().filter(source=source, stable_id="https://example.com/c").exists()+ def test_refresh_cut_off_by_the_crawl_deadline_stores_new_pages_and_refreshes_stored_ones(self) -> None:+ source = self._seed(["https://example.com/a", "https://example.com/b"])++ sitemap_urls = [+ "https://example.com/a",+ "https://example.com/b",+ "https://example.com/c",+ "https://example.com/d",+ ]+ behaviours: dict[str, url_fetch.FetchResult | Exception] = {+ url: _ok(url, f"<html><body>updated body of {url}</body></html>".encode()) for url in sitemap_urls+ }+ real_iter_fetch = crawl.iter_fetch++ def _deadline_after_two_pages(urls: list[str], **kwargs: Any) -> Iterator[crawl.CrawlOutcome]:+ yield from real_iter_fetch(urls[:2], **kwargs)+ for url in urls[2:]:+ yield crawl.CrawlOutcome(url=url, final_url=url, status="error", error="Crawl total timeout exceeded")++ with (+ patch.object(discover, "_http_get_text", return_value=_sitemap_xml(sitemap_urls)),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ patch.object(crawl, "iter_fetch", side_effect=_deadline_after_two_pages),+ ):+ refresh_source(source_id=source.id, team_id=self.team.id)++ assert KnowledgeDocument.objects.unscoped().filter(source=source, stable_id="https://example.com/c").exists()+ doc_a = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/a")+ assert "updated" in doc_a.content+def test_unchanged_source_reports_not_modified(self) -> None:source = self._seed(["https://example.com/a"])doc_a = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/a")diff --git a/products/business_knowledge/backend/tests/test_url_ingest.py b/products/business_knowledge/backend/tests/test_url_ingest.pyindex 947e525fe0e5..4515022cefd0 100644--- a/products/business_knowledge/backend/tests/test_url_ingest.py+++ b/products/business_knowledge/backend/tests/test_url_ingest.py@@ -210,6 +210,15 @@ class TestParseHtml(SimpleTestCase):assert "\ufffd" not in textassert title == "Тест"+ def test_control_characters_are_stripped_from_the_metadata_title(self) -> None:+ html = (+ b'<html><head><title>Raw</title><script type="application/ld+json">'+ b'{"@type": "Article", "headline": "Refund\\u0000 policy"}</script></head>'+ b"<body><article><p>We issue full refunds within 30 days of purchase.</p></article></body></html>"+ )+ title, _ = parse_html(html, "https://example.com/refunds")+ assert title == "Refund policy"+class TestCreateUrlSource(BaseTest):@patch("products.business_knowledge.backend.logic.url_fetch.fetch_url")