Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.
Python aiai-agentscrawl4ai-cloudcrawlerdata-extractionllmmarkdownmcpopen-sourceplaywrightpythonragscraperweb-crawlerweb-crawlingweb-scraping
fix(deep-crawl): keep the shallowest depth when de-duplicating best-first links
ntohidie5e101183ac7
diff --git a/crawl4ai/deep_crawling/bff_strategy.py b/crawl4ai/deep_crawling/bff_strategy.pyindex 4bc247c0..abf53f05 100644--- a/crawl4ai/deep_crawling/bff_strategy.py+++ b/crawl4ai/deep_crawling/bff_strategy.py@@ -179,11 +179,17 @@ class BestFirstCrawlingStrategy(DeepCrawlStrategy):base_url = normalize_url_for_deep_crawl(url, source_url)if base_url in visited:continue+ # Already queued at an equal or shallower depth: a second entry would+ # be scored and dropped for nothing. A strictly shallower find still+ # has to re-queue, so the URL is crawled at its true distance from the+ # start and its own children stay inside max_depth.+ queued_depth = depths.get(base_url)+ if queued_depth is not None and queued_depth <= new_depth:+ continueif not await self.can_process_url(base_url, new_depth):self.stats.urls_skipped += 1continue- visited.add(base_url)valid_links.append(base_url)# Record the new depths and add to next_links@@ -215,10 +221,6 @@ class BestFirstCrawlingStrategy(DeepCrawlStrategy):self._pages_crawled = self._resume_state.get("pages_crawled", 0)# Restore queue from saved itemsqueue_items = self._resume_state.get("queue_items", [])- # Older checkpoints could hold a URL twice and recorded only crawled- # URLs in "visited"; drop the repeats and treat everything queued as seen.- queue_items = list({item["url"]: item for item in queue_items}.values())- visited.update(item["url"] for item in queue_items)for item in queue_items:await queue.put((item["score"], item["depth"], item["url"], item["parent_url"]))# Initialize shadow list if callback is set@@ -231,7 +233,7 @@ class BestFirstCrawlingStrategy(DeepCrawlStrategy):# Original initializationinitial_score = self.url_scorer.score(start_url) if self.url_scorer else 0await queue.put((-initial_score, 0, start_url, None))- visited: Set[str] = {start_url}+ visited: Set[str] = set()depths: Dict[str, int] = {start_url: 0}# Initialize shadow list if callback is setif self._on_state_change:@@ -268,6 +270,10 @@ class BestFirstCrawlingStrategy(DeepCrawlStrategy):self._queue_shadow.remove(item)except ValueError:pass # Item may have been removed already+ score, depth, url, parent_url = item+ if url in visited:+ continue+ visited.add(url)batch.append(item)if not batch:diff --git a/tests/deep_crawling/test_deep_crawl_perf_2242.py b/tests/deep_crawling/test_deep_crawl_perf_2242.pyindex f2782676..f5371293 100644--- a/tests/deep_crawling/test_deep_crawl_perf_2242.py+++ b/tests/deep_crawling/test_deep_crawl_perf_2242.py@@ -121,7 +121,7 @@ async def test_bfs_level_bookkeeping_scales_linearly():@pytest.mark.asyncioasync def test_best_first_queues_a_shared_url_once():- """Two parents linking to the same page must enqueue it a single time."""+ """Two parents at the same depth must enqueue a shared child only once."""link_map = {ROOT: [f"{ROOT}/a", f"{ROOT}/b"],f"{ROOT}/a": [f"{ROOT}/shared"],@@ -145,3 +145,37 @@ async def test_best_first_queues_a_shared_url_once():for queue in snapshots:assert not [u for u, n in Counter(queue).items() if n > 1], f"duplicate in queue: {queue}"assert sorted(crawled) == sorted(link_map)+++async def test_best_first_keeps_the_shallowest_depth_for_a_shared_url():+ """De-duplicating must not freeze a URL at the depth it was first seen.++ ROOT -> A, B, F0..F11; A -> C; C -> X; B -> X; X -> LEAF++ The scores crawl C before B, so X is discovered first at depth 3 and only+ later at depth 2. The twelve fillers push B out of the first BATCH_SIZE+ pull, which is what lets C run ahead of B - without them both land in one+ batch and the ordering that exposes this never happens.++ If the shallower re-discovery is dropped as a duplicate, X stays at depth 3+ and link_discovery bails at 4 > max_depth, losing LEAF.+ """+ a, b, c, x, leaf = (f"{ROOT}/{p}" for p in ("a", "b", "c", "x", "leaf"))+ fillers = [f"{ROOT}/f{i}" for i in range(12)]+ link_map = {ROOT: [a, b] + fillers, a: [c], c: [x], b: [x], x: [leaf]}+ scores = {a: 0.9, b: 0.1, c: 0.95, x: 0.5, leaf: 0.5, **{f: 0.8 for f in fillers}}++ class DictScorer:+ def score(self, url):+ return scores.get(url, 0.0)++ strategy = BestFirstCrawlingStrategy(max_depth=3, max_pages=100, url_scorer=DictScorer())+ crawled = {+ r.url: r.metadata["depth"]+ async for r in strategy._arun_stream(ROOT, make_crawler(link_map), make_config(stream=True))+ }++ assert crawled[x] == 2, "X must be crawled at its shallowest depth, not the first one seen"+ assert leaf in crawled, "LEAF is within max_depth once X sits at depth 2"+ assert crawled == {ROOT: 0, a: 1, b: 1, c: 2, x: 2, leaf: 3, **{f: 1 for f in fillers}}