~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): keep network errnos out of the filesystem_error download token (#7787)
Imaduddin Bhaisaheb254d48920ebd
diff --git a/changelog.d/7787.bugfix.md b/changelog.d/7787.bugfix.mdnew file mode 100644index 0000000000..f9ec46bd9f--- /dev/null+++ b/changelog.d/7787.bugfix.md@@ -0,0 +1 @@+Network-layer download failures (timeouts, ENET*/EHOSTUNREACH, SSL, DNS, RemoteDisconnected) no longer surface as `filesystem_error` and now get short network cooldowns instead of 1h.diff --git a/src/local_deep_research/security/client_safe_errors.py b/src/local_deep_research/security/client_safe_errors.pyindex a2a220e945..3f0f1e0d7e 100644--- a/src/local_deep_research/security/client_safe_errors.py+++ b/src/local_deep_research/security/client_safe_errors.py@@ -17,6 +17,7 @@ exception class; ``DownloadAttempt.error_message`` stores scrubbed detail.shapes only, not SQL/paths/URLs."""+import errnoimport os# Client-safe skip-reason mapping for download exception paths.@@ -34,6 +35,10 @@ CLIENT_SAFE_DOWNLOAD_MESSAGES: dict[str, str] = {"BrokenPipeError": "network_reset","ConnectionRefusedError": "network_unavailable","Timeout": "network_timeout",+ # Not reached via client_safe_download_message (``_network_token`` returns+ # first for every TimeoutError); kept so direct consumers of this map, such+ # as the classifier vocabulary test, see the token.+ "TimeoutError": "network_timeout","HTTPError": "http_error","ChunkedEncodingError": "network_unavailable","ContentDecodingError": "network_unavailable",@@ -54,6 +59,98 @@ CLIENT_SAFE_DOWNLOAD_MESSAGES: dict[str, str] = {"PdfStreamError": "pdf_parse_failed",}+# Network-layer failures that are not ``ConnectionError`` subclasses but would+# otherwise be swallowed by the OSError errno branch below (and surface as+# ``filesystem_error:<strerror>`` with the 1h filesystem cooldown) or fall to+# ``download_error:<ClassName>``. Matched subclass-aware via the MRO so+# ``requests.exceptions.SSLError``, ``ssl.SSLEOFError`` and friends all hit.+# ``ConnectionError`` / ``TimeoutError`` themselves are handled separately in+# ``_network_token``.+_NETWORK_CLASS_TOKENS: dict[str, str] = {+ "SSLError": "network_unavailable", # ssl.SSLError, requests SSLError, ...+ "gaierror": "network_unavailable", # DNS: socket.gaierror+ "herror": "network_unavailable", # DNS: socket.herror+ "RemoteDisconnected": "network_reset", # server closed mid-download+ "IncompleteRead": "network_reset",+ "ReadTimeoutError": "network_timeout", # urllib3+ "ConnectTimeoutError": "network_timeout",+ "ReadTimeout": "network_timeout", # requests (what the download path raises)+ "ConnectTimeout": "network_timeout",+}++# Canonical network-layer errnos on plain ``OSError`` (no dedicated subclass).+# Built with getattr so platform-missing names (Windows/WSA*) are skipped.+_NETWORK_UNAVAILABLE_ERRNOS: frozenset[int] = frozenset(+ getattr(errno, name)+ for name in (+ "ENETUNREACH",+ "ENETDOWN",+ "EHOSTUNREACH",+ "EHOSTDOWN",+ "ENETRESET",+ "ENOTCONN",+ "EADDRNOTAVAIL",+ "ECONNREFUSED",+ # Windows (WSA*) spellings; skipped on platforms without them.+ "WSAECONNREFUSED",+ "WSAENETUNREACH",+ "WSAENETDOWN",+ "WSAEHOSTUNREACH",+ "WSAEHOSTDOWN",+ "WSAENETRESET",+ "WSAENOTCONN",+ "WSAEADDRNOTAVAIL",+ )+ if hasattr(errno, name)+)+_NETWORK_RESET_ERRNOS: frozenset[int] = frozenset(+ getattr(errno, name)+ for name in (+ "ECONNRESET",+ "ECONNABORTED",+ "EPIPE", # matches BrokenPipeError -> network_reset+ "WSAECONNRESET",+ "WSAECONNABORTED",+ )+ if hasattr(errno, name)+)+_NETWORK_TIMEOUT_ERRNOS: frozenset[int] = frozenset(+ getattr(errno, name)+ for name in ("ETIMEDOUT", "WSAETIMEDOUT")+ if hasattr(errno, name)+)+++def _network_token(exc: BaseException) -> str | None:+ """Return a fixed network token when *exc* is a network-layer failure.++ Checked before the OSError errno branch so the network errnos listed in+ the ``_NETWORK_*_ERRNOS`` sets (including their Windows ``WSA*`` spellings+ where the platform defines them) never reach ``filesystem_error:`` (1h+ cooldown). Returns ``None`` for everything else.+ """+ for cls in type(exc).__mro__:+ token = _NETWORK_CLASS_TOKENS.get(cls.__name__)+ if token:+ return token+ if isinstance(exc, TimeoutError):+ return "network_timeout"+ if isinstance(exc, ConnectionResetError):+ return "network_reset"+ if isinstance(exc, ConnectionError):+ # ConnectionRefused/Aborted/BrokenPipe etc. (never filesystem)+ return CLIENT_SAFE_DOWNLOAD_MESSAGES.get(+ type(exc).__name__, "network_unavailable"+ )+ if isinstance(exc, OSError) and exc.errno is not None:+ if exc.errno in _NETWORK_TIMEOUT_ERRNOS:+ return "network_timeout"+ if exc.errno in _NETWORK_RESET_ERRNOS:+ return "network_reset"+ if exc.errno in _NETWORK_UNAVAILABLE_ERRNOS:+ return "network_unavailable"+ return None+def client_safe_download_message(exc: BaseException) -> str:"""Return a caller-safe skip_reason for *exc*.@@ -76,21 +173,22 @@ def client_safe_download_message(exc: BaseException) -> str:``OSError(28, "leak: secret file contents")`` deliberately don't match thecanonical message and fall through to the class-name default.- The ``ConnectionError`` family (``ConnectionResetError``,- ``ConnectionAbortedError``, ``BrokenPipeError``, ``ConnectionRefusedError``)- are ``OSError`` subclasses that carry an errno too, so they skip the errno- branch and keep their network token. Other socket-level ``OSError``- subclasses (for example ``TimeoutError(ETIMEDOUT)`` or ``ENETUNREACH``)- are not covered by that guard and still take the ``filesystem_error:``- branch.+ Network-layer failures never reach the errno branch: ``_network_token``+ runs first and maps the ``ConnectionError`` family, ``TimeoutError``+ (including ``ETIMEDOUT``), the ENET*/EHOST* errnos, SSL, DNS and+ ``RemoteDisconnected`` failures to fixed ``network_*`` tokens. Only errnos+ outside the network families that ``_network_token`` recognizes (for+ example ``ENOSPC`` or ``ENOENT``) take the ``filesystem_error:`` branch."""- if (- isinstance(exc, OSError)- and not isinstance(exc, ConnectionError)- and exc.errno is not None- ):- canonical = os.strerror(exc.errno)- if exc.strerror and exc.strerror == canonical:+ network = _network_token(exc)+ if network is not None:+ return network+ if isinstance(exc, OSError) and exc.errno is not None:+ try:+ canonical = os.strerror(exc.errno)+ except (ValueError, OverflowError):+ canonical = None+ if canonical and exc.strerror and exc.strerror == canonical:return f"filesystem_error:{exc.strerror}"return CLIENT_SAFE_DOWNLOAD_MESSAGES.get(type(exc).__name__, f"download_error:{type(exc).__name__}"diff --git a/tests/library/download_management/test_client_safe_tokens_lockstep_7652.py b/tests/library/download_management/test_client_safe_tokens_lockstep_7652.pynew file mode 100644index 0000000000..c82821e6c6--- /dev/null+++ b/tests/library/download_management/test_client_safe_tokens_lockstep_7652.py@@ -0,0 +1,147 @@+"""Issue #7652: network failures must not land in filesystem_error, and the+token vocabulary must stay in lockstep with FailureClassifier's retry policy."""++import errno+import http.client+import os+import socket+import ssl++import pytest+import requests++from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+)+from local_deep_research.security.client_safe_errors import (+ CLIENT_SAFE_DOWNLOAD_MESSAGES,+ client_safe_download_message,+)+++def _os(code):+ return OSError(code, os.strerror(code))+++NETWORK_CASES = [+ (TimeoutError(errno.ETIMEDOUT, "Connection timed out"), "network_timeout"),+ (_os(errno.ENETUNREACH), "network_unavailable"),+ (_os(errno.ENETDOWN), "network_unavailable"),+ (_os(errno.EHOSTUNREACH), "network_unavailable"),+ (_os(errno.ENETRESET), "network_unavailable"),+ (+ ssl.SSLError(errno.ECONNRESET, "Connection reset by peer"),+ "network_unavailable",+ ),+ (ssl.SSLEOFError(8, "EOF"), "network_unavailable"),+ (requests.exceptions.SSLError("x"), "network_unavailable"),+ (socket.gaierror(-2, "Name or service not known"), "network_unavailable"),+ (socket.herror(1, "Unknown host"), "network_unavailable"),+ (http.client.RemoteDisconnected("closed"), "network_reset"),+ (+ ConnectionRefusedError(errno.ECONNREFUSED, "refused"),+ "network_unavailable",+ ),+ (BrokenPipeError(errno.EPIPE, "Broken pipe"), "network_reset"),+ (requests.exceptions.ReadTimeout("x"), "network_timeout"),+ (requests.exceptions.ConnectTimeout("x"), "network_timeout"),+]++[email protected]("exc,token", NETWORK_CASES)+def test_network_errors_get_network_tokens(exc, token):+ assert client_safe_download_message(exc) == token+++def test_real_filesystem_errno_still_filesystem():+ exc = OSError(errno.ENOSPC, os.strerror(errno.ENOSPC))+ assert client_safe_download_message(exc).startswith("filesystem_error:")+++def test_non_canonical_strerror_does_not_leak():+ msg = client_safe_download_message(OSError(28, "leak: secret"))+ assert "secret" not in msg+++ "token", sorted(set(CLIENT_SAFE_DOWNLOAD_MESSAGES.values()))+)+def test_every_display_token_is_classified(token):+ failure = FailureClassifier().classify_failure("str", details=token)+ assert failure.error_type != "unknown_error"++[email protected]("exc,token", NETWORK_CASES)+def test_network_tokens_use_short_cooldown(exc, token):+ from datetime import timedelta++ failure = FailureClassifier().classify_failure(+ "str", details=client_safe_download_message(exc)+ )+ assert failure.retry_after is not None+ assert failure.retry_after <= timedelta(minutes=30)+++def test_plain_epipe_matches_broken_pipe_error():+ plain = OSError(errno.EPIPE, os.strerror(errno.EPIPE))+ assert client_safe_download_message(plain) == client_safe_download_message(+ BrokenPipeError(errno.EPIPE, "Broken pipe")+ )+++ "name,token",+ [+ ("WSAECONNREFUSED", "network_unavailable"),+ ("WSAENETUNREACH", "network_unavailable"),+ ("WSAEHOSTUNREACH", "network_unavailable"),+ ("WSAECONNRESET", "network_reset"),+ ("WSAETIMEDOUT", "network_timeout"),+ ],+)+def test_windows_wsa_errnos_get_network_tokens(name, token):+ code = getattr(errno, name, None)+ if code is None:+ pytest.skip(f"errno.{name} not defined on this platform")+ # A canonically-spelled WSA error must not become filesystem_error:*.+ try:+ strerror = os.strerror(code)+ except (ValueError, OverflowError):+ strerror = "x"+ assert client_safe_download_message(OSError(code, strerror)) == token++[email protected]("bad_errno", [2**31, 2**40])+def test_out_of_range_errno_falls_back_to_class_name(bad_errno):+ # os.strerror raises OverflowError past the C int range; this used to+ # escape the token function.+ assert (+ client_safe_download_message(OSError(bad_errno, "x"))+ == "download_error:OSError"+ )+++def test_strerror_value_error_falls_back_to_class_name(monkeypatch):+ def boom(_code):+ raise ValueError("unknown errno")++ monkeypatch.setattr(os, "strerror", boom)+ assert (+ client_safe_download_message(OSError(errno.ENOSPC, "No space"))+ == "download_error:OSError"+ )+++ "token",+ [+ "filesystem_error:" + os.strerror(errno.ENOSPC),+ "filesystem_error:" + os.strerror(errno.EACCES),+ "download_error:OSError",+ "download_error:ValueError",+ ],+)+def test_filesystem_and_download_error_families_are_classified(token):+ failure = FailureClassifier().classify_failure("str", details=token)+ assert failure.error_type != "unknown_error"+ assert failure.retry_after is not None