: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): failed crawl refresh stays an error (#116017)
Alex Vf2c6ff710d7f
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex 8ea71b7dc325..68b2ee70aee3 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -1996,6 +1996,10 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledge- Existing URL that vanished from discovery → mark tombstoned_at,delete chunks (keep the doc row so a later re-appearance can reusethe id).+ - No live page confirmed and none left → `last_refresh_status=error`.+ Live documents stay when the fetches fail. A source with none left is+ `status=error`, including when a vanished page was tombstoned and its+ replacement failed to fetch."""try:@@ -2060,9 +2064,12 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgediscovered_set.add(url_fetch.normalize_url(u))except url_fetch.UrlFetchError:pass- vanished_ids = [d.id for url, d in existing_by_url.items() if url not in discovered_set]+ # An empty discovery is a failed read, not proof every stored page is gone.+ vanished_ids = [d.id for url, d in existing_by_url.items() if url not in discovered_set] if discovered else []any_changes = False+ first_error = ""+ retained_page = False# Tombstone docs whose URL vanished from discovery before any batch, so the# chunk cap check below does not count their chunks. Chunks go away now; the# sweep hard-deletes the doc row after a grace period (preserves the id in@@ -2084,6 +2091,8 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgefor outcome in batch:existing = existing_by_url.pop(outcome.url, None)if outcome.status == "not_modified":+ if existing is not None:+ retained_page = True# Still touch the etag so a rotation stays fresh.if existing and outcome.etag and existing.etag != outcome.etag:existing.etag = outcome.etag@@ -2092,6 +2101,8 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgeif outcome.status == "error":# Keep the old doc intact — partial failures shouldn't# knock out a previously-working page.+ if not first_error:+ first_error = outcome.errorlogger.info("business_knowledge.crawl.refresh_page_error",source_id=str(source.id),@@ -2101,6 +2112,7 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgecontinueassert outcome.status == "ok"if existing is not None and existing.content_hash == outcome.content_hash:+ retained_page = True# No re-chunk needed. Still bump etag if we got a new one.if outcome.etag and existing.etag != outcome.etag:existing.etag = outcome.etag@@ -2121,6 +2133,41 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgeif _count_chunks(team_id) > MAX_CHUNKS_PER_TEAM:raise QuotaExceededError(f"Refresh exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")+ has_live_document = KnowledgeDocument.objects.filter(+ team_id=team_id, source_id=source.id, tombstoned_at__isnull=True+ ).exists()+ # A tombstone sets any_changes, so it must not count as a stored page.+ if not retained_page and (not any_changes or not has_live_document):+ if not discovered:+ error_msg = "Crawl discovered no URLs. Check the entry URL and globs."+ elif not safe_urls:+ error_msg = "Crawl discovered no safe URLs to fetch."+ else:+ error_msg = first_error or "All pages failed to fetch."+ with transaction.atomic():+ fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ now = timezone.now()+ fresh.last_refresh_at = now+ fresh.last_refresh_status = RefreshStatus.ERROR+ fresh.last_refresh_error = error_msg+ if has_live_document:+ fresh.status = SourceStatus.READY+ fresh.error_message = ""+ else:+ fresh.status = SourceStatus.ERROR+ fresh.error_message = error_msg+ fresh.save(+ update_fields=[+ "status",+ "error_message",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "updated_at",+ ]+ )+ return get_for_team(source.id, team_id) or fresh+with transaction.atomic():fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)fresh.status = SourceStatus.READYdiff --git a/products/business_knowledge/backend/tests/test_crawl_ingest.py b/products/business_knowledge/backend/tests/test_crawl_ingest.pyindex 752ff672a440..8fef81961e3a 100644--- a/products/business_knowledge/backend/tests/test_crawl_ingest.py+++ b/products/business_knowledge/backend/tests/test_crawl_ingest.py@@ -692,6 +692,97 @@ class TestRefreshCrawlSource(APIBaseTest):doc_a.refresh_from_db()assert doc_a.content_hash != ""+ def test_failed_refresh_with_no_documents_stays_an_error(self) -> None:+ source = KnowledgeSource.objects.unscoped().create(+ team_id=self.team.id,+ name="Empty crawl",+ source_type="url",+ status=SourceStatus.ERROR,+ error_message="All pages failed to fetch.",+ source_url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ last_refresh_status="error",+ last_refresh_error="All pages failed to fetch.",+ )+ sitemap = _sitemap_xml(["https://example.com/a"])+ behaviours = {"https://example.com/a": url_fetch.UrlFetchError("Remote responded with status 403.")}+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ refreshed = refresh_source(source_id=source.id, team_id=self.team.id)++ assert refreshed is not None+ assert refreshed.status == SourceStatus.ERROR+ assert refreshed.last_refresh_status == "error"+ assert refreshed.error_message == "Remote responded with status 403."+ assert refreshed.last_refresh_error == "Remote responded with status 403."+ assert not KnowledgeDocument.objects.unscoped().filter(source=source).exists()++ def test_failed_refresh_keeps_existing_documents(self) -> None:+ source = self._seed(["https://example.com/a"])+ doc = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/a")+ chunks_before = KnowledgeChunk.objects.unscoped().filter(document_id=doc.id).count()+ assert chunks_before > 0++ sitemap = _sitemap_xml(["https://example.com/a"])+ behaviours = {"https://example.com/a": url_fetch.UrlFetchError("Remote responded with status 403.")}+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ refreshed = refresh_source(source_id=source.id, team_id=self.team.id)++ assert refreshed is not None+ assert refreshed.status == SourceStatus.READY+ assert refreshed.error_message == ""+ assert refreshed.last_refresh_status == "error"+ assert refreshed.last_refresh_error == "Remote responded with status 403."+ doc.refresh_from_db()+ assert doc.tombstoned_at is None+ assert KnowledgeChunk.objects.unscoped().filter(document_id=doc.id).count() == chunks_before++ def test_failed_replacement_does_not_leave_an_empty_ready_source(self) -> None:+ source = self._seed(["https://example.com/a"])+ doc_a = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/a")++ sitemap = _sitemap_xml(["https://example.com/b"])+ behaviours = {"https://example.com/b": url_fetch.UrlFetchError("Remote responded with status 403.")}+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ refreshed = refresh_source(source_id=source.id, team_id=self.team.id)++ assert refreshed is not None+ assert refreshed.status == SourceStatus.ERROR+ assert refreshed.last_refresh_status == "error"+ assert refreshed.error_message == "Remote responded with status 403."+ doc_a.refresh_from_db()+ assert doc_a.tombstoned_at is not None+ assert KnowledgeChunk.objects.unscoped().filter(document_id=doc_a.id).count() == 0+ assert not KnowledgeDocument.objects.unscoped().filter(source=source, tombstoned_at__isnull=True).exists()++ def test_empty_discovery_keeps_existing_documents(self) -> None:+ source = self._seed(["https://example.com/a"])+ doc = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/a")+ chunks_before = KnowledgeChunk.objects.unscoped().filter(document_id=doc.id).count()++ with (+ patch.object(discover, "_http_get_text", return_value=_sitemap_xml([])),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=AssertionError("must not fetch")),+ ):+ refreshed = refresh_source(source_id=source.id, team_id=self.team.id)++ assert refreshed is not None+ assert refreshed.status == SourceStatus.READY+ assert refreshed.last_refresh_status == "error"+ assert refreshed.last_refresh_error == "Crawl discovered no URLs. Check the entry URL and globs."+ doc.refresh_from_db()+ assert doc.tombstoned_at is None+ assert KnowledgeChunk.objects.unscoped().filter(document_id=doc.id).count() == chunks_before+def test_ssrf_block_during_refresh_does_not_tombstone(self) -> None:"""Regression: `discovered_set` was previously built from `outcomes`,