: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): write crawl pages in batches (#109050)
Alex V68d43a0a09c5
diff --git a/products/business_knowledge/backend/constants.py b/products/business_knowledge/backend/constants.pyindex dd29b073736f..2040fee6384a 100644--- a/products/business_knowledge/backend/constants.py+++ b/products/business_knowledge/backend/constants.py@@ -56,6 +56,9 @@ MAX_URLS_PER_SOURCE = 5000# Default recursion depth for `same_origin` BFS.DEFAULT_CRAWL_MAX_DEPTH = 2CRAWL_HARD_MAX_DEPTH = 5+# Pages one crawl writes per transaction. A crawl holds at most this many parsed+# pages plus the fetches in flight, not the whole source.+CRAWL_WRITE_BATCH_SIZE = 50# Per-hostname concurrency during a single crawl — prevents us from# hammering an origin. In-process (threading.Semaphore), not cross-worker.PER_HOST_CONCURRENCY = 4diff --git a/products/business_knowledge/backend/crawl.py b/products/business_knowledge/backend/crawl.pyindex e8cf0ded0409..b7fdc147cad4 100644--- a/products/business_knowledge/backend/crawl.py+++ b/products/business_knowledge/backend/crawl.py@@ -9,16 +9,19 @@ Wraps `url_fetch.fetch_url` with:is bigger.- HTML parse hand-off (same `html_parse` used by Stage 2a).- Per-URL outcome records so the caller can upsert / tombstone cleanly.+- A bounded number of fetches in flight, with outcomes yielded as they finish,+ so the caller can write pages in batches instead of holding the whole crawl.Errors per URL are *isolated*: one broken page doesn't tank the batch."""from __future__ import annotations+import timeimport threadingimport urllib.parse as urlparse-from collections.abc import Callable-from concurrent.futures import ALL_COMPLETED, ThreadPoolExecutor, wait+from collections.abc import Callable, Iterator+from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, waitfrom dataclasses import dataclassimport structlog@@ -27,9 +30,9 @@ from . import html_parse, url_fetchfrom .constants import MAX_TEXT_SIZE_BYTES, PER_HOST_CONCURRENCYfrom .url_fetch import sha256_of-# Wall clock for one source's page fetches. A full source at PER_HOST_CONCURRENCY-# has to finish inside the crawl activity, which still discovers URLs and writes-# documents after this wait returns.+# Wall clock for one source's page fetches, including the batch writes the caller+# does between them. A full source at PER_HOST_CONCURRENCY has to finish inside the+# crawl activity, which also discovers URLs and writes the last batch.CRAWL_TOTAL_TIMEOUT_SECONDS = 40 * 60logger = structlog.get_logger(__name__)@@ -154,64 +157,91 @@ def _parse_outcome(url: str, result: url_fetch.FetchResult) -> CrawlOutcome:)-def fetch_many(+def _timeout_outcome(url: str) -> CrawlOutcome:+ logger.warning("business_knowledge.crawl.timeout", url=url)+ return CrawlOutcome(url=url, final_url=url, status="error", error="Crawl total timeout exceeded")+++def iter_fetch(urls: list[str],*,etag_for: Callable[[str], str | None] | None = None,per_host: int = PER_HOST_CONCURRENCY,max_workers: int | None = None,+ max_in_flight: int | None = None,prefetched: dict[str, url_fetch.FetchResult] | None = None,-) -> list[CrawlOutcome]:+) -> Iterator[CrawlOutcome]:"""- Fetch all `urls` in parallel, capped per-host by a threading semaphore.+ Fetch `urls` in parallel, capped per-host by a threading semaphore, and yield+ one outcome per URL in completion order.- `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.+ At most `max_in_flight` URLs are submitted but not yet yielded, so memory+ holds that many parsed pages, not the whole crawl. Fetches keep running+ while the caller handles a yielded outcome.++ `etag_for(url)` — optional; called once per URL, when the URL is submitted,+ 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 wantenough threads to saturate the per-host semaphore without going wild;- the semaphore is the real throttle.+ the semaphore is the real throttle. `max_in_flight` defaults to twice that."""if not urls:- return []+ returnregistry = _PerHostSemaphoreRegistry(per_host)workers = max_workers if max_workers is not None else max(per_host * 4, 8)+ in_flight_cap = max_in_flight if max_in_flight is not None else workers * 2cache = prefetched or {}+ deadline = time.monotonic() + CRAWL_TOTAL_TIMEOUT_SECONDS+ queued = iter(urls)+ in_flight: dict[Future[CrawlOutcome], str] = {}- 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,- prefetched=cache,- ): url- for url in urls- }- done, not_done = wait(futures, timeout=CRAWL_TOTAL_TIMEOUT_SECONDS, return_when=ALL_COMPLETED)- for future in done:- try:- outcome = future.result()- except Exception as exc: # defense in depth — _fetch_one shouldn't raise- url = futures[future]- logger.exception("business_knowledge.crawl.unexpected_error", url=url)- outcome = CrawlOutcome(url=url, final_url=url, status="error", error=str(exc))- results.append(outcome)- for future in not_done:++ def _submit_up_to_cap() -> None:+ while len(in_flight) < in_flight_cap:+ url = next(queued, None)+ if url is None:+ return+ future = pool.submit(+ _fetch_one,+ url,+ etag=(etag_for(url) if etag_for else None),+ registry=registry,+ prefetched=cache,+ )+ in_flight[future] = url++ _submit_up_to_cap()+ while in_flight:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ break+ done, _not_done = wait(in_flight, timeout=remaining, return_when=FIRST_COMPLETED)+ if not done:+ break+ for future in done:+ url = in_flight.pop(future)+ try:+ outcome = future.result()+ except Exception as exc: # defense in depth — _fetch_one shouldn't raise+ logger.exception("business_knowledge.crawl.unexpected_error", url=url)+ outcome = CrawlOutcome(url=url, final_url=url, status="error", error=str(exc))+ yield outcome+ _submit_up_to_cap()++ for future, url in list(in_flight.items()):future.cancel()- url = futures[future]- logger.warning("business_knowledge.crawl.timeout", url=url)- results.append(CrawlOutcome(url=url, final_url=url, status="error", error="Crawl total timeout exceeded"))+ yield _timeout_outcome(url)+ for url in queued:+ yield _timeout_outcome(url)finally:# Don't block on still-running threads — let them drain in the# background. cancel_futures=True drops queued-but-not-started work.pool.shutdown(wait=False, cancel_futures=True)- return resultsdiff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex 63e96fba07af..bb8478639510 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -11,6 +11,7 @@ import datetimefrom collections import defaultdictfrom dataclasses import dataclassfrom functools import reduce+from itertools import batchedfrom operator import or_from typing import Literalfrom urllib.parse import urlsplit@@ -64,6 +65,7 @@ from .constants import (CLASSIFY_MAX_ATTEMPTS,CLASSIFY_MAX_TOTAL_CHARS,CRAWL_HARD_MAX_DEPTH,+ CRAWL_WRITE_BATCH_SIZE,DEFAULT_CRAWL_MAX_DEPTH,DEFAULT_MAX_PAGES,EMBEDDING_STABLE_TS_MAX_AGE,@@ -1828,7 +1830,8 @@ def create_crawl_source(for the same team are serialized.3. Discover candidate URLs via sitemap / same-origin BFS.4. Fetch all candidates in parallel with a per-host semaphore.- 5. In a transaction, bulk-insert documents + chunks and mark READY.+ 5. Insert documents + chunks in batches of `CRAWL_WRITE_BATCH_SIZE` pages,+ one transaction per batch, then mark READY.Failures at any stage update the claim row to ERROR so the user cansee the failure, adjust globs, or retry.@@ -1882,6 +1885,13 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeS)return get_for_team(source.id, team_id) or source+ # A late or duplicate run must not wipe a source that another run already finished.+ if source.status != SourceStatus.PROCESSING:+ return source+ # Batches commit one at a time and chunk ids are deterministic, so a retried+ # activity first drops what the attempt before it wrote, even if it then fails early.+ _delete_crawl_documents(source=source, team_id=team_id)+try:# Re-validate the entry URL (DNS may have rebound between claim and ingest).normalized = _validate_url(source.source_url)@@ -1908,56 +1918,72 @@ def _ingest_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSif not safe_urls:return _mark_error("Crawl discovered no safe URLs to fetch.")- outcomes = crawl.fetch_many(safe_urls, prefetched=discovery.prefetched)- ok_outcomes = [o for o in outcomes if o.status == "ok"]-- if not ok_outcomes:- first_error = next((o.error for o in outcomes if o.status == "error"), "All pages failed to fetch.")- return _mark_error(first_error)-- estimated_total = sum(max(1, len(o.text) // CHUNK_TARGET_CHARS) for o in ok_outcomes)- if _count_chunks(team_id) + estimated_total > MAX_CHUNKS_PER_TEAM:- return _mark_error(f"Crawl would exceed the {MAX_CHUNKS_PER_TEAM} chunk cap.")-+ # Search reads only READY sources, so committed batches stay hidden until the last one lands.+ first_error = ""+ written_any = Falsetry:- with transaction.atomic():- total_chunks_written = 0- for outcome in ok_outcomes:- written = _insert_document_and_chunks(- source=source,- team_id=team_id,- title=outcome.title,- text=outcome.text,- url=outcome.url,- etag=outcome.etag,- content_hash=outcome.content_hash,- existing_doc=None,- )- total_chunks_written += written-- if _count_chunks(team_id) > MAX_CHUNKS_PER_TEAM:- raise QuotaExceededError(f"Crawl exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")+ for batch in batched(+ crawl.iter_fetch(safe_urls, prefetched=discovery.prefetched), CRAWL_WRITE_BATCH_SIZE, strict=False+ ):+ ok_outcomes = [o for o in batch if o.status == "ok"]+ if not first_error:+ first_error = next((o.error for o in batch if o.status == "error"), "")+ if not ok_outcomes:+ continue- source.status = SourceStatus.READY- source.last_refresh_at = timezone.now()- source.last_refresh_status = RefreshStatus.SUCCESS- source.last_refresh_error = ""- source.save(- update_fields=[- "status",- "last_refresh_at",- "last_refresh_status",- "last_refresh_error",- "updated_at",- ]- )+ estimated = sum(max(1, len(o.text) // CHUNK_TARGET_CHARS) for o in ok_outcomes)+ if _count_chunks(team_id) + estimated > MAX_CHUNKS_PER_TEAM:+ _delete_crawl_documents(source=source, team_id=team_id)+ return _mark_error(f"Crawl would exceed the {MAX_CHUNKS_PER_TEAM} chunk cap.")++ with transaction.atomic():+ for outcome in ok_outcomes:+ _insert_document_and_chunks(+ source=source,+ team_id=team_id,+ title=outcome.title,+ text=outcome.text,+ url=outcome.url,+ etag=outcome.etag,+ content_hash=outcome.content_hash,+ existing_doc=None,+ )+ if _count_chunks(team_id) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError(f"Crawl exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")+ written_any = Trueexcept QuotaExceededError:+ _delete_crawl_documents(source=source, team_id=team_id)_mark_error(f"Crawl exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")raise+ except Exception:+ _delete_crawl_documents(source=source, team_id=team_id)+ raise++ if not written_any:+ return _mark_error(first_error or "All pages failed to fetch.")+ source.status = SourceStatus.READY+ source.last_refresh_at = timezone.now()+ source.last_refresh_status = RefreshStatus.SUCCESS+ source.last_refresh_error = ""+ source.save(+ update_fields=[+ "status",+ "last_refresh_at",+ "last_refresh_status",+ "last_refresh_error",+ "updated_at",+ ]+ )return get_for_team(source.id, team_id) or source+def _delete_crawl_documents(*, source: KnowledgeSource, team_id: int) -> None:+ with transaction.atomic():+ KnowledgeChunk.objects.filter(team_id=team_id, source_id=source.id).delete()+ KnowledgeDocument.objects.filter(team_id=team_id, source_id=source.id).delete()++def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> KnowledgeSource | None:"""Crawl refresh: re-discover + per-URL upsert-diff.@@ -2002,9 +2028,10 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledge# Load existing docs keyed by stable_id (== url). Pulling all of them up# front is cheap (we're capped at MAX_URLS_PER_SOURCE) and avoids a- # per-URL query inside the fetch loop.+ # per-URL query inside the fetch loop. `content` stays deferred: loading+ # it would hold the text of every page for the whole refresh.existing_by_url: dict[str, KnowledgeDocument] = {- d.stable_id: d for d in KnowledgeDocument.objects.filter(team_id=team_id, source_id=source.id)+ d.stable_id: d for d in KnowledgeDocument.objects.filter(team_id=team_id, source_id=source.id).defer("content")}# Pre-SSRF the discovered list and preserve ETags per URL for conditional GETs.@@ -2014,12 +2041,13 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgesafe_urls.append(_validate_url(u))except InvalidUrlError:continue+ # 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))def _etag_for(u: str) -> str | None: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, 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@@ -2031,66 +2059,69 @@ def _refresh_crawl_source(*, source: KnowledgeSource, team_id: int) -> Knowledgediscovered_set.add(url_fetch.normalize_url(u))except url_fetch.UrlFetchError:pass-- with transaction.atomic():- fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)-- # Upsert per-outcome.- any_changes = False- for outcome in outcomes:- existing = existing_by_url.get(outcome.url)- if outcome.status == "not_modified":- # Still touch the etag so a rotation stays fresh.- if existing and outcome.etag and existing.etag != outcome.etag:- existing.etag = outcome.etag- existing.save(update_fields=["etag", "updated_at"])- continue- if outcome.status == "error":- # Keep the old doc intact — partial failures shouldn't- # knock out a previously-working page.- logger.info(- "business_knowledge.crawl.refresh_page_error",- source_id=str(source.id),- url=outcome.url,- error=outcome.error,- )- continue- assert outcome.status == "ok"- if existing is not None and existing.content_hash == outcome.content_hash:- # 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- existing.save(update_fields=["etag", "updated_at"])- continue- _insert_document_and_chunks(- source=fresh,- team_id=team_id,- title=outcome.title,- text=outcome.text,- url=outcome.url,- etag=outcome.etag,- content_hash=outcome.content_hash,- existing_doc=existing,- )- any_changes = True-- # Tombstone docs whose URL vanished from discovery. Chunks go away- # now; the sweep hard-deletes the doc row after a grace- # period (preserves the id in case the page comes back soon).- vanished = [d for url, d in existing_by_url.items() if url not in discovered_set]- if vanished:+ vanished_ids = [d.id for url, d in existing_by_url.items() if url not in discovered_set]++ any_changes = 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+ # case the page comes back soon).+ if vanished_ids:+ with transaction.atomic():now = timezone.now()- vanished_ids = [d.id for d in vanished]KnowledgeChunk.objects.filter(team_id=team_id, document_id__in=vanished_ids).delete()KnowledgeDocument.objects.filter(team_id=team_id, id__in=vanished_ids, tombstoned_at__isnull=True).update(tombstoned_at=now, updated_at=now)- any_changes = True+ any_changes = True++ # A refresh that fails part way keeps the batches it already committed. The cap is checked before every commit.+ outcomes = crawl.iter_fetch(safe_urls, etag_for=_etag_for, prefetched=discovery.prefetched)+ for batch in batched(outcomes, CRAWL_WRITE_BATCH_SIZE, strict=False):+ with transaction.atomic():+ fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)+ for outcome in batch:+ existing = existing_by_url.pop(outcome.url, None)+ if outcome.status == "not_modified":+ # Still touch the etag so a rotation stays fresh.+ if existing and outcome.etag and existing.etag != outcome.etag:+ existing.etag = outcome.etag+ existing.save(update_fields=["etag", "updated_at"])+ continue+ if outcome.status == "error":+ # Keep the old doc intact — partial failures shouldn't+ # knock out a previously-working page.+ logger.info(+ "business_knowledge.crawl.refresh_page_error",+ source_id=str(source.id),+ url=outcome.url,+ error=outcome.error,+ )+ continue+ assert outcome.status == "ok"+ if existing is not None and existing.content_hash == outcome.content_hash:+ # 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+ existing.save(update_fields=["etag", "updated_at"])+ continue+ _insert_document_and_chunks(+ source=fresh,+ team_id=team_id,+ title=outcome.title,+ text=outcome.text,+ url=outcome.url,+ etag=outcome.etag,+ content_hash=outcome.content_hash,+ existing_doc=existing,+ )+ any_changes = True- # Exact post-diff quota check.- if _count_chunks(team_id) > MAX_CHUNKS_PER_TEAM:- raise QuotaExceededError(f"Refresh exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")+ if _count_chunks(team_id) > MAX_CHUNKS_PER_TEAM:+ raise QuotaExceededError(f"Refresh exceeded the {MAX_CHUNKS_PER_TEAM} chunk cap.")+ with transaction.atomic():+ fresh = KnowledgeSource.objects.select_for_update().get(id=source.id, team_id=team_id)fresh.status = SourceStatus.READYfresh.last_refresh_at = timezone.now()fresh.last_refresh_status = RefreshStatus.SUCCESS if any_changes else RefreshStatus.NOT_MODIFIEDdiff --git a/products/business_knowledge/backend/tests/test_crawl_ingest.py b/products/business_knowledge/backend/tests/test_crawl_ingest.pyindex d9d092352170..752ff672a440 100644--- a/products/business_knowledge/backend/tests/test_crawl_ingest.py+++ b/products/business_knowledge/backend/tests/test_crawl_ingest.py@@ -25,8 +25,12 @@ from collections.abc import Mappingfrom posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import patch-from products.business_knowledge.backend import crawl, discover, url_fetch-from products.business_knowledge.backend.logic import create_crawl_source, refresh_source+from django.test import SimpleTestCase++from parameterized import parameterized++from products.business_knowledge.backend import crawl, discover, logic, url_fetch+from products.business_knowledge.backend.logic import create_crawl_source, ingest_source, refresh_sourcefrom products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SourceStatus@@ -360,6 +364,26 @@ def _ok(url: str, body: bytes) -> url_fetch.FetchResult:)+class TestIterFetch(SimpleTestCase):+ def test_submits_at_most_max_in_flight_before_the_first_outcome(self) -> None:+ urls = [f"https://example.com/{i}" for i in range(10)]+ fake = _FakeFetch({url: _ok(url, f"<html><body>Page {url}.</body></html>".encode()) for url in urls})+ submitted: list[str] = []++ def _etag_for(url: str) -> None:+ submitted.append(url)+ return None++ with patch.object(crawl.url_fetch, "fetch_url", side_effect=fake):+ outcomes = crawl.iter_fetch(urls, etag_for=_etag_for, max_workers=4, max_in_flight=2)+ first = next(outcomes)+ assert len(submitted) == 2+ rest = list(outcomes)++ assert sorted(o.url for o in [first, *rest]) == sorted(urls)+ assert all(o.status == "ok" for o in [first, *rest])++class TestCreateCrawlSource(APIBaseTest):def test_happy_path_indexes_all_discovered_pages(self) -> None:sitemap = _sitemap_xml(["https://example.com/a", "https://example.com/b", "https://example.com/c"])@@ -387,6 +411,92 @@ class TestCreateCrawlSource(APIBaseTest):assert all(d.content_hash for d in docs)assert KnowledgeChunk.objects.unscoped().filter(source=source).count() >= 3+ def test_chunk_cap_hit_in_a_later_batch_leaves_no_documents(self) -> None:+ urls = ["https://example.com/a", "https://example.com/b"]+ behaviours = {url: _ok(url, f"<html><body>Body of {url}.</body></html>".encode()) for url in urls}+ with (+ patch.object(discover, "_http_get_text", return_value=_sitemap_xml(urls)),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ patch.object(logic, "CRAWL_WRITE_BATCH_SIZE", 1),+ patch.object(logic, "MAX_CHUNKS_PER_TEAM", 1),+ ):+ source = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Handbook",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )+ assert source.status == SourceStatus.ERROR+ assert "would exceed" in source.error_message+ assert not KnowledgeDocument.objects.unscoped().filter(source=source).exists()+ assert not KnowledgeChunk.objects.unscoped().filter(source=source).exists()++ @parameterized.expand(+ [+ ("retry_succeeds", False, SourceStatus.READY, 2),+ ("retry_fails_discovery", True, SourceStatus.ERROR, 0),+ ]+ )+ def test_retried_ingest_replaces_rows_from_the_attempt_before(+ self, _name: str, discovery_fails: bool, expected_status: str, expected_docs: int+ ) -> None:+ urls = ["https://example.com/a", "https://example.com/b"]+ behaviours = {url: _ok(url, f"<html><body>Body of {url}.</body></html>".encode()) for url in urls}+ with (+ patch.object(discover, "_http_get_text", return_value=_sitemap_xml(urls)),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ source = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Handbook",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )+ chunks_before = KnowledgeChunk.objects.unscoped().filter(source=source).count()+ KnowledgeSource.objects.unscoped().filter(id=source.id).update(status=SourceStatus.PROCESSING)++ discovery_effect = discover.DiscoverError("Sitemap unreachable.") if discovery_fails else None+ with (+ patch.object(discover, "_http_get_text", return_value=_sitemap_xml(urls), side_effect=discovery_effect),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ retried = ingest_source(source_id=source.id, team_id=self.team.id)++ assert retried is not None+ assert retried.status == expected_status+ assert KnowledgeDocument.objects.unscoped().filter(source=source).count() == expected_docs+ assert KnowledgeChunk.objects.unscoped().filter(source=source).count() == (+ chunks_before if expected_docs else 0+ )++ def test_ingest_of_a_finished_source_keeps_its_rows(self) -> None:+ urls = ["https://example.com/a"]+ behaviours = {url: _ok(url, f"<html><body>Body of {url}.</body></html>".encode()) for url in urls}+ with (+ patch.object(discover, "_http_get_text", return_value=_sitemap_xml(urls)),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ ):+ source = create_crawl_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Handbook",+ url="https://example.com/sitemap.xml",+ crawl_mode="sitemap",+ crawl_config={"max_pages": 10},+ )+ chunks_before = KnowledgeChunk.objects.unscoped().filter(source=source).count()++ with patch.object(discover, "_http_get_text", side_effect=AssertionError("must not rediscover")):+ again = ingest_source(source_id=source.id, team_id=self.team.id)++ assert again is not None+ assert again.status == SourceStatus.READY+ assert KnowledgeChunk.objects.unscoped().filter(source=source).count() == chunks_before+def test_zero_safe_urls_returns_error_source(self) -> None:sitemap = _sitemap_xml(["http://127.0.0.1/secret"])with patch.object(discover, "_http_get_text", return_value=sitemap):@@ -498,6 +608,7 @@ class TestRefreshCrawlSource(APIBaseTest):with (patch.object(discover, "_http_get_text", return_value=sitemap),patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ patch.object(logic, "CRAWL_WRITE_BATCH_SIZE", 1),):refresh_source(source_id=source.id, team_id=self.team.id)@@ -534,6 +645,30 @@ class TestRefreshCrawlSource(APIBaseTest):assert KnowledgeChunk.objects.unscoped().filter(document_id=doc_b.id).count() == 0assert KnowledgeDocument.objects.unscoped().filter(id=doc_b.id).exists()+ def test_vanished_page_chunks_do_not_count_against_the_cap(self) -> None:+ source = self._seed(["https://example.com/a", "https://example.com/b"])+ doc_b = KnowledgeDocument.objects.unscoped().get(source=source, stable_id="https://example.com/b")+ at_cap = KnowledgeChunk.objects.unscoped().filter(team_id=self.team.id).count()++ sitemap = _sitemap_xml(["https://example.com/a", "https://example.com/c"])+ behaviours = {+ url: _ok(url, f"<html><body>body of {url}</body></html>".encode())+ for url in ["https://example.com/a", "https://example.com/c"]+ }+ with (+ patch.object(discover, "_http_get_text", return_value=sitemap),+ patch.object(crawl.url_fetch, "fetch_url", side_effect=_FakeFetch(behaviours)),+ patch.object(logic, "MAX_CHUNKS_PER_TEAM", at_cap),+ ):+ refresh_source(source_id=source.id, team_id=self.team.id)++ source.refresh_from_db()+ doc_b.refresh_from_db()+ assert source.status == SourceStatus.READY+ assert source.last_refresh_error == ""+ assert doc_b.tombstoned_at is not None+ assert KnowledgeDocument.objects.unscoped().filter(source=source, stable_id="https://example.com/c").exists()+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")