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(safe-requests): retry body-stream transients via consume_body opt-in (#3647)

LearningCircuit60c065171983
diff --git a/src/local_deep_research/journal_quality/data_sources/doaj.py b/src/local_deep_research/journal_quality/data_sources/doaj.py
index 8f387f2142..4da9b7ea5e 100644
--- a/src/local_deep_research/journal_quality/data_sources/doaj.py
+++ b/src/local_deep_research/journal_quality/data_sources/doaj.py
@@ -60,7 +60,11 @@ class DOAJSource(DataSource):
logger.info(f"Fetching DOAJ public CSV dump: {_DOAJ_CSV_URL}")
start = time.time()
- resp = safe_get(_DOAJ_CSV_URL, timeout=120)
+ # consume_body: the CSV is ~25 MB, so a mid-stream
+ # ChunkedEncodingError / ReadTimeout is a realistic failure
+ # mode worth retrying. Without this flag the body-read fires
+ # outside safe_get_with_retries' retry loop.
+ resp = safe_get(_DOAJ_CSV_URL, timeout=120, consume_body=True)
resp.raise_for_status()
# DOAJ serves UTF-8 CSV. Parse in-memory — the whole file is
diff --git a/src/local_deep_research/journal_quality/data_sources/institutions.py b/src/local_deep_research/journal_quality/data_sources/institutions.py
index ecd6ea75aa..247c6d1214 100644
--- a/src/local_deep_research/journal_quality/data_sources/institutions.py
+++ b/src/local_deep_research/journal_quality/data_sources/institutions.py
@@ -73,7 +73,11 @@ class InstitutionSource(DataSource):
f"Fetching OpenAlex institutions manifest: "
f"{_OPENALEX_INSTITUTIONS_MANIFEST}"
)
- manifest_resp = safe_get(_OPENALEX_INSTITUTIONS_MANIFEST, timeout=30)
+ # consume_body=True: small JSON but serial bottleneck — a body
+ # transient here aborts the whole 10-min institutions pull.
+ manifest_resp = safe_get(
+ _OPENALEX_INSTITUTIONS_MANIFEST, timeout=30, consume_body=True
+ )
manifest_resp.raise_for_status()
manifest = manifest_resp.json()
diff --git a/src/local_deep_research/journal_quality/data_sources/jabref.py b/src/local_deep_research/journal_quality/data_sources/jabref.py
index f6487d7b61..4a8e2611e6 100644
--- a/src/local_deep_research/journal_quality/data_sources/jabref.py
+++ b/src/local_deep_research/journal_quality/data_sources/jabref.py
@@ -63,7 +63,7 @@ class JabRefSource(DataSource):
for filename in _JABREF_FILES:
url = f"{_JABREF_BASE}/{filename}"
try:
- resp = safe_get(url, timeout=30)
+ resp = safe_get(url, timeout=30, consume_body=True)
resp.raise_for_status()
reader = csv.reader(io.StringIO(resp.text))
for row in reader:
diff --git a/src/local_deep_research/journal_quality/data_sources/openalex.py b/src/local_deep_research/journal_quality/data_sources/openalex.py
index 45da318491..47771e6e48 100644
--- a/src/local_deep_research/journal_quality/data_sources/openalex.py
+++ b/src/local_deep_research/journal_quality/data_sources/openalex.py
@@ -84,7 +84,12 @@ class OpenAlexSource(DataSource):
logger.info(
f"Fetching OpenAlex sources manifest: {_OPENALEX_SOURCES_MANIFEST}"
)
- manifest_resp = safe_get(_OPENALEX_SOURCES_MANIFEST, timeout=30)
+ # consume_body=True: the manifest is small but a serial
+ # bottleneck for the whole download. A body-read transient
+ # here aborts everything.
+ manifest_resp = safe_get(
+ _OPENALEX_SOURCES_MANIFEST, timeout=30, consume_body=True
+ )
manifest_resp.raise_for_status()
manifest = manifest_resp.json()
diff --git a/src/local_deep_research/journal_quality/data_sources/predatory.py b/src/local_deep_research/journal_quality/data_sources/predatory.py
index b071e263e8..31a4e22989 100644
--- a/src/local_deep_research/journal_quality/data_sources/predatory.py
+++ b/src/local_deep_research/journal_quality/data_sources/predatory.py
@@ -69,7 +69,7 @@ class PredatorySource(DataSource):
def _read_csv(filename: str) -> list[dict]:
url = f"{_PREDATORY_BASE}/{filename}"
- resp = safe_get(url, timeout=30)
+ resp = safe_get(url, timeout=30, consume_body=True)
resp.raise_for_status()
reader = csv.DictReader(io.StringIO(resp.text))
return [
diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.py
index 6cd1e54fad..995b62cada 100644
--- a/src/local_deep_research/security/safe_requests.py
+++ b/src/local_deep_research/security/safe_requests.py
@@ -15,6 +15,7 @@ from loguru import logger
from . import ssrf_validator
from ..constants import USER_AGENT
+from ..utilities.resource_utils import safe_close
# Default timeout for all HTTP requests (prevents hanging)
@@ -577,6 +578,7 @@ def safe_get_with_retries(
allow_private_ips: bool = False,
max_retries: int = 3,
backoff_times: tuple = _RETRY_BACKOFF_SECONDS,
+ consume_body: bool = False,
**kwargs,
) -> requests.Response:
"""`safe_get` plus exponential-backoff retry on transient errors.
@@ -585,11 +587,24 @@ def safe_get_with_retries(
* ``requests.ConnectionError``
* ``requests.Timeout``
* HTTP ``429`` (rate limit) and ``5xx`` (server error)
+ * (when ``consume_body=True``) body-read failures —
+ ``ChunkedEncodingError``, ``ReadTimeout``, mid-stream
+ ``ConnectionError``
Honors the ``Retry-After`` header when present (falls back to the
backoff schedule otherwise). SSRF-validation errors (``ValueError``)
and non-retryable HTTP 4xx responses are not retried.
+ Without ``consume_body``, only failures raised inside ``safe_get``
+ itself (DNS, connect, header timeout, retryable status) trigger a
+ retry. The body isn't read until the caller touches ``.content`` /
+ ``.text`` / ``.json()``, by which point this wrapper has already
+ returned — so a mid-stream S3 hiccup (``ChunkedEncodingError``)
+ propagates uncaught. ``consume_body=True`` reads the body inside
+ the retry loop so those transient body-read failures are also
+ retried. The cached body is still available to the caller via
+ ``response.content`` after the wrapper returns.
+
Args:
url: Target URL.
params: Query parameters.
@@ -598,13 +613,22 @@ def safe_get_with_retries(
allow_private_ips: Forwarded to ``safe_get``.
max_retries: Maximum retry attempts after the initial try.
backoff_times: Per-attempt sleep seconds.
+ consume_body: If True, read ``response.content`` inside the
+ retry loop so body-read transients are retried. Use for
+ large or chunk-transferred bodies (~MB+) where mid-stream
+ disconnects are realistic. The body-guard's ``ValueError``
+ (oversized body) is NOT retried — it propagates immediately.
**kwargs: Forwarded to ``safe_get``.
Returns:
The first successful (or final-attempt) ``requests.Response``.
+ When ``consume_body=True``, the body has already been read and
+ is cached on the response.
Raises:
- ValueError: If SSRF validation fails — retries do not help here.
+ ValueError: If SSRF validation fails or, with
+ ``consume_body=True``, the body-guard rejects an oversized
+ response. Retries do not help in either case.
requests.RequestException: If every attempt fails.
"""
attempt = 0
@@ -650,4 +674,36 @@ def safe_get_with_retries(
attempt += 1
continue
+ if consume_body:
+ try:
+ # Force body read while still inside the retry loop.
+ # ChunkedEncodingError / ReadTimeout / mid-stream
+ # ConnectionError can fire here on large responses
+ # from flaky upstreams. ReadTimeout is a Timeout
+ # subclass but NOT a ConnectionError subclass, so the
+ # except must list both ConnectionError and Timeout
+ # — listing Timeout alone would miss ConnectError, and
+ # listing ConnectionError alone would miss ReadTimeout.
+ _ = response.content
+ except (
+ requests.exceptions.ChunkedEncodingError,
+ requests.exceptions.ConnectionError,
+ requests.exceptions.Timeout,
+ ) as exc:
+ # safe_close instead of bare close: a close() that
+ # raises here would mask the original body-read error
+ # we actually want to surface / retry on.
+ safe_close(response, "response")
+ if attempt >= max_retries:
+ raise
+ wait = backoff_times[min(attempt, len(backoff_times) - 1)]
+ logger.warning(
+ f"{exc.__class__.__name__} reading body of {url}; "
+ f"retrying in {wait}s "
+ f"(attempt {attempt + 1}/{max_retries})"
+ )
+ time.sleep(wait)
+ attempt += 1
+ continue
+
return response
diff --git a/tests/security/test_safe_requests_retries.py b/tests/security/test_safe_requests_retries.py
index 2c2e75b4e0..afe22dae70 100644
--- a/tests/security/test_safe_requests_retries.py
+++ b/tests/security/test_safe_requests_retries.py
@@ -12,10 +12,25 @@ from local_deep_research.security.safe_requests import (
)
-def _mock_response(status_code=200, headers=None):
+def _mock_response(status_code=200, headers=None, content=b""):
r = MagicMock(spec=requests.Response)
r.status_code = status_code
r.headers = headers or {}
+ r.content = content
+ return r
+
+
+def _mock_response_body_raises(exc):
+ """Response whose ``.content`` access raises ``exc`` on first read.
+
+ Models the real production failure where ``safe_get`` returns a
+ Response (headers received), then ``ChunkedEncodingError`` /
+ ``ReadTimeout`` fires later when the body is consumed.
+ """
+ r = MagicMock(spec=requests.Response)
+ r.status_code = 200
+ r.headers = {}
+ type(r).content = property(lambda self: (_ for _ in ()).throw(exc))
return r
@@ -204,3 +219,147 @@ def test_retry_after_negative_integer_is_clamped_to_zero():
):
safe_get_with_retries("https://example.com/x", backoff_times=(1, 1, 1))
assert mock_sleep.call_args[0][0] == 0
+
+
+# ---------------------------------------------------------------------------
+# consume_body=True: retry on body-stream transients
+# ---------------------------------------------------------------------------
+
+
+def test_consume_body_default_does_not_read_body():
+ """Default (``consume_body=False``) must not touch ``response.content``.
+
+ The wrapper has historically returned the response without reading
+ the body. Callers that stream large bodies (e.g., NDJSON line-by-line)
+ rely on this — a regression that pre-reads would balloon memory.
+ """
+ body_marker = MagicMock()
+ body_marker.__bool__ = MagicMock(side_effect=AssertionError("touched"))
+ resp = _mock_response(200)
+ type(resp).content = property(lambda self: body_marker)
+
+ with patch(
+ "local_deep_research.security.safe_requests.safe_get",
+ return_value=resp,
+ ):
+ # Should not raise — default behavior leaves .content untouched.
+ safe_get_with_retries("https://example.com/x")
+
+
+def test_consume_body_retries_on_chunked_encoding_error():
+ """Mid-stream ``ChunkedEncodingError`` retries the whole fetch."""
+ bad = _mock_response_body_raises(
+ requests.exceptions.ChunkedEncodingError(
+ "IncompleteRead(835082 bytes read, 1262437 more expected)"
+ )
+ )
+ ok = _mock_response(200, content=b"final")
+ with (
+ patch(
+ "local_deep_research.security.safe_requests.safe_get",
+ side_effect=[bad, ok],
+ ) as mock_get,
+ patch("local_deep_research.security.safe_requests.time.sleep"),
+ ):
+ resp = safe_get_with_retries(
+ "https://example.com/x",
+ consume_body=True,
+ backoff_times=(0, 0, 0),
+ )
+ assert resp.content == b"final"
+ assert mock_get.call_count == 2
+ bad.close.assert_called_once()
+
+
+def test_consume_body_retries_on_read_timeout():
+ """``ReadTimeout`` (Timeout but NOT ConnectionError) is also retried.
+
+ Pinning this explicitly: the obvious ``except ConnectionError``
+ catch would silently miss ReadTimeout (it's a Timeout subclass,
+ not a ConnectionError subclass), so the implementation must list
+ ``Timeout`` separately.
+ """
+ bad = _mock_response_body_raises(
+ requests.exceptions.ReadTimeout("body read stalled")
+ )
+ ok = _mock_response(200, content=b"final")
+ with (
+ patch(
+ "local_deep_research.security.safe_requests.safe_get",
+ side_effect=[bad, ok],
+ ) as mock_get,
+ patch("local_deep_research.security.safe_requests.time.sleep"),
+ ):
+ resp = safe_get_with_retries(
+ "https://example.com/x",
+ consume_body=True,
+ backoff_times=(0, 0, 0),
+ )
+ assert resp.content == b"final"
+ assert mock_get.call_count == 2
+
+
+def test_consume_body_gives_up_after_max_retries():
+ """Persistent body-read failures eventually surface to the caller."""
+ bad = _mock_response_body_raises(
+ requests.exceptions.ChunkedEncodingError("broken")
+ )
+ with (
+ patch(
+ "local_deep_research.security.safe_requests.safe_get",
+ return_value=bad,
+ ) as mock_get,
+ patch("local_deep_research.security.safe_requests.time.sleep"),
+ ):
+ with pytest.raises(requests.exceptions.ChunkedEncodingError):
+ safe_get_with_retries(
+ "https://example.com/x",
+ consume_body=True,
+ max_retries=2,
+ backoff_times=(0, 0, 0),
+ )
+ # 1 initial + 2 retries = 3 attempts
+ assert mock_get.call_count == 3
+
+
+def test_consume_body_does_not_retry_value_error_from_body_guard():
+ """``ValueError`` from oversized-body guard must NOT be retried.
+
+ A 1 GB+ response isn't a transient network error — retrying just
+ burns more bandwidth on the same outcome. The guard's ValueError
+ must propagate immediately on the first attempt.
+ """
+ bad = _mock_response_body_raises(
+ ValueError("Response body too large: >1073741825 bytes")
+ )
+ with (
+ patch(
+ "local_deep_research.security.safe_requests.safe_get",
+ return_value=bad,
+ ) as mock_get,
+ patch("local_deep_research.security.safe_requests.time.sleep"),
+ ):
+ with pytest.raises(ValueError):
+ safe_get_with_retries(
+ "https://example.com/x",
+ consume_body=True,
+ backoff_times=(0, 0, 0),
+ )
+ # Single attempt — no retry on ValueError.
+ assert mock_get.call_count == 1
+
+
+def test_consume_body_returns_cached_body_to_caller():
+ """After a successful retry, ``response.content`` is cached.
+
+ The point of consuming inside the loop is so the caller doesn't
+ repeat the read (and risk a second transient). Verify the body
+ is available without a second read.
+ """
+ ok = _mock_response(200, content=b"hello world")
+ with patch(
+ "local_deep_research.security.safe_requests.safe_get",
+ return_value=ok,
+ ):
+ resp = safe_get_with_retries("https://example.com/x", consume_body=True)
+ assert resp.content == b"hello world"