Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(downloads): host-level attempt budget stops the fallback chain after a rate-limited static fetch (#7352)

LearningCircuit42a9087b9713
diff --git a/changelog.d/7335.bugfix.md b/changelog.d/7335.bugfix.md
new file mode 100644
index 0000000000..fb82c7e642
--- /dev/null
+++ b/changelog.d/7335.bugfix.md
@@ -0,0 +1 @@
+The download fallback chain now honors a host-level attempt budget: when the static fetch gives up on HTTP 429/503 after its retries, the Auto-downloader skips its SPA probe and the browser-navigation fallback for that host instead of piling further requests onto a rate-limiting host for one URL. `download_with_result` reports a rate-limited skip reason for a URL whose own static fetch gave up on 429/503, and a later URL on a host an earlier URL marked keeps its own result.
diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.py
index 06639cac4a..595ec8ac5b 100644
--- a/src/local_deep_research/research_library/downloaders/html.py
+++ b/src/local_deep_research/research_library/downloaders/html.py
@@ -286,15 +286,23 @@ class HTMLDownloader(BaseDownloader):
# credentialed URL).
return DownloadResult(skip_reason=_client_safe_html_message(e))
- def _fetch_html(self, url: str) -> Optional[str]:
+ def _fetch_html(
+ self,
+ url: str,
+ *,
+ on_rate_limited: Optional[Callable[[], None]] = None,
+ ) -> Optional[str]:
"""Fetch raw HTML content from URL."""
- return self._fetch_html_with_final_url(url)[0]
+ return self._fetch_html_with_final_url(
+ url, on_rate_limited=on_rate_limited
+ )[0]
def _fetch_html_with_final_url(
self,
url: str,
*,
on_transport_failure: Optional[Callable[[], None]] = None,
+ on_rate_limited: Optional[Callable[[], None]] = None,
max_attempts: int = 3,
) -> tuple[Optional[str], Optional[str]]:
"""Fetch raw HTML together with the URL that finally served it.
@@ -332,6 +340,15 @@ class HTMLDownloader(BaseDownloader):
body aborts mid-read never got to answer, and is reported as the
transport failure it is. When given, the failure is logged
as a warning rather than an error, since the caller handles it.
+
+ ``on_rate_limited`` is called once when the fetch gives up on
+ HTTP 429/503 after exhausting ``max_attempts`` (mirroring
+ ``BaseDownloader._download_pdf``): a chain owner uses it to stop
+ sending further requests to that host. Only the caller can stop
+ the later legs of the fallback chain: the probe GET applies no
+ rate limiting, and the browser leg backs off only on its own
+ tracker buckets, which never see the 429/503 outcomes this fetch
+ records.
"""
# Fresh per-fetch recovery state. Cleared on entry so a stale stash
# from an earlier fetch can never leak into this one; consumption
@@ -508,6 +525,12 @@ class HTMLDownloader(BaseDownloader):
and status not in _DOCUMENT_ABSENT_STATUSES
):
on_transport_failure()
+ if status in (429, 503) and on_rate_limited is not None:
+ # Fires exactly once: this branch is terminal (the
+ # retried 429/503s never reach it — see the NOTE above).
+ # Mirrors ``BaseDownloader._download_pdf``: the caller
+ # stops sending further requests to this host.
+ on_rate_limited()
return None, None
finally:
# stream=True leaves the connection unreleased until the
diff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.py
index 73dbf4b3fb..7efa95a287 100644
--- a/src/local_deep_research/research_library/downloaders/playwright_html.py
+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py
@@ -1354,6 +1354,40 @@ class AutoHTMLDownloader(HTMLDownloader):
if hasattr(self.session, "block_link_local"):
self.session.block_link_local = block_link_local
self._playwright_downloader = None
+ # Host-level attempt budget for the fallback chain. The static leg
+ # backs off adaptively and bounds its retries, but its 429/503
+ # outcomes never reach the later legs: the probe GET applies no
+ # rate limiting, and the browser leg backs off only on its own
+ # tracker buckets (playwright_download_/crawl4ai_download_), which
+ # never see the static leg's html_download_ outcomes. When the
+ # static leg gives up with HTTP 429/503, the host's authority is
+ # marked here for the rest of this downloader's life
+ # (fetch_and_extract creates one per URL; batch_fetch_and_extract
+ # and ContentFetcher share one across several URLs), and the probe
+ # and browser legs are skipped for that host from then on. The
+ # static leg still runs for each later URL, and the mark never
+ # rewrites that URL's result. One user action must not keep
+ # sending requests to a host that is asking us to stop.
+ self._rate_limited_hosts: set[str] = set()
+ # Whether the static fetch of the URL that download_with_result()
+ # is working on gave up on 429/503 itself, as opposed to an earlier
+ # URL having marked its host. It is per call (download_with_result()
+ # clears it on entry), and is what lets that method report a
+ # rate-limited skip reason only for the URL that earned it.
+ self._static_fetch_rate_limited = False
+
+ def _host_rate_limited(self, url: str) -> bool:
+ """Whether a static fetch already gave up on 429/503 for this host."""
+ return rate_limit_authority(url) in self._rate_limited_hosts
+
+ def _note_host_rate_limited(self, url: str) -> None:
+ """Record that the static leg exhausted its retries on 429/503.
+
+ Marks the host for the rest of this downloader's life and flags the
+ fetch in progress (``_static_fetch_rate_limited``).
+ """
+ self._rate_limited_hosts.add(rate_limit_authority(url))
+ self._static_fetch_rate_limited = True
def _get_playwright_downloader(self) -> PlaywrightHTMLDownloader:
"""Lazy-init JS rendering downloader for fallback."""
@@ -1385,8 +1419,12 @@ class AutoHTMLDownloader(HTMLDownloader):
in fetch_and_extract/batch_fetch_and_extract — not shared across threads.
"""
self._last_raw_html = None
- # Try the normal static fetch
- html = super()._fetch_html(url)
+ # Try the normal static fetch. ``on_rate_limited`` fires when the
+ # static leg exhausts its retries on 429/503, so the host is
+ # marked before any later leg runs.
+ html = super()._fetch_html(
+ url, on_rate_limited=lambda: self._note_host_rate_limited(url)
+ )
if html:
self._last_raw_html = html
return html
@@ -1400,6 +1438,16 @@ class AutoHTMLDownloader(HTMLDownloader):
):
return None
+ # Host-level budget: a static fetch to this host gave up on
+ # 429/503 — do not spend the probe request on a host that asked us
+ # to stop.
+ if self._host_rate_limited(url):
+ logger.debug(
+ "auto_html.host_rate_limited_probe_skipped url={url}",
+ url=redact_url_for_log(url),
+ )
+ return None
+
# Static fetch failed (403, etc.) — try raw GET to check for
# challenge pages / SPA signals even on non-200 responses
try:
@@ -1444,6 +1492,16 @@ class AutoHTMLDownloader(HTMLDownloader):
)
return result
+ # Host-level budget: a static fetch to this host gave up on
+ # 429/503, and the browser leg's own rate limiting never sees those
+ # outcomes — do not send it to a host that asked us to stop.
+ if self._host_rate_limited(url):
+ logger.debug(
+ "auto_html.host_rate_limited_js_fallback_skipped url={url}",
+ url=redact_url_for_log(url),
+ )
+ return result
+
# Check if we should retry with JS rendering
raw_html = getattr(self, "_last_raw_html", None)
needs_js = raw_html and self._has_spa_signals(raw_html)
@@ -1481,11 +1539,15 @@ class AutoHTMLDownloader(HTMLDownloader):
def download_with_result(self, url, content_type=None):
"""Try static fetch, fall back to JS rendering if needed."""
- from .base import ContentType
+ from .base import ContentType, DownloadResult
if content_type is None:
content_type = ContentType.TEXT
+ # The host mark outlives this call, this flag does not: clear it
+ # before anything can set it, so it can only describe this URL.
+ self._static_fetch_rate_limited = False
+
# First: try static fetch (fast)
logger.debug(
"auto_html.static_fetch_started url={url}",
@@ -1505,6 +1567,28 @@ class AutoHTMLDownloader(HTMLDownloader):
)
return result
+ # Host-level budget: a static fetch to this host gave up on
+ # 429/503, and the browser leg's own rate limiting never sees those
+ # outcomes — do not send it to a host that asked us to stop. Only
+ # the fallback legs are skipped, as in download().
+ if self._host_rate_limited(url):
+ logger.debug(
+ "auto_html.host_rate_limited_js_fallback_skipped url={url}",
+ url=redact_url_for_log(url),
+ )
+ if self._static_fetch_rate_limited:
+ # This URL's own static fetch gave up on 429/503: say so in
+ # place of the generic fetch failure.
+ return DownloadResult(
+ skip_reason=(
+ "Host rate-limited the static fetch (HTTP 429/503 "
+ "after retries); skipping fallback legs"
+ )
+ )
+ # An earlier URL marked the host. That says nothing about this
+ # URL, so it keeps its own static result, success or failure.
+ return result
+
# Check if we should retry with JS rendering
raw_html = getattr(self, "_last_raw_html", None)
needs_js = raw_html and self._has_spa_signals(raw_html)
diff --git a/tests/research_library/downloaders/test_playwright_html.py b/tests/research_library/downloaders/test_playwright_html.py
index dbe58d9b3f..ccec1ac1d2 100644
--- a/tests/research_library/downloaders/test_playwright_html.py
+++ b/tests/research_library/downloaders/test_playwright_html.py
@@ -10,6 +10,10 @@ from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
+from local_deep_research.research_library.downloaders.base import (
+ ContentType,
+ DownloadResult,
+)
from local_deep_research.research_library.downloaders.playwright_html import (
AutoHTMLDownloader,
PlaywrightHTMLDownloader,
@@ -136,6 +140,217 @@ class TestAutoDownloaderFallbackLogic:
dl.close()
+class TestHostRateLimitBudget:
+ """The chain owner caps per-URL requests to a rate-limiting host.
+
+ A host answering 429/503 to everything must see only the static
+ leg's budgeted attempts (3) for one URL — no probe GET, no browser
+ navigation — and the terminal outcome must classify as rate-limited.
+ """
+
+ # ``download`` is the bytes path both extraction pipelines call.
+ @pytest.mark.parametrize("entry", ["download", "download_with_result"])
+ def test_rate_limited_host_gets_no_probe_or_navigation(self, entry):
+ """429 on every request: 3 static attempts, then the chain stops."""
+ dl = AutoHTMLDownloader(
+ timeout=5, min_content_length=200, enable_js_rendering=True
+ )
+
+ calls = []
+
+ def _rate_limited_response(url, **kwargs):
+ calls.append(url)
+ response = Mock()
+ response.status_code = 429
+ response.headers = {}
+ response.text = ""
+ response.url = url
+ return response
+
+ session = Mock(egress_context=None)
+ session.get.side_effect = _rate_limited_response
+ dl.session = session
+ # Neutralize adaptive waits so the retried attempts don't sleep.
+ dl.rate_tracker = Mock()
+ dl.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ pw = Mock()
+ pw.download.return_value = None
+ pw.download_with_result.return_value = DownloadResult(
+ content=None, is_success=False
+ )
+ dl._playwright_downloader = pw
+
+ try:
+ result = getattr(dl, entry)(
+ "https://rate-limited.example.com/paper"
+ )
+ finally:
+ dl.close()
+
+ # The host-level budget: exactly the static leg's 3 attempts —
+ # no probe GET (would be a 4th session.get), no navigation.
+ assert len(calls) == 3
+ pw.download.assert_not_called()
+ pw.download_with_result.assert_not_called()
+ if entry == "download":
+ assert result is None
+ else:
+ # The terminal outcome classifies as rate-limited.
+ assert "rate-limited" in (result.skip_reason or "").lower()
+
+
+def _shared_host_downloader(responses):
+ """One downloader reused across URLs, over a session stub keyed by URL.
+
+ ``responses`` maps each URL to ``(status, html)``. Every request to a
+ URL is answered the same way, so a 429 URL exhausts the static leg's
+ three attempts. ``min_content_length`` is far above anything the stub
+ pages extract to, so every successful fetch is a short one. Returns
+ ``(downloader, requested_urls, browser_stub)``.
+ """
+ dl = AutoHTMLDownloader(
+ timeout=5, min_content_length=10_000, enable_js_rendering=True
+ )
+ requested = []
+
+ def _answer(url, **kwargs):
+ requested.append(url)
+ status, html = responses[url]
+ response = Mock()
+ response.status_code = status
+ response.headers = {"content-type": "text/html; charset=utf-8"}
+ response.text = html
+ response.url = url
+ return response
+
+ session = Mock(egress_context=None)
+ session.get.side_effect = _answer
+ dl.session = session
+ # Neutralize adaptive waits so the retried attempts don't sleep.
+ dl.rate_tracker = Mock()
+ dl.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ pw = Mock()
+ pw.download.return_value = None
+ pw.download_with_result.return_value = DownloadResult(
+ content=None, is_success=False
+ )
+ dl._playwright_downloader = pw
+ return dl, requested, pw
+
+
+class TestHostRateLimitBudgetSharedInstance:
+ """A host marked by one URL never rewrites a later URL's own result.
+
+ ``ContentFetcher`` caches one downloader per URL type and
+ ``batch_fetch_and_extract`` shares one across its batch, so the
+ host-level mark outlives the URL that set it. It only skips the probe
+ and browser legs for later URLs on that host. Whatever a later URL's
+ own static fetch produced (a short success, a 404, an unsupported
+ request) comes back unchanged from both entry points, and only a URL
+ whose own static fetch gave up on 429/503 is reported as rate-limited.
+ """
+
+ HOST = "https://shared-host.example.com"
+ LIMITED = f"{HOST}/limited"
+ LIMITED_AGAIN = f"{HOST}/limited-again"
+ SHORT = f"{HOST}/short"
+ MISSING = f"{HOST}/missing"
+ RESPONSES = {
+ LIMITED: (429, ""),
+ LIMITED_AGAIN: (429, ""),
+ SHORT: (
+ 200,
+ f"<html><body><article><p>{LONG_PARA}</p></article></body></html>",
+ ),
+ MISSING: (404, ""),
+ }
+
+ @classmethod
+ def _host_marked_by_first_url(cls, entry):
+ """A shared downloader whose host an earlier URL already marked."""
+ dl, requested, pw = _shared_host_downloader(cls.RESPONSES)
+ getattr(dl, entry)(cls.LIMITED)
+ # Terminal 429: exactly the static leg's three attempts.
+ assert requested == [cls.LIMITED] * 3
+ return dl, requested, pw
+
+ @pytest.mark.parametrize("entry", ["download", "download_with_result"])
+ def test_later_url_keeps_its_short_success(self, entry):
+ """A short 200 is below min_content_length but still the answer."""
+ dl, requested, pw = self._host_marked_by_first_url(entry)
+ try:
+ result = getattr(dl, entry)(self.SHORT)
+ finally:
+ dl.close()
+
+ if entry == "download_with_result":
+ assert result.is_success
+ assert result.skip_reason is None
+ result = result.content
+ assert result is not None
+ assert b"sufficiently long paragraph" in result
+ # The later URL gets its static leg only: no probe, no navigation.
+ assert requested[3:] == [self.SHORT]
+ pw.download.assert_not_called()
+ pw.download_with_result.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("url", "content_type", "reason", "later_requests"),
+ [
+ (
+ MISSING,
+ ContentType.TEXT,
+ "Failed to fetch HTML content from URL",
+ [MISSING],
+ ),
+ (
+ SHORT,
+ ContentType.PDF,
+ "HTML downloader does not support PDF downloads",
+ [],
+ ),
+ ],
+ ids=["404", "pdf-request"],
+ )
+ def test_later_url_keeps_its_own_failure_reason(
+ self, url, content_type, reason, later_requests
+ ):
+ """A later failure is its own, not the host's history."""
+ dl, requested, pw = self._host_marked_by_first_url(
+ "download_with_result"
+ )
+ try:
+ result = dl.download_with_result(url, content_type)
+ finally:
+ dl.close()
+
+ assert not result.is_success
+ assert result.skip_reason == reason
+ assert requested[3:] == later_requests
+ pw.download.assert_not_called()
+ pw.download_with_result.assert_not_called()
+
+ @pytest.mark.parametrize("entry", ["download", "download_with_result"])
+ def test_later_url_that_is_itself_rate_limited_reports_it(self, entry):
+ """Its own 429/503 give-up is reported even on an already-marked host."""
+ dl, requested, pw = self._host_marked_by_first_url(entry)
+ try:
+ result = getattr(dl, entry)(self.LIMITED_AGAIN)
+ finally:
+ dl.close()
+
+ # Its own three static attempts and nothing more.
+ assert requested[3:] == [self.LIMITED_AGAIN] * 3
+ pw.download.assert_not_called()
+ pw.download_with_result.assert_not_called()
+ if entry == "download":
+ assert result is None
+ else:
+ assert "rate-limited" in (result.skip_reason or "").lower()
+
+
class TestPlaywrightDownloaderClose:
"""Tests for resource cleanup."""