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.

feat(research): share one content cache across quick phase, subsections and subagents (#6759)

S190d9097048c
diff --git a/changelog.d/+shared-research-content-cache.feature.md b/changelog.d/+shared-research-content-cache.feature.md
new file mode 100644
index 0000000000..2321f5d40c
--- /dev/null
+++ b/changelog.d/+shared-research-content-cache.feature.md
@@ -0,0 +1,15 @@
+Added a single shared `ResearchContentCache` for the whole research run:
+repeat webpage / RAG-chunk fetches across the quick-report phase,
+detailed-report subsections, lead agent and parallel subagents are now
+served from previously fetched content instead of re-downloaded on the
+spot. Covers the `web_search` tool (engines + full-search funnel),
+`fetch_content` in all modes (raw page text is cached before the
+per-focus summary prompt is built), library / collection reads, and the
+extraction pipeline. Only successful fetches are cached and the full
+pre-truncation text is kept, so callers with different length limits
+share one entry.
+
+Only confirmed complete source text enters the shared cache; abstract, snippet,
+missing-chunk and generic retriever-fragment fallbacks remain eligible for a
+later full-content fetch. Cached and fresh fetch-tool responses use the same
+content-length limit, including text passed to summary prompts.
diff --git a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
index 43df2f00f4..ad606a8fee 100644
--- a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
@@ -41,6 +41,7 @@ class BaseSearchStrategy(ABC):
settings_snapshot=None,
questions_by_iteration=None,
search_original_query: bool = True,
+ content_cache=None,
):
"""Initialize the base strategy with common attributes.
@@ -49,6 +50,10 @@ class BaseSearchStrategy(ABC):
settings_snapshot: Settings snapshot for configuration
questions_by_iteration: Dictionary of questions by iteration
search_original_query: Whether to include the original query in the first iteration
+ content_cache: Single shared ``ResearchContentCache`` for the
+ whole research run (quick phase, subsections, lead +
+ subagents). When None, a fresh cache is created so repeat
+ URLs within this strategy still share content.
"""
# Log strategy initialization
strategy_name = self.__class__.__name__
@@ -70,6 +75,34 @@ class BaseSearchStrategy(ABC):
)
self.settings_snapshot = settings_snapshot or {}
self.search_original_query = search_original_query
+ if content_cache is None:
+ try:
+ from ...utilities.research_content_cache import (
+ ResearchContentCache,
+ )
+
+ content_cache = ResearchContentCache()
+ except Exception: # pragma: no cover - defensive
+ content_cache = None
+ self.content_cache = content_cache
+
+ def get_content_cache(self):
+ """Return the strategy's shared research content cache.
+
+ Falls back to the cache bound to the current research (if any) so
+ strategies constructed without an explicit cache still share with
+ the rest of the run.
+ """
+ if getattr(self, "content_cache", None) is not None:
+ return self.content_cache
+ try:
+ from ...utilities.research_content_cache import get_current_cache
+ except Exception: # pragma: no cover - defensive
+ return None
+ try:
+ return get_current_cache()
+ except Exception: # pragma: no cover - defensive
+ return None
def close(self):
"""Release any persistent resources held by this strategy.
diff --git a/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
index 48f5655e62..4c00b6c34b 100644
--- a/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
+++ b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py
@@ -38,6 +38,7 @@ class EnhancedContextualFollowUpStrategy(BaseSearchStrategy):
all_links_of_system=None,
settings_snapshot=None,
research_context: Optional[Dict] = None,
+ content_cache=None,
**kwargs,
):
"""
@@ -50,8 +51,16 @@ class EnhancedContextualFollowUpStrategy(BaseSearchStrategy):
all_links_of_system: Accumulated links from past searches
settings_snapshot: Settings configuration
research_context: Context from previous research
+ content_cache: Single shared ``ResearchContentCache`` for the
+ whole research run. Falls back to a fresh cache (via
+ ``BaseSearchStrategy``) when None; ``AdvancedSearchSystem``
+ overwrites it with the run-scoped instance.
"""
- super().__init__(all_links_of_system, settings_snapshot)
+ super().__init__(
+ all_links_of_system,
+ settings_snapshot,
+ content_cache=content_cache,
+ )
self.model = model
self.search = search
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index a50cf9471c..402b7a63e7 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -1463,10 +1463,17 @@ def _make_web_search_tool(
collector: SearchResultsCollector,
programmatic_mode: bool = False,
description: str = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,
+ content_cache: Any = None,
availability: SearchEngineAvailability | None = None,
progress_callback=None,
):
- """Create a primary search tool with research-scoped availability."""
+ """Create a ``web_search`` tool that instantiates a fresh engine per call.
+
+ ``content_cache`` is the single shared cache for the whole research
+ run, threaded into each per-call engine so repeat URLs across the
+ quick phase, subsections, lead agent and subagents hit one cache.
+ When None, engines fall back to the registry-bound cache.
+ """
availability = availability or SearchEngineAvailability()
if search_engine_name == "wayback":
description += _WAYBACK_INPUT_HINT
@@ -1491,6 +1498,7 @@ def _make_web_search_tool(
llm=model,
settings_snapshot=settings_snapshot,
programmatic_mode=programmatic_mode,
+ content_cache=content_cache,
progress_callback=fetch_progress,
# Documented agent invariant (CONFIGURATION.md
# ``search.snippets_only``): autonomous agents always
@@ -1533,6 +1541,7 @@ def _make_specialized_search_tool(
settings_snapshot: dict,
collector: SearchResultsCollector,
programmatic_mode: bool = False,
+ content_cache: Any = None,
availability: SearchEngineAvailability | None = None,
progress_callback=None,
):
@@ -1559,6 +1568,7 @@ def _make_specialized_search_tool(
llm=model,
settings_snapshot=settings_snapshot,
programmatic_mode=programmatic_mode,
+ content_cache=content_cache,
progress_callback=fetch_progress,
# Same documented agent invariant as web_search above:
# specialized agent tools stay snippets-only even when
@@ -1591,6 +1601,7 @@ def _load_specialized_engine_tools(
collector: SearchResultsCollector,
programmatic_mode: bool = False,
egress_context=None,
+ content_cache: Any = None,
availability: SearchEngineAvailability | None = None,
progress_callback=None,
) -> list:
@@ -1740,6 +1751,7 @@ def _load_specialized_engine_tools(
settings_snapshot,
collector,
programmatic_mode=programmatic_mode,
+ content_cache=content_cache,
availability=availability,
progress_callback=progress_callback,
)
@@ -1768,6 +1780,7 @@ def _make_research_subtopic_tool(
library_resolver: Any = None,
web_search_description: str = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,
max_fetches_per_topic: int | None = None,
+ content_cache: Any = None,
availability: SearchEngineAvailability | None = None,
wait_for_engines=None,
subagent_timeout_seconds: float | None = None,
@@ -1876,7 +1889,9 @@ def _make_research_subtopic_tool(
# a fresh engine per invocation and ``SearchResultsCollector`` is
# lock-protected, so sharing the tool objects across pool workers
# is safe. ``research_subtopic`` is itself excluded so subagents
- # cannot recurse.
+ # cannot recurse. All tools share the single research-scoped
+ # content cache so subagents serve pages/chunks the lead agent (or
+ # a sibling subagent, or the quick phase) already fetched.
sub_tools: list = []
if search_enabled:
sub_tools.append(
@@ -1887,6 +1902,7 @@ def _make_research_subtopic_tool(
collector,
programmatic_mode=programmatic_mode,
description=web_search_description,
+ content_cache=content_cache,
availability=availability,
progress_callback=progress_callback,
)
@@ -1901,6 +1917,7 @@ def _make_research_subtopic_tool(
library_resolver=library_resolver,
max_fetches=max_fetches_per_topic,
subagent_id="subagent",
+ content_cache=content_cache,
)
if sub_fetch is not None:
sub_tools.append(sub_fetch)
@@ -1920,6 +1937,7 @@ def _make_research_subtopic_tool(
collector,
programmatic_mode=programmatic_mode,
egress_context=egress_context,
+ content_cache=content_cache,
availability=availability,
progress_callback=progress_callback,
)
@@ -2964,7 +2982,9 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
username = getattr(self, "_username", None)
if not username:
return None
- return make_library_resolver(username)
+ return make_library_resolver(
+ username, content_cache=self.get_content_cache()
+ )
def _build_tools(self, overall_query: str = "") -> list:
"""Build the LangChain tool list for the lead agent.
@@ -3095,6 +3115,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
self.collector,
programmatic_mode=self.programmatic_mode,
description=primary_search_description,
+ content_cache=self.get_content_cache(),
availability=self.engine_availability,
progress_callback=self.progress_callback,
)
@@ -3111,6 +3132,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
library_resolver=library_resolver,
max_fetches=self.max_fetches_per_topic,
subagent_id="lead",
+ content_cache=self.get_content_cache(),
)
if fetch is not None:
tools.append(fetch)
@@ -3135,6 +3157,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
self.collector,
programmatic_mode=self.programmatic_mode,
egress_context=policy_ctx,
+ content_cache=self.get_content_cache(),
availability=self.engine_availability,
progress_callback=self.progress_callback,
)
@@ -3164,6 +3187,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
library_resolver=library_resolver,
web_search_description=primary_search_description,
max_fetches_per_topic=self.max_fetches_per_topic,
+ content_cache=self.get_content_cache(),
availability=self.engine_availability,
wait_for_engines=self._wait_for_cooldown,
subagent_timeout_seconds=self.subagent_timeout_seconds,
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
index ca9b6a02f2..f05aff326a 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
@@ -324,6 +324,81 @@ def _denial_reason(exc: Any) -> str:
return getattr(getattr(exc, "decision", None), "reason", "policy_denied")
+def _is_fetch_cache_hit_allowed(
+ url: str, egress_context: Any, _cache: Any | None = None
+) -> bool:
+ """Whether a shared-cache hit for *url* may be served under *egress_context*.
+
+ Defense-in-depth for the shared research cache: ``_enforce_url_policy``
+ (``evaluate_url``, scope-only) already passed at this point, but the
+ uncached path still runs ``ContentFetcher``'s SSRF gate
+ (``policy_aware_validate_url``) which refuses private/loopback hosts
+ unless the run holds a private grant (``PRIVATE_ONLY``). The cache fast
+ path must apply the same SSRF gate before serving — otherwise an
+ ``UNPROTECTED``-scope run (where ``evaluate_url`` allows any host)
+ would serve a cached private entry that the fetch path refuses.
+
+ Library routes never reach here as cache hits: valid references return
+ early via ``_try_resolve_url`` (local DB read, no HTTP), and anything
+ else fails this check closed (``validate_url`` rejects non-http schemes
+ and unresolvable ``library.document`` aliases).
+
+ Fail-closed: when the validator cannot be imported the hit is refused
+ (callers fall through to ``ContentFetcher``, which enforces its own
+ gate). When *_cache* is a ``ResearchContentCache`` successful verdicts
+ are memoized per-run so repeat hits skip DNS and stay servable when
+ DNS drops mid-run after a success; refusals (including import-failure
+ and transient DNS failures) are never pinned, so recovery stays open.
+ """
+
+ def _compute() -> bool:
+ try:
+ from local_deep_research.security.egress.fetch import (
+ policy_aware_validate_url,
+ )
+ except Exception: # pragma: no cover - defensive
+ logger.debug(
+ "fetch cache grant check: validator unavailable, refusing hit"
+ )
+ return False
+ try:
+ return bool(policy_aware_validate_url(url, egress_context))
+ except Exception: # pragma: no cover - defensive
+ return False
+
+ # Per-run memo keyed by the exact SSRF booleans the compute uses:
+ # PRIVATE_ONLY maps to (allow_private=True, block_link_local=True),
+ # mirroring the fetcher wrapper; every other scope/None maps to the
+ # strict defaults (False, False). Only True is pinned — a False only
+ # skips the cache fast path while the fetcher re-validates, so a
+ # transient DNS blip or import failure never pins the URL.
+ try:
+ _memo = getattr(_cache, "validated", None)
+ if callable(_memo):
+ try:
+ from local_deep_research.security.egress.policy import (
+ EgressScope,
+ )
+ except Exception: # pragma: no cover - defensive
+ EgressScope = None # type: ignore[assignment]
+ allow_private = bool(
+ EgressScope is not None
+ and egress_context is not None
+ and getattr(egress_context, "scope", None)
+ == EgressScope.PRIVATE_ONLY
+ )
+ block_link_local = bool(allow_private)
+ try:
+ return bool(
+ _memo(url, allow_private, block_link_local, _compute)
+ )
+ except Exception: # pragma: no cover - defensive
+ return False
+ except Exception: # pragma: no cover - defensive
+ logger.debug("fetch cache grant check: memo lookup failed")
+ return _compute()
+
+
# Shared instruction appended to every per-URL egress denial returned to the
# agent. Tells it WHY the fetch was refused and what to do instead, so it
# adapts (stays in-scope) rather than retrying the same out-of-scope URL.
@@ -479,10 +554,18 @@ def _fetch_raw_content(
mode_label: str,
max_fetches: int | None = None,
subagent_id: str | None = None,
+ content_cache: Any = None,
content_max_length: int | None = None,
) -> tuple[dict | None, str, str | None, int | None]:
"""Pre-resolve non-network URL shapes or fetch via HTTP.
+ ``content_cache`` is the single shared cache for the whole research
+ run (quick phase, subsections, lead + subagents). When None, the
+ cache bound to the current research (if any) is used via
+ ``ContentFetcher``'s own registry fallback. Repeat URLs are therefore
+ served from previously fetched content instead of hitting the network
+ on the spot.
+
Returns:
(result, final_url, error_string, current_count)
If error_string is not None, a pre-resolution error or budget exhaustion
@@ -490,6 +573,14 @@ def _fetch_raw_content(
current_count is the current fetch count if a network fetch was recorded, or None.
"""
from local_deep_research.content_fetcher import ContentFetcher
+ from local_deep_research.utilities.research_content_cache import (
+ resolve_cache,
+ )
+
+ try:
+ _cache = resolve_cache(content_cache)
+ except Exception: # pragma: no cover - defensive
+ _cache = None
effective_max_length = (
content_max_length
@@ -539,14 +630,69 @@ def _fetch_raw_content(
if budget_err is not None:
return None, url, budget_err, current_count
+ # Inspect the cache only for logging. ContentFetcher serves both
+ # hits and misses below, applying the same policy and max_length
+ # to both. A separate early return here would bypass changes to
+ # the caller's content limit (including summary prompt limits).
+ _hit = None
+ if _cache is not None and _is_fetch_cache_hit_allowed(
+ url, egress_context, _cache
+ ):
+ try:
+ _hit = _cache.get(url)
+ except Exception: # pragma: no cover - defensive
+ _hit = None
+
enable_js = _read_js_rendering_setting(settings_snapshot)
with ContentFetcher(
timeout=CONTENT_FETCH_TIMEOUT,
enable_js_rendering=enable_js,
egress_context=egress_context,
+ content_cache=_cache,
) as fetcher:
result = fetcher.fetch(url, max_length=effective_max_length)
+ if (
+ _hit is not None
+ and isinstance(_hit.get("content"), str)
+ and result.get("status") == "success"
+ ):
+ logger.info(
+ f"[FETCH] mode={mode_label} source=cache "
+ f"url={redact_url_for_log(url)} — "
+ "served from shared research cache"
+ )
+
+ # Store successes at this layer only when ContentFetcher did not
+ # already cache the full text (e.g. mocked fetchers in tests).
+ # Never write truncated display output back: ContentFetcher caches
+ # the full pre-truncation text, and a 10_001-char page sliced to
+ # 10_000 + marker is LONGER, so it would win under longest-wins
+ # and lose the tail for later callers with larger limits.
+ # Only successes: errors must retry. Grant-consistent: entries
+ # this caller's grant would not allow to read are not written
+ # either (mirrors the engine store gate).
+ if (
+ _cache is not None
+ and isinstance(result, dict)
+ and result.get("status") == "success"
+ and isinstance(result.get("content"), str)
+ and result.get("content_is_complete") is not False
+ and _is_fetch_cache_hit_allowed(url, egress_context, _cache)
+ ):
+ _text = result.get("content") or ""
+ if "[... content truncated ...]" not in _text:
+ try:
+ if _cache.get(url) is None:
+ _cache.put(
+ url,
+ _text,
+ title=result.get("title"),
+ url_out=result.get("url") or url,
+ )
+ except Exception: # allow: silent-exception
+ pass
+
return result, url, None, current_count
@@ -557,6 +703,7 @@ def _make_full_fetch_tool(
library_resolver: Any = None,
max_fetches: int | None = None,
subagent_id: str | None = None,
+ content_cache: Any = None,
content_max_length: int | None = None,
):
mode_label = "full"
@@ -589,6 +736,7 @@ def _make_full_fetch_tool(
mode_label,
max_fetches=limit,
subagent_id=subagent_id,
+ content_cache=content_cache,
content_max_length=content_max_length,
)
if err_msg is not None:
@@ -651,6 +799,7 @@ def _make_summary_fetch_tool(
library_resolver: Any = None,
max_fetches: int | None = None,
subagent_id: str | None = None,
+ content_cache: Any = None,
content_max_length: int | None = None,
):
"""Build the summary-mode fetch tool.
@@ -695,6 +844,7 @@ def _make_summary_fetch_tool(
mode_label,
max_fetches=limit,
subagent_id=subagent_id,
+ content_cache=content_cache,
content_max_length=content_max_length,
)
if err_msg is not None:
@@ -824,6 +974,7 @@ def build_fetch_tool(
library_resolver: Any = None,
max_fetches: int | None = None,
subagent_id: str | None = None,
+ content_cache: Any = None,
content_max_length: int | None = None,
):
"""Build the agent-facing ``fetch_content`` tool for *mode*.
@@ -848,6 +999,11 @@ def build_fetch_tool(
When ``None``, the tool falls through to the egress gate unchanged
(which, when ``egress_context`` is configured, rejects library / citation
URLs as ``unsupported_scheme``) — same as the pre-fix behaviour.
+
+ ``content_cache`` is the single shared cache for the whole research
+ run. When None, the cache bound to the current research (if any) is
+ used, so the lead agent, subagents, quick phase and subsections all
+ share previously fetched pages instead of re-fetching on the spot.
"""
if mode == "disabled":
return None
@@ -859,6 +1015,7 @@ def build_fetch_tool(
library_resolver=library_resolver,
max_fetches=max_fetches,
subagent_id=subagent_id,
+ content_cache=content_cache,
content_max_length=content_max_length,
)
if mode == "summary_focus":
@@ -873,6 +1030,7 @@ def build_fetch_tool(
library_resolver=library_resolver,
max_fetches=max_fetches,
subagent_id=subagent_id,
+ content_cache=content_cache,
content_max_length=content_max_length,
)
if mode == "summary_focus_query":
@@ -889,6 +1047,7 @@ def build_fetch_tool(
library_resolver=library_resolver,
max_fetches=max_fetches,
subagent_id=subagent_id,
+ content_cache=content_cache,
content_max_length=content_max_length,
)
raise ValueError(
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py b/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
index b92d146063..18e188f4ac 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
@@ -207,7 +207,7 @@ def is_citation_reference(url: str) -> int | None:
def resolve_library_document(
- url: str, username: Optional[str]
+ url: str, username: Optional[str], content_cache: Any = None
) -> Optional[dict[str, Any]]:
"""Look up a local library document by ``/library/document/<uuid>[/pdf]`` URL.
@@ -237,10 +237,46 @@ def resolve_library_document(
(Documents with empty text content return a result payload with
``content=""``, which summary-mode handles as NOT RELEVANT without an
LLM call.)
+
+ When a shared ``content_cache`` is available (the single cache for the
+ whole research run), chunk / document text is served from it on repeat
+ reads — so the quick-report phase, detailed subsections, lead agent
+ and subagents do not re-query the same rows on the spot.
+
+ Only genuine library references consult the cache here. A cached web
+ page (e.g. ``https://example.com/page`` fetched via ``web_search``)
+ must never surface as a "library document": web URLs fall through to
+ the egress gate + budget + HTTP fetcher so accounting stays symmetric
+ (library reads are local and consume no network slot; web fetches do,
+ even on cache hits, preserving historical accounting).
"""
reference = _parse_library_reference(url)
if reference is None:
return None
+ try:
+ from ....utilities.research_content_cache import (
+ resolve_cache as _resolve_cache,
+ )
+
+ _cache = _resolve_cache(content_cache)
+ except Exception: # pragma: no cover - defensive
+ _cache = None
+ if _cache is not None:
+ try:
+ _hit = _cache.get(url)
+ except Exception: # pragma: no cover - defensive
+ _hit = None
+ if _hit is not None and isinstance(_hit.get("content"), str):
+ _text = _hit["content"]
+ _title = _hit.get("title") or ""
+ _curl = _hit.get("url") or url
+ return {
+ "title": _title,
+ "content": _text,
+ "url": _curl,
+ "snippet": (_text[:200].strip() if _text else _title or "")
+ or "",
+ }
lookup_value = reference.value
chunk_index = reference.chunk_index
@@ -319,6 +355,22 @@ def resolve_library_document(
"(id={!r})",
resolved_id,
)
+ # Skip the cache write when the requested chunk was not found
+ # (chunk_index is set but no DocumentChunk row matched).
+ # A later retry in the same run must hit the database rather
+ # than returning the stored "Chunk N not found" failure message.
+ if _cache is not None and not (
+ chunk_index is not None and chunk is None
+ ):
+ try:
+ _cache.put(
+ url,
+ text,
+ title=document.title or f"Document {lookup_value}",
+ url_out=citation_url,
+ )
+ except Exception: # allow: silent-exception
+ pass
return {
"title": document.title or f"Document {lookup_value}",
"content": text,
@@ -346,6 +398,7 @@ def resolve_library_document(
def make_library_resolver(
username: Optional[str],
+ content_cache: Any = None,
) -> Callable[[str], Optional[dict[str, Any]]]:
"""Build a one-arg URL → dict resolver suitable for the fetch tool.
@@ -354,6 +407,9 @@ def make_library_resolver(
using the run's user, the same way the LangGraph strategy threads
``settings_snapshot`` and ``egress_context`` through tool closures.
+ *content_cache* is the single shared cache for the whole research run;
+ when None, the cache bound to the current research (if any) is used.
+
Returns the resolved dict, or ``None`` for URLs that aren't library
document refs — the fetch tool then falls through to the egress gate
unchanged.
@@ -361,8 +417,13 @@ def make_library_resolver(
# Bind the username once so the inner function doesn't re-resolve on
# every call (cheap, but keeps the per-call hot path branch-free).
_username = username
+ _cache = content_cache
def _resolve(url: str) -> Optional[dict[str, Any]]:
+ if _cache is not None:
+ return resolve_library_document(
+ url, _username, content_cache=_cache
+ )
return resolve_library_document(url, _username)
return _resolve
diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.py
index a3dee35816..597414974f 100644
--- a/src/local_deep_research/content_fetcher/fetcher.py
+++ b/src/local_deep_research/content_fetcher/fetcher.py
@@ -54,6 +54,7 @@ class ContentFetcher:
language: str = "English",
enable_js_rendering: bool = False,
egress_context: Any = None,
+ content_cache: Any = None,
):
"""
Initialize the content fetcher.
@@ -79,13 +80,32 @@ class ContentFetcher:
local lab deployments (Ollama at 127.0.0.1, SearXNG on
192.168.x) can actually be reached without forcing the
operator to set SSRF_ALLOW_PRIVATE_IPS=1 globally.
+ content_cache: Optional shared ``ResearchContentCache`` for the
+ whole research run. When None, the cache bound to the
+ current research (if any) is used, so the quick-report
+ phase, detailed subsections, lead agent and subagents
+ share previously fetched pages instead of re-fetching.
"""
self.timeout = timeout
self.language = language
self.enable_js_rendering = enable_js_rendering
self.egress_context = egress_context
+ self.content_cache = content_cache
self._downloaders: Dict[URLType, Any] = {}
+ def _resolve_cache(self) -> Any:
+ """Return the effective shared cache (explicit or research-bound)."""
+ if self.content_cache is not None:
+ return self.content_cache
+ try:
+ from ..utilities.research_content_cache import get_current_cache
+ except Exception: # pragma: no cover - defensive
+ return None
+ try:
+ return get_current_cache()
+ except Exception: # pragma: no cover - defensive
+ return None
+
def _get_downloader(self, url_type: URLType):
"""Get or create the appropriate downloader for a URL type."""
if url_type in self._downloaders:
@@ -267,7 +287,49 @@ class ContentFetcher:
# SSRF validation: reject private/internal IPs before reaching downloaders.
# Policy-aware so PRIVATE_ONLY egress scope can actually reach
# private hosts (lab deployments) without disabling SSRF globally.
- if not policy_aware_validate_url(url, self.egress_context):
+ # Per-run memo in the shared cache removes the per-fetch getaddrinfo
+ # when the fetch-tool gate already validated the same (url, grant):
+ # an uncached fetch otherwise resolves 3x (tool read gate, here,
+ # tool put gate). Only True is pinned — a False (including a
+ # transient DNS failure, which validate_url maps to False rather
+ # than raising) is recomputed so recovery stays open.
+ def _ssrf_ok() -> bool:
+ _cache_for_gate = self._resolve_cache()
+ _memo = getattr(_cache_for_gate, "validated", None)
+ if callable(_memo):
+ try:
+ from ..security.egress.policy import EgressScope
+ except Exception: # pragma: no cover - defensive
+ EgressScope = None # type: ignore[assignment, misc]
+ _allow_private = bool(
+ EgressScope is not None
+ and self.egress_context is not None
+ and getattr(self.egress_context, "scope", None)
+ == EgressScope.PRIVATE_ONLY
+ )
+ # Mirror the exact booleans policy_aware_validate_url
+ # computes with: (True, True) under PRIVATE_ONLY, strict
+ # (False, False) otherwise.
+ _block_link_local = bool(_allow_private)
+ try:
+ return bool(
+ _memo(
+ url,
+ _allow_private,
+ _block_link_local,
+ lambda: policy_aware_validate_url(
+ url, self.egress_context
+ ),
+ )
+ )
+ except Exception: # pragma: no cover - defensive
+ return False
+ try:
+ return bool(policy_aware_validate_url(url, self.egress_context))
+ except Exception: # pragma: no cover - defensive
+ return False
+
+ if not _ssrf_ok():
logger.warning(
"content_fetcher.ssrf_denied url={url}",
url=redact_url_for_log(url),
@@ -313,121 +375,149 @@ class ContentFetcher:
source_type=source_name,
)
- # Get the appropriate downloader
- downloader = self._get_downloader(url_type)
-
- if not downloader and url_type not in _NO_IMPORT_FALLBACK:
- # Fall back to generic HTML downloader. This triggers when a
- # specialized downloader failed to import — playwright_html may
- # still be available.
- # Use _get_downloader so the instance is cached and cleaned up
- # by close().
- downloader = self._get_downloader(URLType.HTML)
- if not downloader:
- return {
- "status": "error",
- "url": url,
- "source_type": source_name,
- "error": "No suitable downloader available",
- }
-
- # Determine content type
+ # Shared cache with request coalescing: repeat URLs (quick phase vs
+ # subagents, lead vs subagents, web_search vs fetch_content) are
+ # served from the single research-scoped cache without a second
+ # download, and concurrent same-URL fetches collapse to one network
+ # call via ``get_or_fetch``. Only successful (full pre-truncation)
+ # text is cached, so transient errors still retry. The cache sits
+ # AFTER the egress gate above — no policy bypass.
+ _cache = self._resolve_cache()
content_type = ContentType.TEXT if prefer_text else ContentType.PDF
- # Download content
- try:
- result = downloader.download_with_result(url, content_type)
-
- # HTML fallback: when a fallback-eligible specialized downloader
- # fails (for example, PubMed is paywalled), try generic extraction.
- # A paper URL classified ARXIV is terminal here because its
- # downloader owns canonical HTML, PDF, and API fallbacks and the
- # input URL is never fetched; non-paper arXiv pages never reach
- # this branch as ARXIV, so they are not denied the fallback.
- if not result.is_success and url_type not in _NO_HTML_FALLBACK:
- logger.debug(
- "content_fetcher.html_fallback_started url={url}",
- url=redact_url_for_log(url),
- )
- html_downloader = self._get_downloader(URLType.HTML)
- if html_downloader:
- result = html_downloader.download_with_result(
- url, content_type
- )
- # Use the HTML downloader for metadata too, so we
- # don't call the failed specialized downloader's
- # get_metadata (which would re-fetch or return wrong data).
- downloader = html_downloader
-
- if result.is_success and result.content:
- # Decode content — check PDF magic bytes first, then try
- # UTF-8, and reject anything that is neither.
- if result.content[:4] == b"%PDF":
- from ..research_library.downloaders.base import (
- BaseDownloader,
- )
-
- content = BaseDownloader.extract_text_from_pdf(
- result.content
- )
- if not content:
- return {
- "status": "error",
- "url": url,
- "source_type": source_name,
- "error": "Could not extract text from PDF",
- }
- else:
- try:
- content = result.content.decode("utf-8")
- except UnicodeDecodeError:
- return {
- "status": "error",
- "url": url,
- "source_type": source_name,
- "error": "Content is not valid UTF-8 and not a PDF",
- }
-
- # Truncate if needed
- if max_length and len(content) > max_length:
- content = (
- content[:max_length] + "\n\n[... content truncated ...]"
+ def _download_once() -> Dict[str, Any] | None:
+ """Download and decode *url* once (no cache access).
+
+ Returns a cache-shaped success dict with the FULL pre-truncation
+ text on success, or an error-shaped dict (no ``content``) on
+ failure so ``get_or_fetch`` passes it through without caching
+ while waiters retry with their own fetch.
+ """
+ downloader = self._get_downloader(url_type)
+ if not downloader and url_type not in _NO_IMPORT_FALLBACK:
+ downloader = self._get_downloader(URLType.HTML)
+ if not downloader:
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": "No suitable downloader available",
+ }
+ try:
+ result = downloader.download_with_result(url, content_type)
+ if not result.is_success and url_type not in _NO_HTML_FALLBACK:
+ logger.debug(
+ "content_fetcher.html_fallback_started url={url}",
+ url=redact_url_for_log(url),
)
-
- # Try to get metadata
- metadata = {}
- if hasattr(downloader, "get_metadata"):
- try:
- metadata = downloader.get_metadata(url)
- except Exception:
- # Best-effort/optional metadata; expected to fail
- # routinely (e.g. no metadata available for this
- # URL type) so keep this at DEBUG, not ERROR, to
- # avoid flooding alerting. Still drop the exception
- # attachment to keep raw/credentialed URLs out of
- # the DB/frontend log sinks.
- logger.opt(exception=False).debug(
- "content_fetcher.metadata_failed url={url}",
- url=redact_url_for_log(url),
+ html_downloader = self._get_downloader(URLType.HTML)
+ if html_downloader:
+ result = html_downloader.download_with_result(
+ url, content_type
+ )
+ downloader = html_downloader
+ if result.is_success and result.content:
+ if result.content[:4] == b"%PDF":
+ from ..research_library.downloaders.base import (
+ BaseDownloader,
)
+ content = BaseDownloader.extract_text_from_pdf(
+ result.content
+ )
+ if not content:
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": "Could not extract text from PDF",
+ }
+ else:
+ try:
+ content = result.content.decode("utf-8")
+ except UnicodeDecodeError:
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": (
+ "Content is not valid UTF-8 and not a PDF"
+ ),
+ }
+ metadata: Dict[str, Any] = {}
+ if hasattr(downloader, "get_metadata"):
+ try:
+ metadata = downloader.get_metadata(url)
+ except Exception:
+ # Best-effort/optional metadata; expected to fail
+ # routinely so keep at DEBUG without exception
+ # attachment to keep raw URLs out of log sinks.
+ logger.opt(exception=False).debug(
+ "content_fetcher.metadata_failed url={url}",
+ url=redact_url_for_log(url),
+ )
+ return {
+ "content": content,
+ "content_is_complete": getattr(
+ result, "content_is_complete", True
+ )
+ is not False,
+ "title": metadata.get("title"),
+ "url": url,
+ "author": metadata.get("author"),
+ "published_date": metadata.get("published_date"),
+ }
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": result.skip_reason or "Download failed",
+ }
+ except Exception as e:
+ logger.opt(exception=False).error(
+ "content_fetcher.download_error url={url}",
+ url=redact_url_for_log(url),
+ )
return {
- "status": "success",
- "content": content,
+ "status": "error",
"url": url,
"source_type": source_name,
- "title": metadata.get("title"),
- "author": metadata.get("author"),
- "published_date": metadata.get("published_date"),
+ "error": str(e),
}
+ if _cache is None:
+ outcome = _download_once()
+ if outcome is None or not isinstance(outcome.get("content"), str):
+ if (
+ isinstance(outcome, dict)
+ and outcome.get("status") == "error"
+ ):
+ return outcome
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": "Download failed",
+ }
+ full_content = outcome["content"] or ""
+ display = full_content
+ if max_length and len(display) > max_length:
+ display = (
+ display[:max_length] + "\n\n[... content truncated ...]"
+ )
return {
- "status": "error",
+ "status": "success",
+ "content": display,
+ "content_is_complete": outcome.get("content_is_complete", True),
"url": url,
"source_type": source_name,
- "error": result.skip_reason or "Download failed",
+ "title": outcome.get("title"),
+ "author": outcome.get("author"),
+ "published_date": outcome.get("published_date"),
}
+ try:
+ cached = _cache.get_or_fetch(url, _download_once)
except Exception as e:
logger.opt(exception=False).error(
"content_fetcher.download_error url={url}",
@@ -439,6 +529,37 @@ class ContentFetcher:
"source_type": source_name,
"error": str(e),
}
+ if cached is None or not isinstance(cached.get("content"), str):
+ if isinstance(cached, dict) and cached.get("status") == "error":
+ return cached
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": "Download failed",
+ }
+ full_cached = cached.get("content") or ""
+ display_cached = full_cached
+ if max_length and len(display_cached) > max_length:
+ display_cached = (
+ display_cached[:max_length] + "\n\n[... content truncated ...]"
+ )
+ result_out: Dict[str, Any] = {
+ "status": "success",
+ "content": display_cached,
+ "content_is_complete": cached.get("content_is_complete", True),
+ "url": url,
+ "source_type": source_name,
+ "title": cached.get("title"),
+ }
+ # get_or_fetch returns the cached entry (content/title/url only);
+ # when this caller was the fetcher, the full download also produced
+ # author metadata — include it when available.
+ if isinstance(cached.get("author"), str):
+ result_out["author"] = cached.get("author")
+ if cached.get("published_date") is not None:
+ result_out["published_date"] = cached.get("published_date")
+ return result_out
def fetch_text(
self, url: str, max_length: Optional[int] = None
diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.py
index b635f85d6f..5773657b9c 100644
--- a/src/local_deep_research/research_library/downloaders/arxiv.py
+++ b/src/local_deep_research/research_library/downloaders/arxiv.py
@@ -215,11 +215,13 @@ class ArxivDownloader(HTMLDownloader):
)
if content_type == ContentType.TEXT:
- text = self.download_text(url)
- if text:
+ result = self.download_text_with_source(url)
+ if result and result.text:
return DownloadResult(
- content=text.encode("utf-8", errors="ignore"),
+ content=result.text.encode("utf-8", errors="ignore"),
is_success=True,
+ content_is_complete=result.source
+ != ArxivTextSource.ARXIV_API,
)
return DownloadResult(
skip_reason=f"Could not retrieve full text for arXiv:{arxiv_id}"
diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.py
index 02b5eb89e0..e9bf43dce1 100644
--- a/src/local_deep_research/research_library/downloaders/base.py
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@ -104,6 +104,9 @@ class DownloadResult(NamedTuple):
skip_reason: Optional[str] = None
is_success: bool = False
status_code: Optional[int] = None
+ # Abstract/metadata fallbacks are useful display text, but cannot
+ # satisfy a later request for the complete source from a shared cache.
+ content_is_complete: bool = True
class _ResponseBodyTooLarge(Exception):
diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.py
index 5cb3616aad..f85309e3ec 100644
--- a/src/local_deep_research/research_library/downloaders/biorxiv.py
+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py
@@ -49,7 +49,9 @@ class BioRxivDownloader(BaseDownloader):
text = self._fetch_abstract_from_page(url)
if text:
return DownloadResult(
- content=text.encode("utf-8"), is_success=True
+ content=text.encode("utf-8"),
+ is_success=True,
+ content_is_complete=False,
)
# Fallback to PDF extraction
diff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
index bed3e44675..3bccfdabf0 100644
--- a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
+++ b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
@@ -521,6 +521,12 @@ def _try_specialized_downloader(
session.block_link_local = block_link_local
session.egress_context = egress_context
result = downloader.download_with_result(url, ContentType.TEXT)
+ if getattr(result, "content_is_complete", True) is False:
+ # This pipeline supplies full-content engines. An abstract
+ # must not be promoted to a complete paper by those callers.
+ return failure._replace(
+ skip_reason="Specialized downloader returned only metadata"
+ )
if result.is_success and result.content:
text = result.content.decode("utf-8", errors="replace")
if len(text.strip()) >= MIN_CONTENT_LENGTH:
@@ -538,6 +544,7 @@ def _try_specialized_downloader(
or "Specialized downloader returned no usable content"
)
except PolicyDeniedError:
+ # Propagate egress policy denials so callers enforce per-URL policy.
raise
except Exception as e:
skip_reason = "Specialized downloader failed"
@@ -561,11 +568,95 @@ def _try_specialized_downloader(
return failure
+def _is_cache_hit_allowed(
+ url: str,
+ allow_private_ips: bool,
+ block_link_local: bool,
+ _cache: object | None = None,
+) -> bool:
+ """Whether a cache hit for *url* may be served under the caller's grant.
+
+ Defense-in-depth for the shared research cache: a granted call
+ (``allow_private_ips=True``) may fetch and cache a loopback/private URL,
+ but a later non-granted call sharing the same cache must not be served
+ that entry — it must go through the downloader's own SSRF gate (which
+ will refuse). Path-only library routes (``/library/...``, ``/lib/...``)
+ are local DB reads, not network fetches, so they are always allowed.
+
+ The absolute ``https://library.document/<id>`` alias is NOT exempted:
+ the pipeline has no library resolver, so that spelling is a network URL
+ here and must pass the same egress check as any web URL (it fails
+ ``validate_url`` — unresolvable host — and correctly bypasses the cache
+ instead of leaking a cached entry to a non-granted caller).
+
+ The library exemption uses the fetch tool's strict grammar
+ (32/64-hex or UUID via ``library_resolver.parse_library_url``), not
+ the wider citation grammar (``is_safe_document_id`` accepts any
+ ``[0-9A-Za-z_-]+`` slug): a slug-shaped route can never resolve via
+ the fetch tool, so exempting it here would let the two surfaces drift.
+
+ Fail-closed: when the SSRF validator cannot be imported the hit is
+ refused (callers fall through to the downloader, which enforces its
+ own gate). When *_cache* is a ``ResearchContentCache`` successful
+ verdicts are memoized per-run so repeat hits do not pay a getaddrinfo
+ per read and stay servable when DNS drops mid-run after a success;
+ refusals are recomputed so a transient DNS blip never pins the URL
+ for the rest of the run.
+ """
+ try:
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ parse_library_url,
+ )
+
+ stripped = url.strip() if isinstance(url, str) else ""
+ if stripped.startswith("/") and parse_library_url(stripped) is not None:
+ return True
+ except Exception: # pragma: no cover - defensive
+ logger.debug("cache grant check: library route parse failed")
+ try:
+ from local_deep_research.security.ssrf_validator import validate_url
+ except Exception: # pragma: no cover - defensive
+ logger.debug("cache grant check: validator unavailable, refusing hit")
+ return False
+ # Per-run memo: same (url, grant) repeats skip DNS on success. A
+ # False verdict only skips the cache fast path and is never pinned —
+ # the downloader re-validates — so a transient DNS failure cannot
+ # block recovery.
+ _memo = getattr(_cache, "validated", None)
+ if callable(_memo):
+ try:
+ return bool(
+ _memo(
+ url,
+ allow_private_ips,
+ block_link_local,
+ lambda: validate_url(
+ url,
+ allow_private_ips=allow_private_ips,
+ block_link_local=block_link_local,
+ ),
+ )
+ )
+ except Exception: # pragma: no cover - defensive
+ return False
+ try:
+ return bool(
+ validate_url(
+ url,
+ allow_private_ips=allow_private_ips,
+ block_link_local=block_link_local,
+ )
+ )
+ except Exception: # pragma: no cover - defensive
+ return False
+
+
def fetch_and_extract(
url: str,
timeout: int = 30,
language: str = "English",
enable_js_rendering: bool = False,
+ content_cache: Any = None,
allow_private_ips: bool = False,
block_link_local: bool = False,
egress_context: Any = None,
@@ -573,8 +664,12 @@ def fetch_and_extract(
"""Fetch a URL and extract clean text content.
Pipeline:
- 1. Specialized downloader (arXiv canonical sources, PubMed API, etc.)
- 2. Static HTTP fetch → Playwright fallback (if JS needed and
+ 1. Shared research content cache (when bound — the quick-report
+ phase, detailed subsections and parallel subagents share one
+ cache for the whole research run, so repeat URLs are served
+ without a second network fetch).
+ 2. Specialized downloader (arXiv canonical sources, PubMed API, etc.)
+ 3. Static HTTP fetch → Playwright fallback (if JS needed and
permitted and ``enable_js_rendering`` is True) → trafilatura →
readability → justext
@@ -590,6 +685,8 @@ def fetch_and_extract(
research-quality improvement from JS rendering, and most regular
benchmark runs are on Docker without Chromium anyway. The
user-facing toggle is ``web.enable_javascript_rendering``.
+ content_cache: Optional shared ``ResearchContentCache``. When None,
+ the cache bound to the current research (if any) is used.
allow_private_ips: Whether the downloader may access private IPs
after SSRF validation. The run policy, when supplied, is also
checked on each redirect and pinned connect address. Cloud
@@ -602,57 +699,107 @@ def fetch_and_extract(
Returns:
Extracted plain text, or None if fetch or extraction failed.
"""
- # Try specialized downloader first (arXiv, PubMed, etc.)
+ # Shared cache with coalescing: repeat URLs (quick phase vs
+ # subagents, lead vs subagents) are served without a second network
+ # fetch, and concurrent same-URL calls collapse to one download via
+ # ``get_or_fetch``. Only successes are cached; failures retry.
try:
- specialized = _try_specialized_downloader(
- url,
+ from local_deep_research.utilities.research_content_cache import (
+ resolve_cache,
+ )
+
+ _cache = resolve_cache(content_cache)
+ except Exception: # pragma: no cover - defensive
+ _cache = None
+
+ def _do_fetch() -> dict[str, Any] | None:
+ # No cache access in here — get_or_fetch owns coalescing.
+ try:
+ specialized = _try_specialized_downloader(
+ url,
+ timeout=timeout,
+ allow_private_ips=allow_private_ips,
+ block_link_local=block_link_local,
+ egress_context=egress_context,
+ )
+ except PolicyDeniedError:
+ # Single-URL fetch: propagate policy denial immediately rather than falling back.
+ raise
+ except Exception as e:
+ logger.opt(exception=False).debug(
+ f"Pipeline: specialized downloader error for "
+ f"{redact_url_for_log(url)} ({type(e).__name__})"
+ )
+ specialized = _SpecializedResult(
+ fallback_allowed=not is_arxiv_paper_url(url)
+ )
+ if specialized.content:
+ return {"content": specialized.content, "url": url}
+ if not specialized.fallback_allowed:
+ logger.warning(
+ "Pipeline: terminal specialized download failed for {}: {}",
+ redact_url_for_log(url),
+ failure_reason_for_log(
+ specialized.skip_reason or "reason unavailable"
+ ),
+ )
+ return None
+ from ..playwright_html import AutoHTMLDownloader
+
+ downloader = AutoHTMLDownloader(
timeout=timeout,
+ language=language,
+ enable_js_rendering=enable_js_rendering,
allow_private_ips=allow_private_ips,
block_link_local=block_link_local,
- egress_context=egress_context,
)
- except PolicyDeniedError:
- raise
- except Exception as e:
- logger.opt(exception=False).debug(
- f"Pipeline: specialized downloader error for "
- f"{redact_url_for_log(url)} ({type(e).__name__})"
- )
- specialized = _SpecializedResult(
- fallback_allowed=not is_arxiv_paper_url(url)
- )
- if specialized.content:
- return specialized.content
- if not specialized.fallback_allowed:
- logger.warning(
- "Pipeline: terminal specialized download failed for {}: {}",
- redact_url_for_log(url),
- failure_reason_for_log(
- specialized.skip_reason or "reason unavailable"
- ),
- )
- return None
-
- # Generic HTML pipeline
- from ..playwright_html import AutoHTMLDownloader
-
- downloader = AutoHTMLDownloader(
- timeout=timeout,
- language=language,
- enable_js_rendering=enable_js_rendering,
- allow_private_ips=allow_private_ips,
- block_link_local=block_link_local,
- )
- try:
downloader.session.egress_context = egress_context
- # download() returns extracted text as UTF-8 bytes (not raw HTML):
- # AutoHTMLDownloader inherits HTMLDownloader.download() which runs
- # _fetch_html() → _extract_content() → the full extraction pipeline.
- result = downloader.download(url)
- if result:
- return result.decode("utf-8", errors="replace")
+ try:
+ # download() returns extracted text as UTF-8 bytes (not raw
+ # HTML): AutoHTMLDownloader inherits HTMLDownloader.download()
+ # which runs _fetch_html() → _extract_content().
+ result = downloader.download(url)
+ if result:
+ return {
+ "content": result.decode("utf-8", errors="replace"),
+ "url": url,
+ }
+ return None
+ except PolicyDeniedError:
+ # Single-URL fetch: propagate policy denial directly to caller.
+ raise
+ except Exception as e:
+ # renders them with any traceback even when diagnose=False.
+ logger.opt(exception=False).error(
+ f"fetch_and_extract failed for {redact_url_for_log(url)} "
+ f"({type(e).__name__})"
+ )
+ return None
+ finally:
+ try:
+ downloader.close()
+ except Exception:
+ logger.debug("Failed to close downloader in fetch_and_extract")
+
+ if _cache is None:
+ outcome = _do_fetch()
+ if outcome is not None and isinstance(outcome.get("content"), str):
+ return outcome["content"] or None
+ return None
+ if not _is_cache_hit_allowed(
+ url, allow_private_ips, block_link_local, _cache
+ ):
+ # Grant-agnostic cache must not serve private content to a
+ # non-granted caller: bypass the cache so the downloader's own
+ # SSRF gate refuses (no hit, no fill).
+ outcome = _do_fetch()
+ if outcome is not None and isinstance(outcome.get("content"), str):
+ return outcome["content"] or None
return None
+ try:
+ cached = _cache.get_or_fetch(url, _do_fetch)
except PolicyDeniedError:
+ # Single-URL fetch: propagate policy denial directly to caller.
raise
except Exception as e:
# Type name only -- exception texts embed the raw URL and loguru
@@ -662,11 +809,9 @@ def fetch_and_extract(
f"({type(e).__name__})"
)
return None
- finally:
- try:
- downloader.close()
- except Exception:
- logger.debug("Failed to close downloader in fetch_and_extract")
+ if cached is not None and isinstance(cached.get("content"), str):
+ return cached["content"] or None
+ return None
def batch_fetch_and_extract(
@@ -674,6 +819,7 @@ def batch_fetch_and_extract(
timeout: int = 30,
language: str = "English",
enable_js_rendering: bool = False,
+ content_cache: Any = None,
allow_private_ips: bool = False,
block_link_local: bool = False,
progress_callback: Optional[Callable[[int, int], None]] = None,
@@ -682,8 +828,10 @@ def batch_fetch_and_extract(
"""Fetch multiple URLs and extract clean text from each.
For each URL:
- 1. Try specialized downloader (arXiv, PubMed, etc.) if URL matches
- 2. Use generic HTML only when the specialized route permits fallback
+ 1. Shared research content cache (single cache for the whole
+ research run — quick phase, subsections and subagents).
+ 2. Try specialized downloader (arXiv, PubMed, etc.) if URL matches
+ 3. Use generic HTML only when the specialized route permits fallback
Uses a single AutoHTMLDownloader (and thus a single Playwright
browser if JS fallback is triggered) for the generic HTML URLs.
@@ -700,6 +848,8 @@ def batch_fetch_and_extract(
research-quality improvement from JS rendering, and most regular
benchmark runs are on Docker without Chromium anyway. The
user-facing toggle is ``web.enable_javascript_rendering``.
+ content_cache: Optional shared ``ResearchContentCache``. When None,
+ the cache bound to the current research (if any) is used.
allow_private_ips: Whether the downloader may access private IPs
after SSRF validation. The run policy, when supplied, is also
checked on each redirect and pinned connect address. Cloud
@@ -723,6 +873,14 @@ def batch_fetch_and_extract(
Returns:
Dict mapping URL → extracted text (or None if failed).
"""
+ try:
+ from local_deep_research.utilities.research_content_cache import (
+ resolve_cache,
+ )
+
+ _cache = resolve_cache(content_cache)
+ except Exception: # pragma: no cover - defensive
+ _cache = None
from ..playwright_html import AutoHTMLDownloader
results: Dict[str, Optional[str]] = {}
@@ -749,82 +907,149 @@ def batch_fetch_and_extract(
_report_progress()
- # Try specialized downloaders first — collect URLs that need HTML fallback
- html_urls: List[str] = []
- for url in urls:
+ # Shared-cache fast path first: repeat URLs (quick phase vs subagents,
+ # lead vs subagents) are served without any network fetch. The fast
+ # path is grant-aware: a private/loopback URL cached by a granted call
+ # must not be served to a non-granted caller sharing the same cache.
+ pending_urls: List[str] = []
+ ungranted_urls: List[str] = []
+ if _cache is not None:
+ for url in urls:
+ if not _is_cache_hit_allowed(
+ url, allow_private_ips, block_link_local, _cache
+ ):
+ ungranted_urls.append(url)
+ continue
+ try:
+ _hit = _cache.get(url)
+ except Exception: # pragma: no cover - defensive
+ _hit = None
+ if _hit is not None and isinstance(_hit.get("content"), str):
+ results[url] = _hit["content"] or None
+ done += 1
+ _report_progress()
+ else:
+ pending_urls.append(url)
+ else:
+ pending_urls = list(urls)
+
+ # Shared holder for the single generic-HTML downloader (one Playwright
+ # browser when JS fallback is enabled). Lazily created on first HTML
+ # fallback so specialized-only batches never pay for it.
+ _holder: Dict[str, Any] = {"downloader": None}
+
+ def _get_shared_downloader() -> Any:
+ if _holder["downloader"] is None:
+ dl = AutoHTMLDownloader(
+ timeout=timeout,
+ language=language,
+ enable_js_rendering=enable_js_rendering,
+ allow_private_ips=allow_private_ips,
+ block_link_local=block_link_local,
+ )
+ dl.session.egress_context = egress_context
+ _holder["downloader"] = dl
+ return _holder["downloader"]
+
+ def _download_one(target: str) -> dict[str, Any] | None:
+ # No cache access — get_or_fetch owns coalescing.
try:
specialized = _try_specialized_downloader(
- url,
+ target,
timeout=timeout,
allow_private_ips=allow_private_ips,
block_link_local=block_link_local,
egress_context=egress_context,
)
- if specialized.content:
- results[url] = specialized.content
- done += 1
- _report_progress()
- continue
- if not specialized.fallback_allowed:
- logger.warning(
- "Pipeline: terminal specialized download failed for {}: {}",
- redact_url_for_log(url),
- failure_reason_for_log(
- specialized.skip_reason or "reason unavailable"
- ),
- )
- results[url] = None
- done += 1
- _report_progress()
- continue
except PolicyDeniedError:
- results[url] = None
- done += 1
- _report_progress()
- continue
+ # Batch fetch: record per-URL denial as None and continue processing remaining URLs.
+ return None
except Exception as e:
logger.opt(exception=False).debug(
f"Pipeline: specialized downloader error for "
- f"{redact_url_for_log(url)} ({type(e).__name__})"
+ f"{redact_url_for_log(target)} ({type(e).__name__})"
)
- if is_arxiv_paper_url(url):
- results[url] = None
- done += 1
- _report_progress()
- continue
- html_urls.append(url)
-
- # Generic HTML pipeline for remaining URLs
- if html_urls:
- downloader = AutoHTMLDownloader(
- timeout=timeout,
- language=language,
- enable_js_rendering=enable_js_rendering,
- allow_private_ips=allow_private_ips,
- block_link_local=block_link_local,
- )
+ if is_arxiv_paper_url(target):
+ return None
+ specialized = _SpecializedResult(fallback_allowed=True)
+ if specialized.content:
+ return {"content": specialized.content, "url": target}
+ if not specialized.fallback_allowed:
+ logger.warning(
+ "Pipeline: terminal specialized download failed for {}: {}",
+ redact_url_for_log(target),
+ failure_reason_for_log(
+ specialized.skip_reason or "reason unavailable"
+ ),
+ )
+ return None
try:
- downloader.session.egress_context = egress_context
- for url in html_urls:
+ data = _get_shared_downloader().download(target)
+ if data:
+ return {
+ "content": data.decode("utf-8", errors="replace"),
+ "url": target,
+ }
+ return None
+ except PolicyDeniedError:
+ # Batch fetch: record per-URL denial as None and continue processing remaining URLs.
+ return None
+ except Exception as e:
+ # Type name only -- exception texts embed the raw URL.
+ logger.opt(exception=False).error(
+ f"batch_fetch_and_extract failed for "
+ f"{redact_url_for_log(target)} ({type(e).__name__})"
+ )
+ return None
+
+ try:
+ # Ungranted destinations bypass the cache entirely so a previous
+ # granted fetch cannot leak private content into this call. The
+ # downloader's own SSRF gate still refuses them (no fill).
+ for url in ungranted_urls:
+ outcome = _download_one(url)
+ if outcome is not None and isinstance(outcome.get("content"), str):
+ results[url] = outcome["content"] or None
+ else:
+ results[url] = None
+ done += 1
+ _report_progress()
+ for url in pending_urls:
+ if _cache is not None:
try:
- data = downloader.download(url)
- if data:
- results[url] = data.decode("utf-8", errors="replace")
- else:
- results[url] = None
- except PolicyDeniedError:
- results[url] = None
+ cached = _cache.get_or_fetch(
+ url, lambda u=url: _download_one(u)
+ )
except Exception as e:
+ # Type name only -- exception texts embed the raw URL.
logger.opt(exception=False).error(
f"batch_fetch_and_extract failed for "
f"{redact_url_for_log(url)} ({type(e).__name__})"
)
results[url] = None
- done += 1
- _report_progress()
- finally:
+ done += 1
+ _report_progress()
+ continue
+ if cached is not None and isinstance(
+ cached.get("content"), str
+ ):
+ results[url] = cached["content"] or None
+ else:
+ results[url] = None
+ else:
+ outcome = _download_one(url)
+ if outcome is not None and isinstance(
+ outcome.get("content"), str
+ ):
+ results[url] = outcome["content"] or None
+ else:
+ results[url] = None
+ done += 1
+ _report_progress()
+ finally:
+ if _holder["downloader"] is not None:
try:
- downloader.close()
+ _holder["downloader"].close()
except Exception:
logger.debug(
"Failed to close downloader in batch_fetch_and_extract"
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index a2a79ec9e9..e53b6856fd 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -181,6 +181,20 @@ class AdvancedSearchSystem:
else:
self.questions_per_iteration = 3 # Default
+ # Single shared content cache for the ENTIRE research run: the
+ # initial quick-report phase, every detailed-report subsection and
+ # all parallel subagents resolve webpage / RAG-chunk fetches through
+ # this one instance instead of re-fetching on the spot.
+ try:
+ from .utilities.research_content_cache import (
+ ResearchContentCache,
+ bind_cache_to_research,
+ )
+
+ self.content_cache = ResearchContentCache()
+ except Exception: # pragma: no cover - defensive
+ self.content_cache = None # type: ignore[assignment]
+
# Log the strategy name that's being used
logger.info(
f"Initializing AdvancedSearchSystem with strategy_name='{strategy_name}'"
@@ -224,6 +238,7 @@ class AdvancedSearchSystem:
settings_snapshot=self.settings_snapshot,
knowledge_accumulation_mode=True,
search_original_query=self.search_original_query,
+ content_cache=getattr(self, "content_cache", None),
max_iterations=self.max_iterations,
questions_per_iteration=self.questions_per_iteration,
)
@@ -236,7 +251,16 @@ class AdvancedSearchSystem:
all_links_of_system=self.all_links_of_system,
settings_snapshot=self.settings_snapshot,
research_context=self.research_context,
+ content_cache=getattr(self, "content_cache", None),
)
+ # The delegate owns the actual fetch path — make sure it shares
+ # the single research-scoped cache even when the factory drops
+ # unknown kwargs for that strategy type.
+ if getattr(self, "content_cache", None) is not None:
+ try:
+ delegate.content_cache = self.content_cache
+ except Exception: # allow: silent-exception
+ pass
else:
# Use factory for all other strategies
logger.info(f"Creating {strategy_name} strategy using factory")
@@ -267,8 +291,29 @@ class AdvancedSearchSystem:
# Forwarded so strategies that create engines per tool call
# (e.g. langgraph-agent) can match the system's mode.
programmatic_mode=self.programmatic_mode,
+ content_cache=getattr(self, "content_cache", None),
)
+ # Share the single research-scoped cache with the strategy (covers
+ # strategies whose constructors do not accept content_cache, and
+ # factory paths that drop unknown kwargs).
+ if getattr(self, "content_cache", None) is not None:
+ try:
+ self.strategy.content_cache = self.content_cache
+ except Exception: # allow: silent-exception
+ pass
+ # Also thread it into the long-lived search engine when present so
+ # non-agent strategies (source-based / focused-iteration) share it
+ # for their direct self.search.run() calls.
+ if (
+ getattr(self, "content_cache", None) is not None
+ and getattr(self, "search", None) is not None
+ ):
+ try:
+ self.search.content_cache = self.content_cache
+ except Exception: # allow: silent-exception
+ pass
+
# Log the actual strategy class
logger.info(f"Created strategy of type: {type(self.strategy).__name__}")
@@ -279,6 +324,22 @@ class AdvancedSearchSystem:
):
self.strategy.set_progress_callback(self.progress_callback)
+ # Publish the binding only after construction succeeds. A failed
+ # strategy has no system for the caller to close.
+ if getattr(self, "content_cache", None) is not None:
+ try:
+ _rid = research_id or (
+ research_context.get("research_id")
+ if isinstance(research_context, dict)
+ else None
+ )
+ if _rid is not None and not isinstance(_rid, str):
+ _rid = str(_rid)
+ if isinstance(_rid, str) and _rid:
+ bind_cache_to_research(_rid, self.content_cache)
+ except Exception: # allow: silent-exception
+ pass
+
def close(self):
"""Close resources held by the search system.
@@ -303,6 +364,29 @@ class AdvancedSearchSystem:
if hasattr(self, "strategy"):
safe_close(self.strategy, "search strategy")
+ # Release the research-scoped content cache binding. The cache
+ # itself is in-memory only; unbinding prevents unbounded growth
+ # of the registry across many programmatic calls.
+ try:
+ from .utilities.research_content_cache import (
+ unbind_cache_from_research,
+ )
+
+ _rid = getattr(self, "research_id", None) or (
+ self.research_context.get("research_id")
+ if isinstance(self.research_context, dict)
+ else None
+ )
+ if _rid is not None and not isinstance(_rid, str):
+ _rid = str(_rid)
+ cache = getattr(self, "content_cache", None)
+ if isinstance(_rid, str) and _rid and cache is not None:
+ unbind_cache_from_research(_rid, cache=cache)
+ except Exception:
+ logger.debug(
+ "content cache unbind failed (non-critical)",
+ exc_info=True,
+ )
def _progress_callback(
self, message: str, progress: int, metadata: dict
@@ -374,6 +458,46 @@ class AdvancedSearchSystem:
# programmatic API construct AdvancedSearchSystem directly and would
# otherwise run the full pipeline with the secondary net inactive.
_armed_egress = self._arm_egress_backstop()
+ # Bind the single research-scoped content cache for the whole run
+ # (quick phase + all detailed subsections + subagents). Deep funnels
+ # (engines created per web_search call, ContentFetcher, pipeline,
+ # library resolver) resolve it via the thread-local search context.
+ try:
+ from .utilities.research_content_cache import (
+ bind_cache_to_research,
+ )
+
+ _rid = self.research_id or (
+ self.research_context.get("research_id")
+ if isinstance(self.research_context, dict)
+ else None
+ )
+ if _rid is not None and not isinstance(_rid, str):
+ _rid = str(_rid)
+ if (
+ isinstance(_rid, str)
+ and _rid
+ and getattr(self, "content_cache", None) is not None
+ ):
+ bind_cache_to_research(_rid, self.content_cache)
+ # Re-share with strategy/engine in case they were constructed
+ # without it (factory drops unknown kwargs on some paths).
+ if getattr(self, "content_cache", None) is not None:
+ try:
+ if getattr(self.strategy, "content_cache", None) is None:
+ self.strategy.content_cache = self.content_cache
+ except Exception: # allow: silent-exception
+ pass
+ try:
+ if (
+ getattr(self, "search", None) is not None
+ and getattr(self.search, "content_cache", None) is None
+ ):
+ self.search.content_cache = self.content_cache
+ except Exception: # allow: silent-exception
+ pass
+ except Exception: # allow: silent-exception
+ pass
try:
# Perform the search
return self._perform_search(
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index 224afabc60..2635321621 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -1772,7 +1772,8 @@ def evaluate_url(
# Quota check: hard fail after MAX_DENIED_FETCHES_PER_RUN. Anchor the
# counter to the run's active context (``_quota_ctx``) so the budget is
# per-RUN, not per-EgressContext. Read under that ctx's lock so
- # concurrent subagents see a consistent count.
+ # concurrent subagents see a consistent count. The check itself never
+ # records, so probes and fetches share the same fail-closed cliff.
qctx = _quota_ctx(ctx)
with qctx._lock:
if qctx._fetch_denial_count["count"] >= MAX_DENIED_FETCHES_PER_RUN:
diff --git a/src/local_deep_research/utilities/research_content_cache.py b/src/local_deep_research/utilities/research_content_cache.py
new file mode 100644
index 0000000000..985b75973f
--- /dev/null
+++ b/src/local_deep_research/utilities/research_content_cache.py
@@ -0,0 +1,558 @@
+"""Single shared content cache for an entire research run.
+
+Every consumer that needs the full text of a webpage, a RAG chunk, a
+library document — whether it is the ``web_search`` tool (via
+``FullSearchResults`` / ``BaseSearchEngine._get_full_content``), the
+``fetch_content`` tool (via ``ContentFetcher`` + the summary-LLM prompt
+construction), or the library / collection RAG engines — resolves through
+this one cache. The initial quick-report phase, the detailed-report
+subsections and all parallel subagents therefore share previously fetched
+content instead of re-fetching the same URLs on the spot.
+
+Lifetime: one instance per research run, owned by ``AdvancedSearchSystem``
+(``system.content_cache``) and threaded explicitly into strategies, tools
+and engines. Deep funnels that cannot receive an explicit reference
+(``batch_fetch_and_extract``, ``ContentFetcher.fetch``,
+``resolve_library_document``) fall back to the research-scoped registry
+below, keyed by the ``research_id`` carried in the thread-local search
+context — so freshly created per-call engines still hit the same cache.
+
+When no cache is bound (no explicit instance and no research context, e.g.
+legacy unit tests) all helpers return ``None`` and callers fall back to
+direct fetching, preserving historical behaviour.
+"""
+
+from __future__ import annotations
+
+import threading
+from typing import Any, Callable
+
+
+def normalize_collection_scope(collection_id: Any) -> str | None:
+ """Normalise a collection identifier to its ``collection_<id>`` form.
+
+ Returns ``None`` for missing/empty values. A value already in
+ ``collection_<id>`` form is returned unchanged so ``"coll-B"`` and
+ ``"collection_coll-B"`` collapse to one cache namespace (matching the
+ ``DocumentChunk.collection_name`` normalisation in
+ ``LibraryRAGSearchEngine._get_full_content``). Human-readable names
+ that do not look like ``collection_*`` still get a distinct namespace
+ (under-merge, never cross-contamination).
+ """
+ if collection_id is None or isinstance(collection_id, bool):
+ return None
+ if not isinstance(collection_id, str):
+ collection_id = str(collection_id)
+ stripped = collection_id.strip()
+ if not stripped:
+ return None
+ if stripped.startswith("collection_"):
+ return stripped
+ return f"collection_{stripped}"
+
+
+def _normalize_chunk_display(display: str) -> str:
+ """Merge the two chunk spellings to one cache identity.
+
+ ``/library/document/<id>/chunks#chunk-N`` (emitted by
+ ``build_chunk_anchor_url``) and ``/library/document/<id>#chunk-N``
+ (accepted by the resolver/tests) denote the same chunk text. Strip a
+ trailing ``/chunks`` view when a chunk fragment is present so both
+ share one entry (under-merge only, no corruption).
+ """
+ if "#chunk-" not in display:
+ return display
+ path, _, fragment = display.partition("#")
+ if path.endswith("/chunks"):
+ path = path[: -len("/chunks")]
+ return f"{path}#{fragment}"
+ return display
+
+
+def content_cache_key(url: Any, collection_id: Any = None) -> str:
+ """Normalise *url* into a stable cache key.
+
+ Web URLs collapse tracking params / default ports via
+ ``content_web_cache_key`` (NOT the bibliography ``canonical_url_key``:
+ the path keeps its trailing slash, userinfo is preserved, and
+ fragments are preserved for client-routed SPAs) while
+ ``https://example.com/p?utm_x=1`` and ``https://example.com/p`` share
+ one entry (accepting potential over-merge on sites that vary content per
+ tracking param). Library routes keep their chunk anchor (``#chunk-<n>``)
+ via ``library_display_url`` because a chunk and its parent document
+ are *different* content and must not collide. Anything unparseable
+ falls back to the stripped raw string.
+
+ Library *chunk* URLs are additionally scoped by *collection_id*:
+ the same ``(document, chunk_index)`` can hold different text in two
+ collections (different chunk settings), so ``collection_A#chunk-3``
+ and ``collection_B#chunk-3`` must not share an entry. Document-level
+ library URLs (``Document.text_content`` is collection-independent)
+ and web URLs ignore *collection_id*.
+ """
+ if not isinstance(url, str):
+ return f"raw:{url!r}"
+ stripped = url.strip()
+ if not stripped:
+ return "raw:"
+ try:
+ from .url_utils import content_web_cache_key, library_display_url
+ except Exception: # pragma: no cover - defensive
+ return f"raw:{stripped}"
+ try:
+ display = library_display_url(stripped)
+ except Exception: # pragma: no cover - defensive
+ display = None
+ if display is not None:
+ if "#chunk-" in display:
+ normalised = _normalize_chunk_display(display)
+ scope = normalize_collection_scope(collection_id)
+ if scope is not None:
+ return f"lib:{normalised}|collection:{scope}"
+ return f"lib:{normalised}|collection:__unscoped__"
+ return f"lib:{display}"
+ try:
+ canon = content_web_cache_key(stripped)
+ except Exception: # pragma: no cover - defensive
+ canon = ""
+ if canon:
+ return f"web:{canon}"
+ return f"raw:{stripped}"
+
+
+class ResearchContentCache:
+ """Thread-safe in-memory store of fetched page / chunk text.
+
+ Entries hold the *fullest* fetched content (before per-caller
+ truncation). Callers slice to their own ``max_length`` on the way out,
+ so a ``fetch_content`` call capped at 10k chars and a ``web_search``
+ full-content call share one entry without data loss: the longer fetch
+ wins on ``put``.
+
+ Memory is bounded: at most ``max_entries`` entries and
+ ``max_bytes`` of content bytes are retained (evict-oldest/FIFO).
+ A single oversized page is still stored (it evicts everything else
+ rather than being dropped) so callers never lose the entry they just
+ fetched.
+ """
+
+ # Defaults keep a full research run (quick phase + subsections +
+ # subagents) in memory while capping multi-user server growth:
+ # 200 x ~100KB typical pages ~= 20MB; worst case 32MB per run.
+ DEFAULT_MAX_ENTRIES = 200
+ DEFAULT_MAX_BYTES = 32 * 1024 * 1024
+ # Cap for the SSRF-verdict memo (per-run, FIFO). Each entry is a
+ # small bool keyed by (url, allow_private, block_link_local); 1000
+ # covers a full run's distinct URLs without unbounded growth.
+ MAX_VALIDATION_MEMO_ENTRIES = 1000
+
+ def __init__(
+ self,
+ max_entries: int = DEFAULT_MAX_ENTRIES,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ ) -> None:
+ self._lock = threading.RLock()
+ # key -> {"content": str, "title": str|None, "url": str}
+ self._entries: dict[str, dict[str, Any]] = {}
+ # key -> threading.Event for in-flight fetches (thundering-herd guard)
+ self._inflight: dict[str, threading.Event] = {}
+ self._max_entries = max(1, int(max_entries))
+ self._max_bytes = max(1, int(max_bytes))
+ self._total_bytes = 0
+ self._hits = 0
+ self._misses = 0
+ self._puts = 0
+ self._evictions = 0
+ # (url, allow_private, block_link_local) -> True. Per-run memo
+ # for the SSRF grant gates so repeat cache hits do not pay a
+ # getaddrinfo per read (and stay servable when DNS drops
+ # mid-run after a successful verdict). Only True verdicts are
+ # pinned: validate_url converts a transient DNS failure
+ # (socket.gaierror) into a False verdict rather than raising,
+ # so pinning False would block every later fetch of that URL
+ # for the rest of the run after one blip — a False verdict only
+ # skips the cache fast path and the fetcher/downloader
+ # re-validates on its own, so recomputing False never blocks
+ # recovery.
+ self._validation_memo: dict[tuple[str, bool, bool], bool] = {}
+
+ # -- basic ops ------------------------------------------------------
+ def get(self, url: str, collection_id: Any = None) -> dict[str, Any] | None:
+ key = content_cache_key(url, collection_id)
+ with self._lock:
+ entry = self._entries.get(key)
+ if entry is not None:
+ self._hits += 1
+ return dict(entry)
+ self._misses += 1
+ return None
+
+ def _evict_if_needed(self) -> None:
+ """Evict oldest entries until within entry/byte caps (caller holds lock)."""
+ while (
+ len(self._entries) > self._max_entries
+ or self._total_bytes > self._max_bytes
+ ) and len(self._entries) > 1:
+ oldest_key = next(iter(self._entries))
+ oldest = self._entries.pop(oldest_key)
+ self._total_bytes -= len(oldest.get("content", "") or "")
+ if self._total_bytes < 0:
+ self._total_bytes = 0
+ self._evictions += 1
+
+ def put(
+ self,
+ url: str,
+ content: str,
+ title: str | None = None,
+ url_out: str | None = None,
+ author: str | None = None,
+ published_date: Any | None = None,
+ collection_id: Any = None,
+ ) -> None:
+ """Store *content* for *url*, keeping the longest version on conflict.
+
+ Only full pre-truncation text must be stored here — callers slice
+ to their own ``max_length`` (plus any truncation marker) on the way
+ out. Storing truncated display output would let a
+ ``10_000 + marker`` slice overwrite the complete ``10_001``-char
+ page under longest-wins and lose the tail for later callers with
+ larger limits.
+
+ Library chunk URLs are namespaced by *collection_id* (see
+ :func:`content_cache_key`): the same chunk index can hold
+ different text per collection.
+ """
+ if not isinstance(content, str):
+ return
+ key = content_cache_key(url, collection_id)
+ with self._lock:
+ existing = self._entries.get(key)
+ if existing is not None and len(existing.get("content", "")) >= len(
+ content
+ ):
+ return
+ if existing is not None:
+ self._total_bytes -= len(existing.get("content", "") or "")
+ # Re-insert as newest so FIFO eviction drops truly old URLs.
+ self._entries.pop(key, None)
+ entry: dict[str, Any] = {
+ "content": content,
+ "title": title,
+ "url": url_out if url_out is not None else url,
+ }
+ if author is not None:
+ entry["author"] = author
+ if published_date is not None:
+ entry["published_date"] = published_date
+ self._entries[key] = entry
+ self._total_bytes += len(content)
+ self._puts += 1
+ self._evict_if_needed()
+
+ def get_or_fetch(
+ self,
+ url: str,
+ fetch_fn: Callable[[], dict[str, Any] | None],
+ *,
+ wait_timeout: float = 120.0,
+ collection_id: Any = None,
+ ) -> dict[str, Any] | None:
+ """Return the cached entry for *url* or fetch it exactly once.
+
+ Concurrent callers for the same URL coalesce: the first becomes the
+ fetcher, the rest wait on an event and then read the cache. If the
+ fetcher fails (exception or ``None``) waiters fall through and try
+ their own fetch instead of caching the failure. A waiter whose owner
+ does not finish within ``wait_timeout`` raises ``TimeoutError`` without
+ cancelling the owner; later callers can still reuse its result.
+ Results marked ``content_is_complete=False`` are returned without
+ caching, so a metadata fallback cannot prevent a later full fetch.
+
+ The result is :meth:`put` *before* waiters are woken — waking first
+ would let a waiter re-enter as a second fetcher and double-fetch.
+
+ Library chunk URLs are namespaced by *collection_id* (see
+ :func:`content_cache_key`).
+ """
+ key = content_cache_key(url, collection_id)
+ while True:
+ with self._lock:
+ entry = self._entries.get(key)
+ if entry is not None:
+ self._hits += 1
+ return dict(entry)
+ self._misses += 1
+ event = self._inflight.get(key)
+ if event is None:
+ event = threading.Event()
+ self._inflight[key] = event
+ break
+ if not event.wait(timeout=wait_timeout):
+ # Keep the original owner's claim: a timed-out waiter must
+ # neither recurse forever nor release another thread's fetch.
+ raise TimeoutError("Timed out waiting for shared content")
+ # The owner completed without caching a result. Retry election
+ # iteratively so repeated failures never grow the call stack.
+ try:
+ result = fetch_fn()
+ if result is None:
+ return None
+ content = (
+ result.get("content") if isinstance(result, dict) else None
+ )
+ if (
+ isinstance(content, str)
+ and result.get("content_is_complete") is not False
+ ):
+ # Cache BEFORE waking waiters so they observe the fresh
+ # entry. The finally below wakes waiters; put failures
+ # still wake via finally so waiters retry instead of
+ # hanging on a dead event.
+ self.put(
+ url,
+ content,
+ title=result.get("title")
+ if isinstance(result, dict)
+ else None,
+ url_out=result.get("url")
+ if isinstance(result, dict)
+ else None,
+ author=result.get("author")
+ if isinstance(result, dict)
+ else None,
+ published_date=result.get("published_date")
+ if isinstance(result, dict)
+ else None,
+ collection_id=collection_id,
+ )
+ with self._lock:
+ cached = self._entries.get(key)
+ if cached is not None:
+ return dict(cached)
+ return result
+ finally:
+ # Always release the in-flight slot and wake waiters — even
+ # for BaseException (cancellation/KeyboardInterrupt) and put
+ # failures — or a later caller would block until wait_timeout
+ # on a dead event. Store-before-wake holds because put runs
+ # inside try before this finally signals the event.
+ with self._lock:
+ self._inflight.pop(key, None)
+ event.set()
+
+ # -- SSRF-verdict memo (per-run, defense-in-depth) ------------------
+ @staticmethod
+ def _validation_memo_key(
+ url: Any, allow_private_ips: bool, block_link_local: bool
+ ) -> tuple[str, bool, bool] | None:
+ if not isinstance(url, str):
+ return None
+ stripped = url.strip()
+ if not stripped:
+ return None
+ return (stripped, bool(allow_private_ips), bool(block_link_local))
+
+ def get_validation(
+ self, url: str, allow_private_ips: bool, block_link_local: bool
+ ) -> bool | None:
+ """Return the memoized SSRF verdict, or None when not memoized."""
+ key = self._validation_memo_key(
+ url, allow_private_ips, block_link_local
+ )
+ if key is None:
+ return None
+ with self._lock:
+ return self._validation_memo.get(key)
+
+ def set_validation(
+ self,
+ url: str,
+ allow_private_ips: bool,
+ block_link_local: bool,
+ allowed: bool,
+ ) -> None:
+ """Memoize a successful SSRF verdict (FIFO-bounded, per-run).
+
+ Only True is stored — see :meth:`validated` for why False is
+ never pinned.
+ """
+ if not allowed:
+ return
+ key = self._validation_memo_key(
+ url, allow_private_ips, block_link_local
+ )
+ if key is None:
+ return
+ with self._lock:
+ if key not in self._validation_memo:
+ while (
+ len(self._validation_memo)
+ >= self.MAX_VALIDATION_MEMO_ENTRIES
+ ):
+ try:
+ self._validation_memo.pop(
+ next(iter(self._validation_memo))
+ )
+ except StopIteration:
+ break
+ self._validation_memo[key] = True
+
+ def validated(
+ self,
+ url: str,
+ allow_private_ips: bool,
+ block_link_local: bool,
+ compute: Callable[[], bool],
+ ) -> bool:
+ """Return memoized success or compute, pinning only True.
+
+ Thread-safe: concurrent callers for the same key may compute in
+ parallel (DNS outside the lock); the first True wins and stays
+ for the run like ``policy._dns_cache``. False is never stored:
+ ``validate_url`` maps a transient DNS failure (socket.gaierror)
+ to False instead of raising, so pinning it would refuse every
+ later fetch of that URL until the run ends even after DNS heals.
+ Recomputing False costs one resolution per refused hit (bounded,
+ perf-only) and keeps the fetcher/downloader recovery path open.
+ """
+ key = self._validation_memo_key(
+ url, allow_private_ips, block_link_local
+ )
+ if key is None:
+ try:
+ return bool(compute())
+ except Exception:
+ return False
+ with self._lock:
+ if key in self._validation_memo:
+ return True
+ try:
+ verdict = bool(compute())
+ except Exception:
+ return False
+ if not verdict:
+ return False
+ with self._lock:
+ if key not in self._validation_memo:
+ while (
+ len(self._validation_memo)
+ >= self.MAX_VALIDATION_MEMO_ENTRIES
+ ):
+ try:
+ self._validation_memo.pop(
+ next(iter(self._validation_memo))
+ )
+ except StopIteration:
+ break
+ self._validation_memo[key] = True
+ return True
+
+ def clear(self) -> None:
+ with self._lock:
+ self._entries.clear()
+ self._inflight.clear()
+ self._validation_memo.clear()
+ self._total_bytes = 0
+ self._hits = 0
+ self._misses = 0
+ self._puts = 0
+ self._evictions = 0
+
+ def stats(self) -> dict[str, int]:
+ with self._lock:
+ return {
+ "hits": self._hits,
+ "misses": self._misses,
+ "puts": self._puts,
+ "entries": len(self._entries),
+ "evictions": self._evictions,
+ "total_bytes": self._total_bytes,
+ "validation_memo": len(self._validation_memo),
+ }
+
+ def __len__(self) -> int:
+ with self._lock:
+ return len(self._entries)
+
+
+# -- research-scoped registry -------------------------------------------
+# Maps research_id -> ResearchContentCache. Owned by AdvancedSearchSystem
+# (one cache per research run); deep funnels resolve it via the
+# thread-local search context so per-call engines share it without
+# signature changes across dozens of files.
+
+_registry_lock = threading.RLock()
+_registry: dict[str, ResearchContentCache] = {}
+
+
+def bind_cache_to_research(
+ research_id: str | None, cache: ResearchContentCache | None
+) -> None:
+ """Bind *cache* to *research_id* (no-op for empty ids / None cache)."""
+ if not research_id or cache is None:
+ return
+ with _registry_lock:
+ _registry[research_id] = cache
+
+
+def unbind_cache_from_research(
+ research_id: str | None, *, cache: ResearchContentCache | None = None
+) -> None:
+ """Unbind a run, optionally only when *cache* still owns its binding."""
+ if not research_id:
+ return
+ with _registry_lock:
+ if cache is None or _registry.get(research_id) is cache:
+ _registry.pop(research_id, None)
+
+
+def get_cache_for_research(
+ research_id: str | None,
+) -> ResearchContentCache | None:
+ if not research_id:
+ return None
+ with _registry_lock:
+ return _registry.get(research_id)
+
+
+def get_current_cache() -> ResearchContentCache | None:
+ """Resolve the active research's cache via the thread-local context."""
+ try:
+ from .thread_context import get_search_context
+ except Exception: # pragma: no cover - defensive
+ return None
+ try:
+ ctx = get_search_context()
+ except Exception: # pragma: no cover - defensive
+ return None
+ if not isinstance(ctx, dict):
+ return None
+ research_id = ctx.get("research_id")
+ if not research_id or not isinstance(research_id, str):
+ # Non-string ids (int legacy) are still valid scopes.
+ if research_id is None or isinstance(research_id, bool):
+ return None
+ research_id = str(research_id)
+ return get_cache_for_research(research_id)
+
+
+def resolve_cache(
+ explicit: ResearchContentCache | None,
+) -> ResearchContentCache | None:
+ """Prefer *explicit*, else the registry-bound cache for this thread."""
+ if explicit is not None:
+ return explicit
+ return get_current_cache()
+
+
+__all__ = [
+ "ResearchContentCache",
+ "bind_cache_to_research",
+ "content_cache_key",
+ "get_cache_for_research",
+ "get_current_cache",
+ "normalize_collection_scope",
+ "resolve_cache",
+ "unbind_cache_from_research",
+]
diff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.py
index cbc8d129c7..53020c509f 100644
--- a/src/local_deep_research/utilities/url_utils.py
+++ b/src/local_deep_research/utilities/url_utils.py
@@ -22,6 +22,7 @@ __all__ = [
"normalize_url",
"is_private_ip",
"canonical_url_key",
+ "content_web_cache_key",
"library_display_url",
"is_safe_custom_llm_endpoint",
]
@@ -557,6 +558,114 @@ def canonical_url_key(url: str) -> str:
return urlunsplit((scheme, netloc, path, query_str, ""))
+@lru_cache(maxsize=1024)
+def content_web_cache_key(url: str) -> str:
+ """Return a cache key for *web* content fetches (NOT bibliography dedup).
+
+ Same normalisations as :func:`canonical_url_key` — lowercased
+ scheme/host, stripped default ports, dropped tracking query params —
+ but with deliberate differences, because bibliographic equivalence
+ does not establish identical fetched bytes:
+
+ * the path is preserved verbatim, including a non-root trailing
+ ``/``: ``/article`` and ``/article/`` are different HTTP resources
+ and routinely serve different bodies;
+ * URL userinfo (``user:pass@``) is preserved verbatim (host still
+ lowercased): ``https://alice@host/p`` and ``https://bob@host/p``
+ authenticate differently and must never share an entry;
+ * the fragment is preserved verbatim: client-routed SPAs (hash
+ routing) render different views per fragment under JS rendering
+ (Playwright navigates with the fragment intact).
+
+ Query handling otherwise matches the bibliography key: only tracking
+ params (``utm_*``, ``fbclid``, ...) collapse; every other param,
+ its order and its values are preserved, so ``?a=1`` and ``?a=2``
+ stay distinct. Dropping tracking parameters accepts the trade-off of
+ potential over-merge on rare sites that vary content per tracking param
+ (e.g., campaign- or affiliate-specific landing pages). Raw spellings
+ (``?q=a+b`` vs ``?q=a%20b``) stay
+ distinct, matching :func:`canonical_url_key` (#6758 B2). Anything
+ without a scheme+netloc falls back to the stripped raw string (same as
+ :func:`canonical_url_key`).
+ Library routes are NOT handled here — callers resolve those via
+ ``library_display_url`` first. A relative ``/library/...`` URL
+ therefore falls through to the raw fallback, never to a web key.
+ """
+
+ if not url:
+ return ""
+ try:
+ parsed = urlsplit(url)
+ except Exception:
+ return url.strip()
+ if not parsed.scheme or not parsed.netloc:
+ return url.strip()
+
+ scheme = parsed.scheme.lower()
+
+ # Preserve userinfo verbatim (credentials are case-sensitive and
+ # select a different origin view); lowercase only the host part.
+ raw_netloc = parsed.netloc
+ if "@" in raw_netloc:
+ userinfo, _, hostport = raw_netloc.rpartition("@")
+ else:
+ userinfo, hostport = "", raw_netloc
+
+ # Split host/port carefully so IPv6 literals survive.
+ if hostport.startswith("["):
+ end = hostport.find("]")
+ if end == -1:
+ return url.strip()
+ host = hostport[: end + 1].lower()
+ rest = hostport[end + 1 :]
+ port = rest[1:] if rest.startswith(":") else ""
+ if rest and not rest.startswith(":"):
+ return url.strip()
+ elif ":" in hostport:
+ host, _, port = hostport.rpartition(":")
+ host = host.lower()
+ else:
+ host, port = hostport.lower(), ""
+
+ if (scheme == "https" and port == "443") or (
+ scheme == "http" and port == "80"
+ ):
+ port = ""
+ hostport_norm = f"{host}:{port}" if port else host
+ netloc = f"{userinfo}@{hostport_norm}" if userinfo else hostport_norm
+
+ # Filter query params case-insensitively on key; preserve raw
+ # spellings and order (same raw-preserving filter as
+ # :func:`canonical_url_key` — no parse_qsl/urlencode round-trip).
+ if parsed.query:
+ kept_raw: list[str] = []
+ for raw_pair in parsed.query.split("&"):
+ if raw_pair == "":
+ continue
+ raw_key = raw_pair.split("=", 1)[0]
+ try:
+ decoded_key = unquote(raw_key).lower()
+ except Exception:
+ decoded_key = raw_key.lower()
+ if decoded_key in _TRACKING_PARAMS or any(
+ decoded_key.startswith(p) for p in _TRACKING_PREFIXES
+ ):
+ continue
+ kept_raw.append(raw_pair)
+ query_str = "&".join(kept_raw)
+ else:
+ query_str = ""
+
+ # Path preserved verbatim: case AND trailing slash both select
+ # distinct HTTP resources. Fragment preserved: client-routed SPAs
+ # (hash routing) render different content per fragment under JS
+ # rendering (playwright_html navigates with fragment intact).
+ path = parsed.path
+ fragment = parsed.fragment
+
+ return urlunsplit((scheme, netloc, path, query_str, fragment))
+
+
def is_safe_custom_llm_endpoint(custom_endpoint: Optional[str]) -> bool:
"""SSRF guard for a user-supplied custom LLM endpoint, applied at the
request boundary as fail-fast defense-in-depth.
diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index aa68667cf3..1ed30cb5f3 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -134,6 +134,7 @@ class FullSearchResults:
settings_snapshot: Optional[Dict] = None,
egress_context: Optional[Any] = None,
allow_private_ips: bool = False,
+ content_cache: Optional[Any] = None,
progress_callback: Optional[Callable[[int, int], None]] = None,
):
self.llm = llm
@@ -169,11 +170,24 @@ class FullSearchResults:
# Set by the factory when the parent engine is gated against a
# specific scope; used to evaluate per-URL fetches below.
self.egress_context = egress_context
+ self.content_cache = content_cache
# One operator-visible line per wrapper when the grant is set but
# the run scope keeps it from applying
# (``_effective_allow_private_ips``).
self._grant_withheld_logged = False
+ def _resolve_cache(self) -> Optional[Any]:
+ if self.content_cache is not None:
+ return self.content_cache
+ try:
+ from ...utilities.research_content_cache import get_current_cache
+ except Exception: # pragma: no cover - defensive
+ return None
+ try:
+ return get_current_cache()
+ except Exception: # pragma: no cover - defensive
+ return None
+
def set_fetch_progress_callback(self, hook) -> None:
"""Late-bind the ``(done, total)`` bulk-fetch hook.
@@ -495,6 +509,7 @@ class FullSearchResults:
enable_js_rendering=_read_js_rendering_setting(
self.settings_snapshot
),
+ content_cache=self._resolve_cache(),
allow_private_ips=allow_private,
block_link_local=True,
egress_context=egress_ctx,
@@ -505,6 +520,7 @@ class FullSearchResults:
for result in filtered_results:
link = result.get("link")
result["full_content"] = url_to_content.get(link) if link else None
+ result["full_content_is_complete"] = bool(result["full_content"])
logger.info(f"Full search: retrieved content from {nr_full_text} pages")
return filtered_results
@@ -563,6 +579,7 @@ class FullSearchResults:
enable_js_rendering=_read_js_rendering_setting(
self.settings_snapshot
),
+ content_cache=self._resolve_cache(),
allow_private_ips=allow_private,
block_link_local=True,
egress_context=egress_ctx,
@@ -582,6 +599,7 @@ class FullSearchResults:
for item in relevant_items:
link = item.get("link")
item["full_content"] = url_to_content.get(link) if link else None
+ item["full_content_is_complete"] = bool(item["full_content"])
return relevant_items
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index 76092f7ce2..d8235918ba 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -472,6 +472,7 @@ class ArXivSearchEngine(BaseSearchEngine):
# Default to using summary as content
result["content"] = paper.summary
result["full_content"] = paper.summary
+ result["full_content_is_complete"] = False
# Fetch full text through the shared HTML-first arXiv
# downloader (official HTML rendition with a PDF
@@ -526,6 +527,7 @@ class ArXivSearchEngine(BaseSearchEngine):
if full_text and full_text.strip():
result["content"] = full_text
result["full_content"] = full_text
+ result["full_content_is_complete"] = True
logger.info(
"Retrieved full text via the HTML-first arXiv downloader"
)
@@ -548,6 +550,7 @@ class ArXivSearchEngine(BaseSearchEngine):
)
result["content"] = paper.summary
result["full_content"] = paper.summary
+ result["full_content_is_complete"] = False
results.append(result)
@@ -600,7 +603,7 @@ class ArXivSearchEngine(BaseSearchEngine):
paper = papers[0]
# Format result based on config
- result = {
+ result: Dict[str, Any] = {
"title": paper.title,
"link": paper.entry_id,
"snippet": (
@@ -641,6 +644,7 @@ class ArXivSearchEngine(BaseSearchEngine):
"doi": paper.doi,
"content": paper.summary, # Use summary as content
"full_content": paper.summary, # For consistency
+ "full_content_is_complete": False,
}
)
@@ -656,6 +660,7 @@ class ArXivSearchEngine(BaseSearchEngine):
if full_text and full_text.strip():
result["content"] = full_text
result["full_content"] = full_text
+ result["full_content_is_complete"] = True
logger.info(
"Retrieved full text via the HTML-first arXiv downloader"
)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
index d63db1460e..5951b34cff 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
@@ -502,6 +502,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
"content", result.get("snippet", "")
)
result["full_content"] = source.get("content", "")
+ result["full_content_is_complete"] = bool(source.get("content"))
# Add metadata from source
for key, value in source.items():
@@ -554,7 +555,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
# Process and return the results
previews = self._process_es_response(response)
- return self._get_full_content(previews)
+ return self._get_full_content_cached(previews)
except Exception as e:
safe_msg = self._scrub_error(e)
@@ -580,7 +581,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
# Process and return the results
previews = self._process_es_response(response)
- return self._get_full_content(previews)
+ return self._get_full_content_cached(previews)
except Exception as e:
safe_msg = self._scrub_error(e)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
index d38dd039b7..d18d2f9418 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@ -634,6 +634,7 @@ class GitHubSearchEngine(BaseSearchEngine):
# Get README content
readme_content = self._get_readme_content(repo_full_name)
result["full_content"] = readme_content
+ result["full_content_is_complete"] = bool(readme_content)
result["content_type"] = "readme"
# Get recent issues if requested
@@ -647,12 +648,14 @@ class GitHubSearchEngine(BaseSearchEngine):
# Get file content
file_content = self._get_file_content(file_url)
result["full_content"] = file_content
+ result["full_content_is_complete"] = bool(file_content)
result["content_type"] = "file"
elif search_type == "issue":
# For issues, the snippet usually contains a summary already
# We'll just keep it as is
result["full_content"] = item.get("snippet", "")
+ result["full_content_is_complete"] = False
result["content_type"] = "issue"
elif search_type == "user":
@@ -677,6 +680,7 @@ class GitHubSearchEngine(BaseSearchEngine):
profile_summary += f"\nBio: {item.get('snippet')}\n"
result["full_content"] = profile_summary
+ result["full_content_is_complete"] = False
result["content_type"] = "user_profile"
results.append(result)
@@ -723,6 +727,7 @@ class GitHubSearchEngine(BaseSearchEngine):
if self.include_readme:
readme_content = self._get_readme_content(repo_full_name)
result["full_content"] = readme_content
+ result["full_content_is_complete"] = bool(readme_content)
result["content_type"] = "readme"
# Add recent issues if requested
@@ -781,7 +786,7 @@ class GitHubSearchEngine(BaseSearchEngine):
# Format results
previews = [self._format_code_preview(result) for result in results]
- return self._get_full_content(previews)
+ return self._get_full_content_cached(previews)
finally:
# Restore original search type
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
index 41255b1d89..ffb14bca6b 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
@@ -428,6 +428,9 @@ ONE WORD ONLY:"""
if not self.search_snippets_only:
result["content"] = fields.get("body", "")
result["full_content"] = fields.get("body", "")
+ result["full_content_is_complete"] = bool(
+ fields.get("body")
+ )
# Extract tags/keywords
tags = article.get("tags", [])
@@ -618,7 +621,7 @@ ONE WORD ONLY:"""
results = (
filtered_items
if self.search_snippets_only
- else self._get_full_content(filtered_items)
+ else self._get_full_content_cached(filtered_items)
)
# Add source information to make it clear these are from The Guardian
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
index a7d560addb..ef97eab781 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
@@ -622,6 +622,7 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
# BaseCitationHandler reads "full_content" and falls
# back to the truncated "snippet".
item["full_content"] = text
+ item["full_content_is_complete"] = chunk is not None
item["snippet"] = (
text[:SNIPPET_LENGTH_LONG] + "..."
if len(text) > SNIPPET_LENGTH_LONG
@@ -641,6 +642,7 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
# Replace snippet with full content
item["content"] = document.text_content
item["full_content"] = document.text_content
+ item["full_content_is_complete"] = True
item["snippet"] = (
document.text_content[:SNIPPET_LENGTH_LONG]
+ "..."
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
index 4480c5d583..7a95fbb971 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
@@ -687,12 +687,14 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""
)
item["full_content"] = full_content or item["snippet"]
+ item["full_content_is_complete"] = bool(full_content)
logger.info(
f"Document {idx + 1} full content length: {len(item['full_content'])}"
)
else:
# Fallback to snippet if no raw data
item["full_content"] = item["snippet"]
+ item["full_content_is_complete"] = False
logger.info(
f"Document {idx + 1} using snippet as full content (no raw data)"
)
@@ -712,6 +714,7 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""
f"Error getting full content for document: {safe_msg}"
)
item["full_content"] = item["snippet"]
+ item["full_content_is_complete"] = False
item.pop("_raw_data", None)
results.append(item)
@@ -753,8 +756,9 @@ IMPORTANT: Output ONLY the search query. No explanations, no additional text."""
else:
filtered_previews = previews
- # Get full content for relevant items
- results = self._get_full_content(filtered_previews)
+ # Get full content for relevant items (cache-aware so repeat
+ # URLs across quick phase / subsections / subagents share).
+ results = self._get_full_content_cached(filtered_previews)
logger.info(
f"Search completed successfully, returning {len(results)} results"
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
index f6661c8387..c22c7e17eb 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
@@ -1692,6 +1692,7 @@ The default assumption should be that medical and scientific queries want RECENT
# Use abstract as content if no full text
if pmid not in pmid_to_pmcid:
result["full_content"] = enriched_content
+ result["full_content_is_complete"] = False
result["content"] = enriched_content
result["content_type"] = "abstract"
@@ -1713,6 +1714,7 @@ The default assumption should be that medical and scientific queries want RECENT
result, full_text
)
result["full_content"] = enriched_full_text
+ result["full_content_is_complete"] = True
result["content"] = enriched_full_text
result["content_type"] = "full_text"
result["pmcid"] = pmcid
@@ -1722,6 +1724,7 @@ The default assumption should be that medical and scientific queries want RECENT
result, abstracts[pmid]
)
result["full_content"] = enriched_content
+ result["full_content_is_complete"] = False
result["content"] = enriched_content
result["content_type"] = "abstract"
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py b/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
index 6989dd1657..e034482965 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_retriever.py
@@ -108,7 +108,10 @@ class RetrieverSearchEngine(BaseSearchEngine):
if doc.page_content
else "",
# Optional fields
+ # Retriever documents may be chunks of the source URL, not the
+ # complete resource that other cache consumers request.
"full_content": doc.page_content,
+ "full_content_is_complete": False,
"author": metadata.get("author", ""),
"date": metadata.get("date", ""),
# Include all metadata for flexibility
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_sofya.py b/src/local_deep_research/web_search_engines/engines/search_engine_sofya.py
index 6e9d0e6e68..83ba66cce0 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_sofya.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_sofya.py
@@ -255,5 +255,8 @@ class SofyaSearchEngine(BaseSearchEngine):
or result.get("full_content")
or result.get("snippet", "")
)
+ result["full_content_is_complete"] = bool(content) or (
+ result.get("full_content_is_complete") is True
+ )
results.append(result)
return results
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
index ea80086078..a5a30677b2 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
@@ -358,6 +358,9 @@ class WaybackSearchEngine(BaseSearchEngine):
result = item.copy()
result["raw_html"] = raw_html
result["full_content"] = full_content
+ result["full_content_is_complete"] = bool(
+ raw_html and full_content
+ )
results.append(result)
@@ -402,7 +405,7 @@ class WaybackSearchEngine(BaseSearchEngine):
}
previews.append(preview)
- return self._get_full_content(previews)
+ return self._get_full_content_cached(previews)
def search_by_date_range(
self, url: str, start_date: str, end_date: str
@@ -460,7 +463,7 @@ class WaybackSearchEngine(BaseSearchEngine):
}
)
- return self._get_full_content(snapshots)
+ return self._get_full_content_cached(snapshots)
except Exception as e:
safe_msg = self._scrub_error(e)
@@ -504,6 +507,9 @@ class WaybackSearchEngine(BaseSearchEngine):
raw_html, full_content = self._get_wayback_content(wayback_url)
result["raw_html"] = raw_html
result["full_content"] = full_content
+ result["full_content_is_complete"] = bool(
+ raw_html and full_content
+ )
return result
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
index 9d9e2f8f9f..0d761c1aab 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
@@ -384,6 +384,8 @@ Respond with ONE WORD ONLY: CURRENT, HISTORICAL, or UNCLEAR"""
"link": f"https://{self.lang_code}.wikinews.org/?curid={page_id}", # Used by citation handler
"content": full_content,
"full_content": full_content,
+ "full_content_is_complete": not self.search_snippets_only
+ and bool(full_content),
"publication_date": publication_date.isoformat(timespec="seconds"),
}
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
index 75760e0283..9143dd14fc 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
@@ -271,6 +271,7 @@ class WikipediaSearchEngine(BaseSearchEngine):
# Add additional information
result["content"] = page.content
result["full_content"] = page.content
+ result["full_content_is_complete"] = True
result["categories"] = page.categories
result["references"] = page.references
result["links"] = page.links
@@ -350,6 +351,7 @@ class WikipediaSearchEngine(BaseSearchEngine):
if include_content:
result["content"] = page.content
result["full_content"] = page.content
+ result["full_content_is_complete"] = True
result["categories"] = page.categories
result["references"] = page.references
result["links"] = page.links
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index dd10a9f5f7..9371fef3c2 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -456,6 +456,7 @@ class BaseSearchEngine(ABC):
include_full_content: bool = False,
settings_snapshot: Optional[Dict[str, Any]] = None,
programmatic_mode: bool = False,
+ content_cache: Any = None,
progress_callback=None,
**kwargs,
):
@@ -474,6 +475,11 @@ class BaseSearchEngine(ABC):
include_full_content: Whether to use FullSearchResults for full webpage content
settings_snapshot: Settings snapshot for configuration
programmatic_mode: If True, disables database operations and uses memory-only tracking
+ content_cache: Optional shared ``ResearchContentCache`` for the
+ whole research run. When None, the cache bound to the
+ current research (if any) is used, so repeat URLs across
+ the quick-report phase, detailed subsections, lead agent
+ and subagents are served without re-fetching on the spot.
progress_callback: Optional ``(done, total)`` bulk-fetch liveness
hook forwarded to ``FullSearchResults`` via
``_init_full_search`` / ``set_fetch_progress_callback``
@@ -504,6 +510,11 @@ class BaseSearchEngine(ABC):
self.settings_snapshot = (
settings_snapshot or {}
) # Store settings snapshot
+ # Single shared cache for the whole research run. Also honoured
+ # from **kwargs for engines whose __init__ forwards extras.
+ if content_cache is None:
+ content_cache = kwargs.get("content_cache")
+ self.content_cache = content_cache
# Bulk-fetch liveness hook (``(done, total)``) for full-search
# progress. Set at construction via the factory or later via
# ``set_fetch_progress_callback`` (e.g. when
@@ -590,6 +601,422 @@ class BaseSearchEngine(ABC):
else:
self.rate_tracker = get_tracker()
+ def get_content_cache(self) -> Any:
+ """Return the effective shared content cache for this engine.
+
+ Prefers the explicitly configured ``self.content_cache`` (the
+ single cache for the whole research run, threaded through the
+ factory from the strategy), else the cache bound to the current
+ research via the thread-local search context. Returns ``None``
+ when no research cache is active (legacy direct-fetch behaviour).
+ """
+ if getattr(self, "content_cache", None) is not None:
+ return self.content_cache
+ try:
+ from ..utilities.research_content_cache import get_current_cache
+ except Exception: # pragma: no cover - defensive
+ return None
+ try:
+ return get_current_cache()
+ except Exception: # pragma: no cover - defensive
+ return None
+
+ @staticmethod
+ def _collection_scope_for_item(item: Dict[str, Any]) -> Optional[str]:
+ """Return the normalised collection scope for a library chunk *item*.
+
+ The same ``(document, chunk_index)`` can hold different text in
+ two collections (different chunk settings), so chunk cache entries
+ are namespaced by collection. Prefers ``collection_id`` (UUID or
+ ``collection_<uuid>``) from metadata/top-level, falling back to a
+ ``collection_*``-prefixed ``collection_name``. Returns ``None``
+ when no collection can be established — callers bypass the shared
+ URL entry rather than risk serving another collection's text.
+ """
+ try:
+ from ..utilities.research_content_cache import (
+ normalize_collection_scope as _norm,
+ )
+ except Exception: # pragma: no cover - defensive
+ return None
+ metadata = item.get("metadata")
+ if not isinstance(metadata, dict):
+ metadata = {}
+ for source in (metadata, item):
+ if not isinstance(source, dict):
+ continue
+ cid = source.get("collection_id")
+ if isinstance(cid, str) and cid.strip():
+ scoped = _norm(cid)
+ if scoped is not None:
+ return scoped
+ for source in (metadata, item):
+ if not isinstance(source, dict):
+ continue
+ cname = source.get("collection_name")
+ if isinstance(cname, str) and cname.startswith("collection_"):
+ return cname
+ return None
+
+ @staticmethod
+ def _is_library_chunk_link(link: Any) -> bool:
+ """Return True when *link* is a library chunk URL (``#chunk-N``)."""
+ if not isinstance(link, str):
+ return False
+ try:
+ from ..utilities.url_utils import library_display_url
+ except Exception: # pragma: no cover - defensive
+ return False
+ try:
+ display = library_display_url(link.strip())
+ except Exception: # pragma: no cover - defensive
+ return None # type: ignore[return-value]
+ return display is not None and "#chunk-" in display
+
+ def _get_cache_egress_context(self) -> Any | None:
+ """Egress context for the cache scope gate, memoized per snapshot.
+
+ Mirrors ``_verify_egress_scope`` memo discipline (identity + policy
+ key) so ADAPTIVE resolution — which can do a bounded DNS lookup —
+ runs once per snapshot, not once per cached URL. Returns None when
+ no snapshot is configured (callers fall back to SSRF-only, matching
+ the network path without a context) or when the policy cannot be
+ evaluated — callers must then refuse the cache hit, matching the
+ network path which disables fetching
+ (``_build_full_search_egress_context`` sets ``include_full_content``
+ to False) instead of fetching SSRF-only.
+ """
+ try:
+ snapshot = getattr(self, "settings_snapshot", None)
+ if not isinstance(snapshot, dict):
+ return None
+ strict = _is_strict_scope(snapshot or {})
+ if not snapshot and not strict:
+ return None
+ primary_default = (
+ None if strict else getattr(self, "_engine_name", None)
+ )
+ policy_key = (self._egress_policy_key(), primary_default)
+ cached_ctx = getattr(self, "_cache_egress_ctx", None)
+ cached_key = getattr(self, "_cache_egress_key", None)
+ cached_snap = getattr(self, "_cache_egress_snapshot", None)
+ if (
+ cached_ctx is not None
+ and cached_snap is snapshot
+ and cached_key == policy_key
+ ):
+ return cached_ctx
+ from ..security.egress.policy import (
+ context_from_snapshot,
+ resolve_run_primary_engine,
+ )
+ from ..search_system import username_from_snapshot
+
+ ctx = context_from_snapshot(
+ snapshot,
+ resolve_run_primary_engine(snapshot, default=primary_default),
+ username=username_from_snapshot(snapshot),
+ )
+ self._cache_egress_ctx = ctx
+ self._cache_egress_key = policy_key
+ self._cache_egress_snapshot = snapshot
+ return ctx
+ except Exception: # pragma: no cover - defensive
+ logger.debug("cache scope gate: egress context unavailable")
+ return None
+
+ def _is_cache_url_allowed(self, link: Any) -> bool:
+ """Whether a cache hit for *link* may be served to this engine.
+
+ Defense-in-depth for the shared research cache: content cached by a
+ granted engine (``allow_private_result_fetch=True``) must not flow
+ into a non-granted engine sharing the same run cache. Path-only
+ library routes (``/library/...``, ``/lib/...``) are local DB reads,
+ not network fetches, so they are always allowed. The absolute
+ ``https://library.document/<id>`` alias is NOT exempted — it is a
+ network URL from the engine fill/store path and must pass the same
+ SSRF gate as any web URL. Web URLs must pass the same SSRF gate
+ the fetch path enforces (grant + link-local carve-out).
+
+ Scope-aware: the run's ``evaluate_url`` scope check must also allow
+ the URL (matching the network path's SSRF + scope pair in
+ ``FullSearchResults.run`` / ``_get_full_content``). Unlike
+ ``FullSearchResults._downloader_allow_private_ips`` — which withholds
+ the private grant from the download pipeline because it cannot
+ enforce scope on redirect hops / browser subresources — the cache
+ has no hops, so the boolean grant is kept and scope is enforced
+ per-URL via ``evaluate_url``. No current producer births a
+ scoped-grant private entry the network path would refuse, so this
+ is latent hardening.
+
+ Fail-closed twice: when the SSRF validator cannot be imported the
+ hit is refused, and when a settings snapshot is configured but its
+ policy cannot be evaluated the hit is refused too — matching the
+ network path, which disables fetching instead of falling back to
+ SSRF-only. Path-only library routes stay servable even then: they
+ are local DB reads (the fetch tool's ``_try_resolve_url`` fast path
+ likewise skips the egress gate), so refusing them would hide
+ local-only content under a corrupted scope setting. Successful SSRF
+ verdicts are memoized per-run in the shared cache so repeat hits
+ skip DNS (and stay servable when DNS drops mid-run after a
+ success); refusals are recomputed so a transient DNS blip never
+ pins the URL. The scope verdict reuses the run's own DNS memo in
+ ``EgressContext`` and never burns the run-wide denial quota (cache
+ probes use the non-recording evaluation; only real fetches count).
+ That also means cache probes emit no ``policy denied`` audit line
+ while fetch-path denials of the same URL still do — intended
+ (probes must not burn quota), just a triage asymmetry to know
+ about. An exhausted quota still refuses cache probes
+ (``denial_quota_exceeded``), same as the fetch path.
+ """
+ if not isinstance(link, str) or not link.strip():
+ return False
+ # Local-only fast path first: path-only library routes are DB
+ # reads, not network fetches, so they stay servable even when the
+ # run policy is unevaluable. This deliberately mirrors the fetch
+ # tool's strict grammar (32/64-hex or UUID via
+ # ``library_resolver.parse_library_url``), NOT the wider citation
+ # grammar (``is_safe_document_id`` / ``library_display_url`` accepts
+ # any ``[0-9A-Za-z_-]+`` slug): a slug-shaped route can never
+ # resolve via the fetch tool, so exempting it here would let the
+ # two surfaces drift.
+ try:
+ from ..advanced_search_system.tools.fetch.library_resolver import (
+ parse_library_url,
+ )
+
+ stripped = link.strip()
+ if (
+ stripped.startswith("/")
+ and parse_library_url(stripped) is not None
+ ):
+ return True
+ except Exception: # pragma: no cover - defensive
+ logger.debug("cache grant check: library route parse failed")
+ # Unevaluable policy fails closed for web URLs: a snapshot is
+ # configured but its policy cannot be evaluated (e.g. unknown
+ # egress scope), and the network path disables fetching outright
+ # instead of falling back to SSRF-only.
+ egress_ctx = self._get_cache_egress_context()
+ snapshot = getattr(self, "settings_snapshot", None)
+ if egress_ctx is None and (
+ snapshot or _is_strict_scope(snapshot or {})
+ ):
+ logger.debug(
+ "cache grant check: unevaluable egress policy, refusing hit"
+ )
+ return False
+ try:
+ from ..security.ssrf_validator import validate_url
+ except Exception: # pragma: no cover - defensive
+ logger.debug(
+ "cache grant check: validator unavailable, refusing hit"
+ )
+ return False
+ try:
+ allow_private = bool(
+ getattr(self, "allow_private_result_fetch", False)
+ )
+
+ def _compute() -> bool:
+ return bool(
+ validate_url(
+ link,
+ allow_private_ips=allow_private,
+ block_link_local=True,
+ )
+ )
+
+ cache = self.get_content_cache()
+ _memo = getattr(cache, "validated", None)
+ if callable(_memo):
+ try:
+ ssrf_ok = bool(_memo(link, allow_private, True, _compute))
+ except Exception: # pragma: no cover - defensive
+ return False
+ else:
+ ssrf_ok = _compute()
+ if not ssrf_ok:
+ return False
+ # Scope axis: the network path (FullSearchResults.run /
+ # _get_full_content) runs evaluate_url after SSRF. The cache
+ # must not serve what that path would deny — but the probe must
+ # not burn the run-wide denial quota either, so it evaluates
+ # without recording; only real fetches count toward
+ # MAX_DENIED_FETCHES_PER_RUN.
+ if egress_ctx is not None:
+ try:
+ from ..security.egress.policy import evaluate_url
+
+ decision = evaluate_url(
+ link, egress_ctx, record_denial=False
+ )
+ if not decision.allowed:
+ return False
+ except Exception: # pragma: no cover - defensive
+ return False
+ return True
+ except Exception: # pragma: no cover - defensive
+ return False
+
+ def _fill_full_content_from_cache(
+ self, items: list[Dict[str, Any]]
+ ) -> tuple[list[Dict[str, Any]], list[Dict[str, Any]]]:
+ """Split *items* into (already_cached, needs_fetch).
+
+ Cached items get ``full_content`` filled in place from the shared
+ research cache. Items without a link, or with no cache entry, go
+ to *needs_fetch*. Returns ``([], items)`` when no cache is active.
+
+ Library chunk URLs are namespaced by collection: the same
+ document/chunk URL in two collections holds different text, so a
+ chunk whose collection cannot be established bypasses the shared
+ entry (fresh DB lookup) rather than risking another collection's
+ text. Document-level library URLs (``Document.text_content`` is
+ collection-independent) and web URLs use the URL-only key.
+ """
+ cache = self.get_content_cache()
+ if cache is None or not items:
+ return [], list(items)
+ cached: list[Dict[str, Any]] = []
+ missing: list[Dict[str, Any]] = []
+ for item in items:
+ if not isinstance(item, dict):
+ missing.append(item)
+ continue
+ link = item.get("link") or item.get("url")
+ if not link:
+ missing.append(item)
+ continue
+ if not self._is_cache_url_allowed(link):
+ missing.append(item)
+ continue
+ try:
+ if self._is_library_chunk_link(link):
+ scope = self._collection_scope_for_item(item)
+ if scope is None:
+ missing.append(item)
+ continue
+ hit = cache.get(link, collection_id=scope)
+ else:
+ hit = cache.get(link)
+ except Exception: # pragma: no cover - defensive
+ hit = None
+ if hit is not None and isinstance(hit.get("content"), str):
+ # A preview can already carry an abstract in full_content.
+ # The shared cache contains complete text and takes priority.
+ if (
+ not item.get("full_content")
+ or item.get("full_content_is_complete") is not True
+ ):
+ item["full_content"] = hit["content"]
+ item["full_content_is_complete"] = True
+ cached.append(item)
+ else:
+ missing.append(item)
+ return cached, missing
+
+ def _store_full_content_in_cache(self, items: list[Dict[str, Any]]) -> None:
+ """Store only explicitly complete text in the shared research cache.
+
+ Engines must set ``full_content_is_complete=True`` at the point
+ they retrieve source text. The legacy ``full_content`` field also
+ holds abstracts, snippets, errors and retrieved fragments; those
+ must not satisfy a later full-document fetch or prevent a retry.
+ Unknown producers remain usable as search results without caching.
+
+ Library chunk entries are namespaced by collection (see
+ :meth:`_fill_full_content_from_cache`); chunks without an
+ establishable collection are not stored under the shared URL key.
+ Entries this engine's grant would not allow to read are not
+ written either, keeping the shared cache grant-consistent.
+ """
+ cache = self.get_content_cache()
+ if cache is None or not items:
+ return
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ if item.get("full_content_is_complete") is not True:
+ continue
+ link = item.get("link") or item.get("url")
+ content = item.get("full_content")
+ if not link or not isinstance(content, str) or not content:
+ continue
+ if not self._is_cache_url_allowed(link):
+ continue
+ try:
+ if self._is_library_chunk_link(link):
+ scope = self._collection_scope_for_item(item)
+ if scope is None:
+ continue
+ cache.put(
+ link,
+ content,
+ title=item.get("title"),
+ url_out=link,
+ collection_id=scope,
+ )
+ else:
+ cache.put(
+ link,
+ content,
+ title=item.get("title"),
+ url_out=link,
+ )
+ except Exception: # pragma: no cover - defensive
+ continue
+
+ def _get_full_content_cached(
+ self, relevant_items: list[Dict[str, Any]]
+ ) -> list[Dict[str, Any]]:
+ """Cache-aware wrapper around ``_get_full_content``.
+
+ Serves repeat URLs (quick phase vs subagents, lead vs subagents,
+ repeated ``web_search`` calls) from the single research-scoped
+ cache and only fetches uncached URLs on the spot. Newly fetched
+ content is stored for later consumers in the same research run.
+ """
+ if not relevant_items:
+ return []
+ _, needs_fetch = self._fill_full_content_from_cache(relevant_items)
+ if not needs_fetch:
+ return relevant_items
+ # Fetch only the uncached subset; cached items were filled in place.
+ fetched = self._get_full_content(needs_fetch)
+ # _get_full_content may return a new list; merge back by identity:
+ # cached items are already correct in relevant_items, fetched ones
+ # carry fresh full_content to store.
+ try:
+ self._store_full_content_in_cache(
+ fetched if isinstance(fetched, list) else needs_fetch
+ )
+ except Exception: # allow: silent-exception
+ pass
+ if isinstance(fetched, list) and fetched is not needs_fetch:
+ # Engine returned a new list for the subset: splice it back in
+ # order. Fall back to the in-place list on any shape mismatch.
+ # The contract is length-preserving and order-preserving —
+ # ``zip`` truncation would silently drop results if an engine
+ # returned fewer/reordered items, so pin it with a warning.
+ if len(fetched) != len(needs_fetch):
+ logger.warning(
+ "_get_full_content returned {} items for {} "
+ "requested; falling back to in-place list",
+ len(fetched),
+ len(needs_fetch),
+ )
+ return relevant_items
+ try:
+ by_id = {id(o): n for o, n in zip(needs_fetch, fetched)}
+ merged: list[Dict[str, Any]] = []
+ for item in relevant_items:
+ merged.append(by_id.get(id(item), item))
+ return merged
+ except Exception: # pragma: no cover - defensive
+ return relevant_items
+ return relevant_items
+
@property
def max_filtered_results(self) -> int:
"""Get the maximum number of filtered results."""
@@ -930,7 +1357,10 @@ class BaseSearchEngine(ABC):
logger.info("Returning snippet-only results as per config")
results = filtered_items
else:
- results = self._get_full_content(filtered_items)
+ # Cache-aware: repeat URLs across the quick phase,
+ # subsections and subagents are served from the single
+ # research-scoped cache instead of re-fetched on the spot.
+ results = self._get_full_content_cached(filtered_items)
for content_filter in self._content_filters:
results = content_filter.filter_results(results, query)
@@ -1578,6 +2008,7 @@ class BaseSearchEngine(ABC):
# explicit boolean grant, nothing else, so an engine
# built through this seam does not lose it silently.
allow_private_ips=self.allow_private_result_fetch is True,
+ content_cache=self.get_content_cache(),
progress_callback=(
progress_callback
if progress_callback is not None
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index 2dbb98edf5..d88ca27ae3 100644
--- a/src/local_deep_research/web_search_engines/search_engine_factory.py
+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py
@@ -53,6 +53,7 @@ _BASE_FORWARDED_PARAMS = frozenset(
"language",
"time_period",
"include_full_content",
+ "content_cache",
"progress_callback",
}
)
@@ -140,6 +141,7 @@ def create_search_engine(
username: str | None = None,
settings_snapshot: Dict[str, Any] | None = None,
programmatic_mode: bool = False,
+ content_cache: Any = None,
**kwargs,
) -> Optional[BaseSearchEngine]:
"""
@@ -149,6 +151,11 @@ def create_search_engine(
engine_name: Name of the search engine to create
llm: Language model instance (passed to engines that accept one)
programmatic_mode: If True, disables database operations and metrics tracking
+ content_cache: Optional shared ``ResearchContentCache`` for the whole
+ research run. Threaded into the engine (and its full-search
+ wrapper) so repeat URLs across quick phase, subsections and
+ subagents hit one cache. When None, engines fall back to the
+ cache bound to the current research via thread-local context.
**kwargs: Additional parameters to override defaults
Returns:
@@ -249,6 +256,7 @@ def create_search_engine(
name=engine_name,
max_results=kwargs.get("max_results", 10),
programmatic_mode=programmatic_mode,
+ content_cache=content_cache,
)
# Extract search engine configs from settings snapshot
@@ -605,6 +613,11 @@ def create_search_engine(
# Combine default parameters with provided ones
all_params = {**engine_config.get("default_params", {}), **kwargs}
+ # The shared research cache is a factory-level argument, not an
+ # engine default — inject it so engines that accept it (or **kwargs)
+ # receive the single cache for the whole research run.
+ if content_cache is not None and "content_cache" not in all_params:
+ all_params["content_cache"] = content_cache
# Filter out parameters that aren't accepted by the engine class
# Note: 'self' is always the first parameter of instance methods, so we skip it.
@@ -684,6 +697,15 @@ def create_search_engine(
all_params["search_snippets_only"]
)
+ # Thread the single research-scoped content cache into the engine
+ # (explicit wins; engines also fall back to the registry via
+ # thread-local search context). Covers subclasses that swallow
+ # **kwargs without forwarding to BaseSearchEngine.
+ if isinstance(engine, BaseSearchEngine) and content_cache is not None:
+ try:
+ engine.content_cache = content_cache
+ except Exception: # allow: silent-exception
+ pass
# Stamp the bulk-fetch liveness hook for engines built through
# this seam (pipeline-strategy full-search progress). The base
# engine itself does not fetch, but `_init_full_search` and
@@ -796,6 +818,7 @@ def create_search_engine(
kwargs,
username,
settings_snapshot,
+ content_cache=content_cache,
egress_context=ctx,
)
@@ -824,6 +847,7 @@ def _create_full_search_wrapper(
params: Dict[str, Any],
username: str | None = None,
settings_snapshot: Dict[str, Any] | None = None,
+ content_cache: Any = None,
*,
egress_context: Any = None,
) -> Optional[BaseSearchEngine]:
@@ -986,12 +1010,27 @@ def _create_full_search_wrapper(
and base_engine.allow_private_result_fetch is True
)
+ # Thread the shared research cache into the full-search wrapper so
+ # web_search full-content fetches share it with fetch_content and
+ # the RAG engines.
+ if "content_cache" in wrapper_init_params and content_cache is not None:
+ wrapper_params["content_cache"] = content_cache
+
logger.debug(
f"Creating full search wrapper for {engine_name} with filtered parameters: {wrapper_params.keys()}"
)
# Create the full search wrapper with filtered parameters
service: BaseSearchEngine = full_search_class(**wrapper_params)
+ # Belt-and-suspenders for wrappers that swallow **kwargs without
+ # forwarding content_cache to their base.
+ if content_cache is not None:
+ try:
+ existing = getattr(service, "content_cache", None)
+ if existing is None:
+ service.content_cache = content_cache
+ except Exception: # allow: silent-exception
+ pass
return service
except Exception as e:
@@ -1021,6 +1060,7 @@ def get_search(
max_filtered_results: Optional[int] = None,
settings_snapshot: Dict[str, Any] | None = None,
programmatic_mode: bool = False,
+ content_cache: Any = None,
progress_callback=None,
):
"""
@@ -1146,6 +1186,7 @@ def get_search(
search_tool,
settings_snapshot=settings_snapshot,
programmatic_mode=programmatic_mode,
+ content_cache=content_cache,
**params,
)
diff --git a/tests/advanced_search_system/tools/test_library_resolver.py b/tests/advanced_search_system/tools/test_library_resolver.py
index d6ebe5e074..6f0eb5e419 100644
--- a/tests/advanced_search_system/tools/test_library_resolver.py
+++ b/tests/advanced_search_system/tools/test_library_resolver.py
@@ -254,6 +254,90 @@ def test_resolve_library_document_reports_missing_chunk_when_chunk_missing():
)
+def test_resolve_library_document_missing_chunk_not_cached_and_retries_successfully():
+ """Missing chunks must not be cached as source text (PR #6759).
+
+ A chunk-anchored citation whose chunk row is missing returns a
+ "Chunk N not found" message, but that failure must NOT be written to
+ the content cache. A later call after the chunk is indexed must query
+ the database and return the real text, while a successfully resolved
+ chunk must be cached and reused on retry without querying the database.
+ """
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ resolve_library_document,
+ )
+ from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ )
+ from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+ )
+
+ doc_id = "123e4567-e89b-12d3-a456-426614174000"
+ url = f"/library/document/{doc_id}/chunks#chunk-3"
+
+ document = MagicMock()
+ document.id = doc_id
+ document.title = "My Paper"
+ document.text_content = "full document body"
+
+ chunk = MagicMock()
+ chunk.id = 1
+ chunk.chunk_index = 3
+ chunk.chunk_text = "Real chunk 3 text content"
+ chunk.collection_name = "default"
+
+ chunk_available = False
+ session = MagicMock()
+
+ def query_side_effect(model):
+ q = MagicMock()
+ if model == Document:
+ q.filter_by.return_value.first.return_value = document
+ elif model == DocumentChunk:
+ q.filter.return_value.order_by.return_value.first.return_value = (
+ chunk if chunk_available else None
+ )
+ return q
+
+ session.query.side_effect = query_side_effect
+ session_cm = MagicMock()
+ session_cm.__enter__.return_value = session
+ session_cm.__exit__.return_value = False
+
+ cache = ResearchContentCache()
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=session_cm,
+ ):
+ # 1. First attempt: chunk does not exist yet
+ res1 = resolve_library_document(url, "alice", content_cache=cache)
+ assert res1 is not None
+ assert "Chunk 3 not found for document" in res1["content"]
+ # Must NOT be stored in cache
+ assert cache.get(url) is None
+
+ # 2. Chunk becomes available; retry through the SAME cache
+ chunk_available = True
+ session.query.reset_mock()
+ res2 = resolve_library_document(url, "alice", content_cache=cache)
+ assert res2 is not None
+ assert res2["content"] == "Real chunk 3 text content"
+ # Must hit DB because failure was not cached
+ assert session.query.call_count > 0
+ # Now the successful resolution IS cached
+ assert cache.get(url) is not None
+
+ # 3. Control: repeat with chunk available -> served from cache, no DB lookup
+ session.query.reset_mock()
+ res3 = resolve_library_document(url, "alice", content_cache=cache)
+ assert res3 is not None
+ assert res3["content"] == "Real chunk 3 text content"
+ assert session.query.call_count == 0
+
+
def test_resolve_library_document_returns_empty_content_when_chunk_text_empty():
"""When a chunk is present but its chunk_text is empty, returns content=""
rather than falling back to the full document."""
diff --git a/tests/research_library/downloaders/test_arxiv_html_text.py b/tests/research_library/downloaders/test_arxiv_html_text.py
index 093b44af61..c89020311d 100644
--- a/tests/research_library/downloaders/test_arxiv_html_text.py
+++ b/tests/research_library/downloaders/test_arxiv_html_text.py
@@ -488,7 +488,9 @@ def test_text_falls_back_when_html_pipeline_cannot_be_used(downloader, mocker):
def test_text_entrypoints_share_the_same_download_seam(downloader, mocker):
# Given a successful text behavior seam
text_download = mocker.patch.object(
- downloader, "download_text", return_value="shared text"
+ downloader,
+ "download_text_with_source",
+ return_value=ArxivTextResult("shared text", ArxivTextSource.ARXIV_HTML),
)
mocker.patch.object(
downloader,
diff --git a/tests/research_library/downloaders/test_biorxiv_coverage.py b/tests/research_library/downloaders/test_biorxiv_coverage.py
index d06c3d163b..cce0da1b95 100644
--- a/tests/research_library/downloaders/test_biorxiv_coverage.py
+++ b/tests/research_library/downloaders/test_biorxiv_coverage.py
@@ -443,6 +443,7 @@ class TestDownloadWithResultText:
)
assert result.is_success is True
assert result.content == b"Title: X\nAbstract: Y"
+ assert result.content_is_complete is False
def test_fallback_to_pdf_extraction(self, raw_downloader, mock_pdf_content):
raw_downloader._fetch_abstract_from_page = Mock(return_value=None)
@@ -456,6 +457,7 @@ class TestDownloadWithResultText:
)
assert result.is_success is True
assert result.content == b"pdf text here"
+ assert result.content_is_complete is True
def test_failure_returns_skip_reason(self, raw_downloader):
raw_downloader._fetch_abstract_from_page = Mock(return_value=None)
diff --git a/tests/research_library/downloaders/test_extraction_pipeline.py b/tests/research_library/downloaders/test_extraction_pipeline.py
index f64df9d871..b7fd1c7e27 100644
--- a/tests/research_library/downloaders/test_extraction_pipeline.py
+++ b/tests/research_library/downloaders/test_extraction_pipeline.py
@@ -1101,6 +1101,72 @@ class TestBatchFetchProgress:
assert len(results) == 2
assert calls == [(0, 2), (1, 2), (2, 2)]
+ @pytest.mark.parametrize("all_cached", [False, True])
+ @pytest.mark.parametrize("flaky_callback", [False, True])
+ def test_cached_results_still_report_progress(
+ self, monkeypatch, all_cached, flaky_callback
+ ):
+ from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+ )
+
+ self._html_only(monkeypatch)
+ monkeypatch.setattr(
+ pipeline, "_is_cache_hit_allowed", lambda *args: True
+ )
+ cache = ResearchContentCache()
+ urls = ["https://a.example/1", "https://a.example/2"]
+ cache.put(urls[0], "cached first")
+ if all_cached:
+ cache.put(urls[1], "cached second")
+ calls = []
+
+ def progress(done, total):
+ calls.append((done, total))
+ if flaky_callback and done == 1:
+ raise RuntimeError("flaky callback")
+
+ results = pipeline.batch_fetch_and_extract(
+ urls, content_cache=cache, progress_callback=progress
+ )
+ assert results == {
+ urls[0]: "cached first",
+ urls[1]: "cached second" if all_cached else "content",
+ }
+ assert calls == [(0, 2), (1, 2), (2, 2)]
+
+ def test_cached_result_can_cancel_before_remaining_downloads(
+ self, monkeypatch
+ ):
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+ )
+
+ download = Mock(
+ side_effect=AssertionError("cancelled batch performed a download")
+ )
+ monkeypatch.setattr(pipeline, "_try_specialized_downloader", download)
+ monkeypatch.setattr(
+ pipeline, "_is_cache_hit_allowed", lambda *args: True
+ )
+ cache = ResearchContentCache()
+ urls = ["https://a.example/1", "https://a.example/2"]
+ cache.put(urls[0], "cached first")
+ calls = []
+
+ def progress(done, total):
+ calls.append((done, total))
+ if done == 1:
+ raise ResearchTerminatedException()
+
+ with pytest.raises(ResearchTerminatedException):
+ pipeline.batch_fetch_and_extract(
+ urls, content_cache=cache, progress_callback=progress
+ )
+ assert calls == [(0, 2), (1, 2)]
+ download.assert_not_called()
+
def test_specialized_hits_count_as_done(self, monkeypatch):
def mock_specialized(url, timeout=30):
if "arxiv" in url:
diff --git a/tests/security/test_egress_transport_scope_v2.py b/tests/security/test_egress_transport_scope_v2.py
index a7e3884557..60f16adea4 100644
--- a/tests/security/test_egress_transport_scope_v2.py
+++ b/tests/security/test_egress_transport_scope_v2.py
@@ -447,6 +447,23 @@ def test_specialized_pipeline_passes_context_to_api_transport():
assert seen == [ctx]
+def test_specialized_pipeline_propagates_denial():
+ ctx = _context(EgressScope.PRIVATE_ONLY)
+ denial = PolicyDeniedError(Decision(False, "scope_mismatch_private_only"))
+
+ with (
+ patch.object(
+ PubMedDownloader, "download_with_result", side_effect=denial
+ ),
+ patch.object(AutoHTMLDownloader, "download") as mock_html_download,
+ pytest.raises(PolicyDeniedError),
+ ):
+ pipeline.fetch_and_extract(
+ "https://pubmed.ncbi.nlm.nih.gov/12345/", egress_context=ctx
+ )
+ mock_html_download.assert_not_called()
+
+
def test_batch_contains_denial_without_falling_back_for_that_url():
denied_url = "http://denied.example/"
allowed_url = "http://allowed.example/"
diff --git a/tests/utilities/test_research_cache_completeness.py b/tests/utilities/test_research_cache_completeness.py
new file mode 100644
index 0000000000..ef4417f9a5
--- /dev/null
+++ b/tests/utilities/test_research_cache_completeness.py
@@ -0,0 +1,492 @@
+"""Only complete source text may satisfy a later full-document request."""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.content_fetcher.fetcher import ContentFetcher
+from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+)
+from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
+ ArXivSearchEngine,
+ FullTextFetchFailedError,
+ FullTextNotExtractedError,
+)
+
+
+URL = "https://arxiv.org/abs/2301.12345"
+ABSTRACT = "An abstract that is longer than the complete test paper."
+BODY = "Complete paper."
+
+
+def arxiv_engine(tmp_path):
+ with patch.object(
+ ArXivSearchEngine, "_create_journal_filter", return_value=None
+ ):
+ engine = ArXivSearchEngine(
+ include_full_text=True,
+ download_dir=str(tmp_path),
+ settings_snapshot={},
+ )
+ engine._configure_programmatic_mode(True)
+ engine.search_snippets_only = False
+ engine.content_cache = ResearchContentCache()
+ engine.rate_tracker = MagicMock()
+ paper = SimpleNamespace(
+ entry_id=URL,
+ summary=ABSTRACT,
+ authors=[],
+ published=None,
+ updated=None,
+ categories=[],
+ comment="",
+ doi="",
+ journal_ref="",
+ title="Test paper",
+ )
+
+ def previews(query):
+ engine._papers = {URL: paper}
+ return [
+ {"id": URL, "link": URL, "title": paper.title, "snippet": ABSTRACT}
+ ]
+
+ engine._get_previews = previews
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ):
+ yield engine
+
+
+ "initial",
+ [
+ FullTextFetchFailedError("temporary outage"),
+ FullTextNotExtractedError("empty extraction"),
+ None,
+ " ",
+ ],
+)
+def test_arxiv_retries_partial_content_after_recovery(arxiv_engine, initial):
+ engine = arxiv_engine
+ engine._fetch_full_text = MagicMock(side_effect=[initial, BODY])
+ assert engine.run("first search")[0]["full_content"] == ABSTRACT
+ assert engine.content_cache.get(URL) is None
+ assert engine.run("later search")[0]["full_content"] == BODY
+ assert engine.run("repeat search")[0]["full_content"] == BODY
+ assert engine._fetch_full_text.call_count == 2
+ assert engine.content_cache.get(URL)["content"] == BODY
+
+
[email protected]("reason", ["disabled", "budget"])
+def test_abstract_only_search_does_not_satisfy_full_fetch(arxiv_engine, reason):
+ engine = arxiv_engine
+ if reason == "disabled":
+ engine.include_full_text = False
+ else:
+ engine.max_full_text = 0
+ engine._fetch_full_text = MagicMock(
+ side_effect=AssertionError("search must not fetch")
+ )
+ assert engine.run("search")[0]["full_content"] == ABSTRACT
+ downloader = MagicMock()
+ downloader.download_with_result.return_value = SimpleNamespace(
+ is_success=True, content=BODY.encode(), skip_reason=None
+ )
+ downloader.get_metadata.return_value = {"title": "Test paper"}
+ with (
+ patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ),
+ patch.object(
+ ContentFetcher, "_get_downloader", return_value=downloader
+ ),
+ ):
+ with ContentFetcher(content_cache=engine.content_cache) as fetcher:
+ assert fetcher.fetch(URL)["content"] == BODY
+ assert fetcher.fetch(URL)["content"] == BODY
+ assert downloader.download_with_result.call_count == 1
+
+
+def test_complete_cache_replaces_partial_preview(arxiv_engine):
+ engine = arxiv_engine
+ engine.content_cache.put(URL, BODY)
+ engine._fetch_full_text = MagicMock(
+ side_effect=AssertionError("must reuse complete text")
+ )
+ result = engine._get_full_content_cached(
+ [
+ {
+ "link": URL,
+ "full_content": ABSTRACT,
+ "full_content_is_complete": False,
+ }
+ ]
+ )
+ assert result[0]["full_content"] == BODY
+ assert result[0]["full_content_is_complete"] is True
+
+
+def test_complete_preview_is_preserved(arxiv_engine):
+ arxiv_engine.content_cache.put(URL, "Previously fetched text")
+ result = arxiv_engine._get_full_content_cached(
+ [
+ {
+ "link": URL,
+ "full_content": BODY,
+ "full_content_is_complete": True,
+ }
+ ]
+ )
+ assert result[0]["full_content"] == BODY
+
+
[email protected]("complete", [None, False, "true", 1, True])
+def test_unverified_search_content_cannot_fill_document_cache(
+ arxiv_engine, complete
+):
+ item = {"link": URL, "full_content": ABSTRACT}
+ if complete is not None:
+ item["full_content_is_complete"] = complete
+ arxiv_engine._store_full_content_in_cache([item])
+ assert (arxiv_engine.content_cache.get(URL) is not None) is (
+ complete is True
+ )
+
+
+def test_pubmed_abstract_fallback_is_retried():
+ from local_deep_research.web_search_engines.engines.search_engine_pubmed import (
+ PubMedSearchEngine,
+ )
+
+ with patch.object(
+ PubMedSearchEngine, "_create_journal_filter", return_value=None
+ ):
+ engine = PubMedSearchEngine(get_full_text=True, settings_snapshot={})
+ engine.content_cache = ResearchContentCache()
+ engine._get_article_abstracts = MagicMock(return_value={"123": ABSTRACT})
+ engine._get_article_detailed_metadata = MagicMock(return_value={})
+ engine._find_pmc_ids = MagicMock(return_value={"123": "PMC123"})
+ engine._get_pmc_full_text = MagicMock(side_effect=[None, BODY])
+ url = "https://pubmed.ncbi.nlm.nih.gov/123/"
+
+ def search():
+ return engine._get_full_content_cached(
+ [{"_pmid": "123", "link": url, "title": "Paper"}]
+ )[0]
+
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ):
+ assert search()["content_type"] == "abstract"
+ assert engine.content_cache.get(url) is None
+ assert BODY in search()["full_content"]
+ assert BODY in search()["full_content"]
+ assert engine._get_pmc_full_text.call_count == 2
+
+
+ "initial", [None, {}, RuntimeError("temporary outage")]
+)
+def test_paperless_snippet_fallback_is_retried(initial):
+ from local_deep_research.web_search_engines.engines.search_engine_paperless import (
+ PaperlessSearchEngine,
+ )
+
+ engine = PaperlessSearchEngine.__new__(PaperlessSearchEngine)
+ engine.include_content = True
+ engine.content_cache = ResearchContentCache()
+ engine._make_request = MagicMock(side_effect=[initial, {"content": BODY}])
+ engine._scrub_error = MagicMock(return_value="request failed")
+ engine._is_cache_url_allowed = MagicMock(return_value=True)
+ url = "https://paperless.example/documents/123/"
+
+ def search():
+ return engine._get_full_content_cached(
+ [
+ {
+ "link": url,
+ "snippet": ABSTRACT,
+ "_raw_data": {},
+ "metadata": {"doc_id": "123"},
+ }
+ ]
+ )[0]
+
+ assert search()["full_content"] == ABSTRACT
+ assert engine.content_cache.get(url) is None
+ assert search()["full_content"] == BODY
+ assert search()["full_content"] == BODY
+ assert engine._make_request.call_count == 2
+
+
+def test_wayback_error_text_is_not_a_complete_cached_page():
+ from local_deep_research.web_search_engines.engines.search_engine_wayback import (
+ WaybackSearchEngine,
+ )
+
+ engine = WaybackSearchEngine.__new__(WaybackSearchEngine)
+ engine.content_cache = ResearchContentCache()
+ engine.rate_tracker = MagicMock()
+ engine.engine_type = "wayback"
+ engine._is_cache_url_allowed = MagicMock(return_value=True)
+ engine._get_wayback_content = MagicMock(
+ side_effect=[
+ ("", "Error retrieving content: temporary outage"),
+ ("<p>Complete paper.</p>", BODY),
+ ]
+ )
+ url = "https://web.archive.org/web/20200101/https://example.com/"
+ assert (
+ "Error retrieving"
+ in engine._get_full_content_cached([{"link": url}])[0]["full_content"]
+ )
+ assert engine.content_cache.get(url) is None
+ assert (
+ engine._get_full_content_cached([{"link": url}])[0]["full_content"]
+ == BODY
+ )
+ assert (
+ engine._get_full_content_cached([{"link": url}])[0]["full_content"]
+ == BODY
+ )
+ assert engine._get_wayback_content.call_count == 2
+
+
[email protected]("kind", ["issue", "user"])
+def test_github_summaries_do_not_fill_document_cache(kind):
+ from local_deep_research.web_search_engines.engines.search_engine_github import (
+ GitHubSearchEngine,
+ )
+
+ engine = GitHubSearchEngine.__new__(GitHubSearchEngine)
+ engine.content_cache = ResearchContentCache()
+ engine._is_cache_url_allowed = MagicMock(return_value=True)
+ url = "https://github.com/example/repo/issues/1"
+ result = engine._get_full_content_cached(
+ [
+ {
+ "link": url,
+ "snippet": ABSTRACT,
+ "search_type": kind,
+ }
+ ]
+ )
+ assert ABSTRACT in result[0]["full_content"]
+ assert engine.content_cache.get(url) is None
+
+
+def test_sofya_snippet_then_extracted_content():
+ from local_deep_research.web_search_engines.engines.search_engine_sofya import (
+ SofyaSearchEngine,
+ )
+
+ engine = SofyaSearchEngine.__new__(SofyaSearchEngine)
+ engine.content_cache = ResearchContentCache()
+ engine._is_cache_url_allowed = MagicMock(return_value=True)
+ preview = {"link": URL, "snippet": ABSTRACT}
+ assert (
+ engine._get_full_content_cached([preview.copy()])[0]["full_content"]
+ == ABSTRACT
+ )
+ assert engine.content_cache.get(URL) is None
+ preview["_full_result"] = {"content": BODY}
+ assert engine._get_full_content_cached([preview])[0]["full_content"] == BODY
+ assert engine.content_cache.get(URL)["content"] == BODY
+
+
+def test_missing_library_chunk_can_be_retried():
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ engine = LibraryRAGSearchEngine.__new__(LibraryRAGSearchEngine)
+ engine.username = "cache-test-user"
+ engine.content_cache = ResearchContentCache()
+ engine._is_cache_url_allowed = MagicMock(return_value=True)
+ document_id = "12345678-1234-5678-1234-567812345678"
+ url = f"/library/document/{document_id}#chunk-1"
+ session = MagicMock()
+ query = session.query.return_value
+ query.filter.return_value = query
+ query.order_by.return_value.first.side_effect = [
+ None,
+ SimpleNamespace(chunk_text=BODY),
+ ]
+
+ def search():
+ return engine._get_full_content_cached(
+ [
+ {
+ "link": url,
+ "metadata": {
+ "source_id": document_id,
+ "chunk_index": 1,
+ "collection_id": "test",
+ },
+ }
+ ]
+ )[0]
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as context:
+ context.return_value.__enter__.return_value = session
+ assert "not found" in search()["full_content"]
+ assert engine.content_cache.get(url, collection_id="test") is None
+ assert search()["full_content"] == BODY
+ assert search()["full_content"] == BODY
+ assert context.call_count == 2
+
+
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
[email protected]("limit", [1_000, 10_000, 50_000])
+def test_repeated_tool_fetch_uses_same_limit_and_keeps_raw_text(mode, limit):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
+ )
+
+ cache = ResearchContentCache()
+ raw = "Ω" * (limit + 2000)
+ downloader = MagicMock()
+ downloader.download_with_result.return_value = SimpleNamespace(
+ is_success=True, content=raw.encode(), skip_reason=None
+ )
+ downloader.get_metadata.return_value = {"title": "Paper"}
+ model = MagicMock()
+ model.invoke.return_value = SimpleNamespace(content="Selected text")
+ tool = build_fetch_tool(
+ mode,
+ SearchResultsCollector([]),
+ model=model,
+ overall_query="Question",
+ settings_snapshot={"search.fetch.content_max_length": {"value": limit}},
+ max_fetches=0,
+ content_cache=cache,
+ )
+ args = {"url": URL}
+ if mode != "full":
+ args["focus"] = "Question"
+ with (
+ patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.security.egress.fetch.policy_aware_validate_url",
+ return_value=True,
+ ),
+ patch.object(
+ ContentFetcher, "_get_downloader", return_value=downloader
+ ),
+ ):
+ outputs = [tool.invoke(args), tool.invoke(args)]
+ if mode != "full":
+ assert model.invoke.call_count == 2
+ outputs = [call.args[0] for call in model.invoke.call_args_list]
+ assert [text.count("Ω") for text in outputs] == [limit] * 2
+ assert cache.get(URL)["content"] == raw
+ assert downloader.download_with_result.call_count == 1
+
+
[email protected]("surface", ["fetcher", "tool", "pipeline", "batch"])
+def test_arxiv_download_metadata_does_not_prevent_later_full_text(
+ monkeypatch, surface
+):
+ from local_deep_research.research_library.downloaders.arxiv import (
+ ArxivDownloader,
+ ArxivTextResult,
+ ArxivTextSource,
+ )
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline,
+ )
+
+ raw = BODY * 20
+ source = MagicMock(
+ side_effect=[
+ ArxivTextResult(ABSTRACT, ArxivTextSource.ARXIV_API),
+ ArxivTextResult(raw, ArxivTextSource.ARXIV_HTML),
+ ]
+ )
+ # Keep the real downloader's result construction and downstream cache
+ # paths. Only replace its transport/source selection and resource setup.
+ monkeypatch.setattr(
+ ArxivDownloader, "__init__", lambda self, **kwargs: None
+ )
+ monkeypatch.setattr(ArxivDownloader, "download_text_with_source", source)
+ monkeypatch.setattr(ArxivDownloader, "get_metadata", lambda self, url: {})
+ monkeypatch.setattr(ArxivDownloader, "close", lambda self: None)
+ monkeypatch.setattr(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ lambda *args, **kwargs: True,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ lambda *args, **kwargs: True,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.security.egress.fetch.policy_aware_validate_url",
+ lambda *args, **kwargs: True,
+ )
+ cache = ResearchContentCache()
+ if surface in {"fetcher", "tool"}:
+ monkeypatch.setattr(
+ ContentFetcher,
+ "_get_downloader",
+ lambda self, url_type: ArxivDownloader(),
+ )
+ if surface == "fetcher":
+
+ def fetch():
+ with ContentFetcher(content_cache=cache) as fetcher:
+ return fetcher.fetch(URL)["content"]
+ elif surface == "tool":
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
+ )
+
+ tool = build_fetch_tool(
+ "full",
+ SearchResultsCollector([]),
+ content_cache=cache,
+ max_fetches=0,
+ )
+
+ def fetch():
+ return tool.invoke({"url": URL})
+ elif surface == "pipeline":
+
+ def fetch():
+ return pipeline.fetch_and_extract(URL, content_cache=cache)
+ else:
+
+ def fetch():
+ return pipeline.batch_fetch_and_extract([URL], content_cache=cache)[
+ URL
+ ]
+
+ first = fetch()
+ if surface in {"pipeline", "batch"}:
+ assert first is None
+ else:
+ assert ABSTRACT in first
+ assert cache.get(URL) is None
+ assert raw in fetch()
+ assert raw in fetch()
+ assert cache.get(URL)["content"] == raw
+ assert source.call_count == 2
diff --git a/tests/utilities/test_research_content_cache.py b/tests/utilities/test_research_content_cache.py
new file mode 100644
index 0000000000..00d117df7a
--- /dev/null
+++ b/tests/utilities/test_research_content_cache.py
@@ -0,0 +1,2873 @@
+"""Tests for the single shared research content cache.
+
+Every consumer that needs the full text of a webpage, a RAG chunk or a
+library document — the ``web_search`` tool (engines / FullSearchResults),
+the ``fetch_content`` tool (ContentFetcher + summary-prompt construction),
+the library resolver, and the extraction pipeline — resolves through one
+``ResearchContentCache`` per research run. These tests pin that contract:
+
+* key normalisation (tracking params collapse, chunk vs document distinct),
+* store/lookup semantics (longest fetch wins, failures never cached),
+* concurrent coalescing (parallel subagents fetch once),
+* registry binding via the thread-local search context (incl. worker threads),
+* cross-consumer sharing (pipeline fills, fetcher/fetch-tool/engine serve),
+* lead + subagent fetch tools sharing one instance,
+* one cache owned by ``AdvancedSearchSystem`` for quick phase + subsections.
+
+No real network, DB, or LLM is touched — downloaders and fetchers are mocked.
+"""
+
+from __future__ import annotations
+
+import threading
+import uuid
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+ bind_cache_to_research,
+ content_cache_key,
+ get_cache_for_research,
+ get_current_cache,
+ resolve_cache,
+ unbind_cache_from_research,
+)
+from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ get_search_context,
+ search_context,
+ set_search_context,
+)
+
+
+def fresh_context():
+ """Guarantee no search-context or registry leakage between tests."""
+ clear_search_context()
+ yield
+ clear_search_context()
+
+
+def bound_cache(fresh_context):
+ """One cache bound to a unique research id, unbound on teardown."""
+ rid = f"test-{uuid.uuid4().hex}"
+ cache = ResearchContentCache()
+ bind_cache_to_research(rid, cache)
+ set_search_context({"research_id": rid})
+ yield rid, cache
+ clear_search_context()
+ unbind_cache_from_research(rid)
+
+
+class TestContentCacheKey:
+ def test_tracking_params_collapse(self):
+ """Tracking params collapse; accepts over-merge on sites varying content per param."""
+ assert content_cache_key(
+ "https://example.com/p?utm_source=x&foo=1"
+ ) == content_cache_key("https://example.com/p?foo=1")
+
+ def test_fragment_stays_distinct_for_web(self):
+ """Fragments select distinct views in client-routed SPAs (JS rendering)."""
+ assert content_cache_key(
+ "https://example.com/p#section"
+ ) != content_cache_key("https://example.com/p")
+ assert content_cache_key(
+ "https://spa.example.com/app#/route-alpha"
+ ) != content_cache_key("https://spa.example.com/app#/route-beta")
+
+ def test_different_paths_differ(self):
+ assert content_cache_key("https://example.com/a") != content_cache_key(
+ "https://example.com/b"
+ )
+
+ def test_trailing_slash_stays_distinct_for_web(self):
+ """PR #6759: ``/article`` and ``/article/`` are different HTTP
+ resources and must never share a content entry (the bibliography
+ ``canonical_url_key`` collapses them; the content key must not)."""
+ assert content_cache_key(
+ "https://example.com/article"
+ ) != content_cache_key("https://example.com/article/")
+ assert content_cache_key(
+ "http://127.0.0.1:9/article"
+ ) != content_cache_key("http://127.0.0.1:9/article/")
+
+ def test_userinfo_stays_distinct_for_web(self):
+ """PR #6759: userinfo selects a different origin view — a
+ credentialed URL must never hit the bare-host entry."""
+ assert content_cache_key(
+ "https://user:[email protected]/p"
+ ) != content_cache_key("https://example.com/p")
+ assert content_cache_key(
+ "https://[email protected]/p"
+ ) != content_cache_key("https://[email protected]/p")
+
+ def test_query_params_stay_distinct_for_web(self):
+ assert content_cache_key(
+ "https://example.com/p?a=1"
+ ) != content_cache_key("https://example.com/p?a=2")
+ assert content_cache_key(
+ "https://example.com/p?foo=1"
+ ) != content_cache_key("https://example.com/p")
+
+ def test_library_chunk_distinct_from_document(self):
+ doc = "/library/document/12345678123456781234567812345678"
+ chunk = doc + "#chunk-3"
+ assert content_cache_key(doc) != content_cache_key(chunk)
+
+ def test_library_lib_spelling_matches(self):
+ assert content_cache_key(
+ "/lib/document/12345678123456781234567812345678"
+ ) == content_cache_key(
+ "/library/document/12345678123456781234567812345678"
+ )
+
+ def test_non_string_safe(self):
+ assert content_cache_key(None) # must not raise
+ assert content_cache_key("") != content_cache_key(
+ "https://example.com/"
+ )
+
+
+class TestStoreSemantics:
+ def test_put_get_roundtrip(self):
+ cache = ResearchContentCache()
+ cache.put("https://example.com/x", "body", title="T")
+ hit = cache.get("https://example.com/x")
+ assert hit is not None and hit["content"] == "body"
+ assert hit["title"] == "T"
+
+ def test_get_returns_copy(self):
+ cache = ResearchContentCache()
+ cache.put("https://example.com/x", "body")
+ hit = cache.get("https://example.com/x")
+ assert hit is not None
+ hit["content"] = "mutated"
+ assert cache.get("https://example.com/x")["content"] == "body"
+
+ def test_longest_fetch_wins(self):
+ cache = ResearchContentCache()
+ cache.put("https://example.com/x", "short")
+ cache.put("https://example.com/x", "a much longer content here")
+ assert (
+ cache.get("https://example.com/x")["content"]
+ == "a much longer content here"
+ )
+ cache.put("https://example.com/x", "tiny")
+ assert (
+ cache.get("https://example.com/x")["content"]
+ == "a much longer content here"
+ )
+
+ def test_miss_returns_none(self):
+ assert ResearchContentCache().get("https://nope.example/") is None
+
+ def test_stats_and_len(self):
+ cache = ResearchContentCache()
+ cache.put("https://example.com/x", "short")
+ cache.put("https://example.com/x", "a much longer content here")
+ cache.get("https://example.com/x")
+ cache.get("https://example.com/missing")
+ stats = cache.stats()
+ assert stats["entries"] == 1
+ assert stats["puts"] == 2
+ assert stats["hits"] >= 1
+ assert stats["misses"] >= 1
+ assert len(cache) == 1
+
+ def test_clear(self):
+ cache = ResearchContentCache()
+ cache.put("https://example.com/x", "body")
+ cache.clear()
+ assert len(cache) == 0
+ assert cache.get("https://example.com/x") is None
+ stats = cache.stats()
+ assert stats["hits"] == 0
+ assert stats["misses"] == 1
+ assert stats["puts"] == 0
+ assert stats["entries"] == 0
+ assert stats["evictions"] == 0
+ assert stats["total_bytes"] == 0
+
+ def test_get_or_fetch_caches_success(self):
+ cache = ResearchContentCache()
+ calls = {"n": 0}
+
+ def fetch():
+ calls["n"] += 1
+ return {
+ "content": "hello",
+ "title": "T",
+ "url": "https://example.com/c",
+ }
+
+ first = cache.get_or_fetch("https://example.com/c", fetch)
+ second = cache.get_or_fetch("https://example.com/c", fetch)
+ assert first is not None and first["content"] == "hello"
+ assert second is not None and second["content"] == "hello"
+ assert calls["n"] == 1
+
+ def test_get_or_fetch_never_caches_failure(self):
+ cache = ResearchContentCache()
+ assert cache.get_or_fetch("https://example.com/n", lambda: None) is None
+ assert len(cache) == 0
+ assert cache.get("https://example.com/n") is None
+
+ def test_get_or_fetch_cleans_inflight_on_exception(self):
+ """Ordinary exceptions release the slot so a retry refetches."""
+ cache = ResearchContentCache()
+ url = "https://example.com/flaky"
+
+ def boom():
+ raise ValueError("boom")
+
+ with pytest.raises(ValueError, match="boom"):
+ cache.get_or_fetch(url, boom)
+ # Slot released and waiters woken: no dead event retained.
+ assert cache._inflight == {}
+ assert len(cache) == 0
+
+ calls = {"n": 0}
+
+ def ok():
+ calls["n"] += 1
+ return {
+ "content": "recovered",
+ "title": "T",
+ "url": url,
+ }
+
+ result = cache.get_or_fetch(url, ok)
+ assert result is not None and result["content"] == "recovered"
+ assert calls["n"] == 1
+
+ def test_get_or_fetch_cleans_inflight_on_cancellation(self):
+ """BaseException (cancellation) releases the slot like Exception."""
+
+ class _Cancelled(BaseException):
+ pass
+
+ cache = ResearchContentCache()
+ url = "https://example.com/cancelled"
+
+ def boom():
+ raise _Cancelled("cancelled")
+
+ with pytest.raises(_Cancelled):
+ cache.get_or_fetch(url, boom)
+ # Old `except Exception` cleanup leaked here: the unset event stayed
+ # in _inflight and a later caller waited on it past wait_timeout.
+ assert cache._inflight == {}
+ assert len(cache) == 0
+
+ def ok():
+ return {
+ "content": "recovered",
+ "title": "T",
+ "url": url,
+ }
+
+ # Must become the fetcher immediately, not wait on a dead event.
+ result = cache.get_or_fetch(url, ok, wait_timeout=5.0)
+ assert result is not None and result["content"] == "recovered"
+
+ def test_get_or_fetch_cleans_inflight_on_put_failure(self):
+ """A put failure still wakes waiters so they retry, not hang."""
+ cache = ResearchContentCache()
+ url = "https://example.com/put-boom"
+
+ def ok():
+ return {
+ "content": "hello",
+ "title": "T",
+ "url": url,
+ }
+
+ with patch.object(
+ ResearchContentCache, "put", side_effect=RuntimeError("put boom")
+ ):
+ with pytest.raises(RuntimeError, match="put boom"):
+ cache.get_or_fetch(url, ok)
+ assert cache._inflight == {}
+ # Retry after the put failure stores normally.
+ result = cache.get_or_fetch(url, ok)
+ assert result is not None and result["content"] == "hello"
+
+ def test_get_or_fetch_waiter_recovers_after_cancellation(self):
+ """A waiter on a cancelled fetch falls through to its own fetch."""
+ import time
+
+ class _Cancelled(BaseException):
+ pass
+
+ cache = ResearchContentCache()
+ url = "https://example.com/cancel-race"
+
+ def cancelling_fetch():
+ time.sleep(0.2) # allow: unmarked-sleep
+ raise _Cancelled("cancelled")
+
+ def waiter_fetch():
+ return {
+ "content": "waiter-recovered",
+ "title": "T",
+ "url": url,
+ }
+
+ results: dict[str, object] = {}
+
+ def run_fetcher():
+ with pytest.raises(_Cancelled):
+ cache.get_or_fetch(url, cancelling_fetch, wait_timeout=5.0)
+
+ def run_waiter():
+ # Starts while the fetcher holds the slot; must not hang on
+ # the dead event after cancellation.
+ time.sleep(0.05) # allow: unmarked-sleep
+ results["waiter"] = cache.get_or_fetch(
+ url, waiter_fetch, wait_timeout=5.0
+ )
+
+ fetcher_thread = threading.Thread(target=run_fetcher)
+ waiter_thread = threading.Thread(target=run_waiter)
+ fetcher_thread.start()
+ waiter_thread.start()
+ fetcher_thread.join(timeout=10)
+ waiter_thread.join(timeout=10)
+ assert not fetcher_thread.is_alive()
+ assert not waiter_thread.is_alive()
+ assert results.get("waiter") is not None
+ assert results["waiter"]["content"] == "waiter-recovered"
+
+ @pytest.mark.slow
+ def test_concurrent_fetchers_coalesce_to_one(self):
+ cache = ResearchContentCache()
+ calls = {"n": 0}
+
+ def slow_fetch():
+ import time
+
+ calls["n"] += 1
+ time.sleep(0.2) # allow: unmarked-sleep
+ return {
+ "content": "hello",
+ "title": "T",
+ "url": "https://example.com/c",
+ }
+
+ results: list = []
+ threads = [
+ threading.Thread(
+ target=lambda: results.append(
+ cache.get_or_fetch("https://example.com/c", slow_fetch)
+ )
+ )
+ for _ in range(8)
+ ]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert calls["n"] == 1
+ assert len(results) == 8
+ assert all(r is not None and r["content"] == "hello" for r in results)
+
+
+class TestRegistry:
+ def test_bind_get_unbind(self):
+ cache = ResearchContentCache()
+ bind_cache_to_research("rid-1", cache)
+ try:
+ assert get_cache_for_research("rid-1") is cache
+ finally:
+ unbind_cache_from_research("rid-1")
+ assert get_cache_for_research("rid-1") is None
+
+ def test_bind_ignores_empty(self):
+ cache = ResearchContentCache()
+ bind_cache_to_research("", cache)
+ bind_cache_to_research(None, cache) # type: ignore[arg-type]
+ assert get_cache_for_research("") is None
+
+ def test_current_cache_via_search_context(self, fresh_context):
+ cache = ResearchContentCache()
+ bind_cache_to_research("rid-ctx", cache)
+ try:
+ set_search_context({"research_id": "rid-ctx"})
+ assert get_current_cache() is cache
+ finally:
+ clear_search_context()
+ unbind_cache_from_research("rid-ctx")
+
+ def test_no_context_means_no_cache(self, fresh_context):
+ assert get_current_cache() is None
+
+ def test_resolve_prefers_explicit(self, bound_cache):
+ _, bound = bound_cache
+ other = ResearchContentCache()
+ assert resolve_cache(other) is other
+ assert resolve_cache(None) is bound
+
+ def test_worker_thread_with_captured_context_sees_same_cache(
+ self, fresh_context
+ ):
+ cache = ResearchContentCache()
+ bind_cache_to_research("rid-thread", cache)
+ set_search_context({"research_id": "rid-thread"})
+ try:
+ captured = get_search_context()
+ seen: dict = {}
+
+ def run():
+ with search_context(captured):
+ seen["cache"] = get_current_cache()
+
+ thread = threading.Thread(target=run)
+ thread.start()
+ thread.join()
+ assert seen.get("cache") is cache
+ finally:
+ clear_search_context()
+ unbind_cache_from_research("rid-thread")
+
+ def test_memory_bounds_evict_oldest(self):
+ cache = ResearchContentCache(max_entries=3, max_bytes=10**9)
+ for i in range(5):
+ cache.put(f"https://example.com/p{i}", f"body-{i}")
+ assert len(cache) == 3
+ stats = cache.stats()
+ assert stats["evictions"] == 2
+ # Oldest evicted, newest retained.
+ assert cache.get("https://example.com/p0") is None
+ assert cache.get("https://example.com/p4") is not None
+
+ def test_memory_bounds_byte_cap(self):
+ cache = ResearchContentCache(max_entries=1000, max_bytes=100)
+ cache.put("https://example.com/a", "x" * 60)
+ cache.put("https://example.com/b", "y" * 60)
+ # 120 bytes > 100 cap with 2 entries: oldest evicted, newest kept.
+ assert len(cache) == 1
+ assert cache.get("https://example.com/a") is None
+ assert cache.get("https://example.com/b") is not None
+ assert cache.stats()["total_bytes"] == 60
+
+ def test_get_or_fetch_wakes_waiters_after_put(self):
+ """Waiters must see the entry (not re-fetch) — put before set."""
+ import time
+
+ cache = ResearchContentCache()
+ calls: list[str] = []
+
+ def slow_fetcher():
+ calls.append("fetcher")
+ time.sleep(0.3) # allow: unmarked-sleep
+ return {
+ "content": "hello",
+ "title": "T",
+ "url": "https://example.com/c",
+ }
+
+ def waiter_fetch():
+ # Must never run: the waiter should observe the cached entry.
+ calls.append("waiter-retry")
+ return {
+ "content": "hello",
+ "title": "T",
+ "url": "https://example.com/c",
+ }
+
+ results: dict[str, object] = {}
+
+ def run_waiter():
+ # Start slightly after the fetcher holds the in-flight slot.
+ time.sleep(0.05) # allow: unmarked-sleep
+ results["waiter"] = cache.get_or_fetch(
+ "https://example.com/c", waiter_fetch
+ )
+
+ fetcher_thread = threading.Thread(
+ target=lambda: results.__setitem__(
+ "fetcher",
+ cache.get_or_fetch("https://example.com/c", slow_fetcher),
+ )
+ )
+ waiter_thread = threading.Thread(target=run_waiter)
+ fetcher_thread.start()
+ waiter_thread.start()
+ fetcher_thread.join()
+ waiter_thread.join()
+ assert calls == ["fetcher"]
+ assert results["fetcher"] is not None
+ assert results["waiter"] is not None
+
+
+def _mock_downloader(content: bytes, title: str = "PT"):
+ downloader = MagicMock()
+ downloader.download_with_result.return_value = MagicMock(
+ is_success=True, content=content, skip_reason=None
+ )
+ downloader.get_metadata.return_value = {"title": title}
+ return downloader
+
+
+class TestContentFetcherCache:
+ def test_second_fetch_served_without_downloader(self):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher(content_cache=cache)
+ downloader = _mock_downloader(b"full page text here")
+ fetcher._get_downloader = MagicMock(return_value=downloader)
+ first = fetcher.fetch("https://example.com/page", max_length=10)
+ assert first["status"] == "success"
+ assert "[... content truncated ...]" in first["content"]
+ assert downloader.download_with_result.call_count == 1
+ second = fetcher.fetch(
+ "https://example.com/page", max_length=100000
+ )
+ assert downloader.download_with_result.call_count == 1
+ assert second["content"] == "full page text here"
+
+ def test_cache_holds_fullest_version(self):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher(content_cache=cache)
+ fetcher._get_downloader = MagicMock(
+ return_value=_mock_downloader(b"full page text here")
+ )
+ fetcher.fetch("https://example.com/page", max_length=10)
+ assert (
+ cache.get("https://example.com/page")["content"]
+ == "full page text here"
+ )
+
+ def test_registry_fallback_without_explicit_cache(self, bound_cache):
+ _, bound = bound_cache
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ bound.put("https://example.com/reg", "registry text", title="RT")
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher()
+ downloader = MagicMock()
+ fetcher._get_downloader = MagicMock(return_value=downloader)
+ result = fetcher.fetch("https://example.com/reg")
+ assert result["status"] == "success"
+ assert result["content"] == "registry text"
+ assert downloader.download_with_result.call_count == 0
+
+ def test_errors_are_not_cached(self):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher(content_cache=cache)
+ failing = MagicMock()
+ failing.download_with_result.return_value = MagicMock(
+ is_success=False, content=None, skip_reason="boom"
+ )
+ fetcher._get_downloader = MagicMock(return_value=failing)
+ result = fetcher.fetch("https://example.com/err")
+ assert result["status"] == "error"
+ assert len(cache) == 0
+
+ def test_fetcher_keeps_trailing_slash_variants_apart(self):
+ """PR #6759: the fetcher must not serve ``/article/`` from the
+ ``/article`` entry — each variant downloads and caches separately."""
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher(content_cache=cache)
+ downloader = MagicMock()
+ calls: list[str] = []
+
+ def _download(url, content_type):
+ calls.append(url)
+ body = (
+ b"slash body text"
+ if url.endswith("/article/")
+ else b"noslash body text"
+ )
+ return MagicMock(
+ is_success=True, content=body, skip_reason=None
+ )
+
+ downloader.download_with_result.side_effect = _download
+ downloader.get_metadata.return_value = {"title": "T"}
+ fetcher._get_downloader = MagicMock(return_value=downloader)
+ first = fetcher.fetch("https://example.com/article")
+ second = fetcher.fetch("https://example.com/article/")
+ assert first["status"] == "success"
+ assert second["status"] == "success"
+ assert first["content"] == "noslash body text"
+ assert second["content"] == "slash body text"
+ # Both variants reached the downloader (no cross-serving).
+ assert calls == [
+ "https://example.com/article",
+ "https://example.com/article/",
+ ]
+
+
+class TestTrailingSlashContentCorrectness:
+ """PR #6759 end-to-end: distinct web resources stay distinct in the
+ shared cache through the real download/extraction code."""
+
+ @staticmethod
+ def _page_bytes(marker: str) -> bytes:
+ paragraph = "Lorem ipsum dolor sit amet. " * 60
+ return (
+ f"<html><head><title>T</title></head><body><article>"
+ f"<h1>{marker}</h1><p>{paragraph} {marker}</p>"
+ f"<p>{paragraph}</p></article></body></html>"
+ ).encode()
+
+ def test_pipeline_real_http_slash_variants_distinct(self):
+ """Different bodies at ``/article`` vs ``/article/``: both correct,
+ and the second URL is actually requested (no cache cross-serving)."""
+ import http.server
+
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ hits: dict[str, int] = {}
+
+ class _Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self): # noqa: N802
+ hits[self.path] = hits.get(self.path, 0) + 1
+ marker = (
+ "ARTICLE-SLASH-BODY"
+ if self.path == "/article/"
+ else "ARTICLE-NOSLASH-BODY"
+ )
+ body = TestTrailingSlashContentCorrectness._page_bytes(marker)
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ port = server.server_address[1]
+ cache = ResearchContentCache()
+ first = pl.fetch_and_extract(
+ f"http://127.0.0.1:{port}/article",
+ content_cache=cache,
+ allow_private_ips=True,
+ )
+ second = pl.fetch_and_extract(
+ f"http://127.0.0.1:{port}/article/",
+ content_cache=cache,
+ allow_private_ips=True,
+ )
+ assert first is not None and "NOSLASH" in first
+ assert second is not None and "SLASH-BODY" in second
+ assert "NOSLASH" not in second
+ # The second URL was really fetched — a collapsed key would
+ # have served it from the first entry with zero hits.
+ assert hits.get("/article") == 1
+ assert hits.get("/article/") == 1
+ finally:
+ server.shutdown()
+
+
+class TestPipelineCache:
+ def test_batch_second_call_hits_cache(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content=None, fallback_allowed=True
+ ),
+ ):
+ fake = MagicMock()
+ fake.download.return_value = b"batch hello"
+ with patch(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ return_value=fake,
+ ):
+ first = pl.batch_fetch_and_extract(
+ ["https://example.com/b1"], content_cache=cache
+ )
+ assert first["https://example.com/b1"] == "batch hello"
+ fake.download.reset_mock()
+ second = pl.batch_fetch_and_extract(
+ ["https://example.com/b1"], content_cache=cache
+ )
+ assert second["https://example.com/b1"] == "batch hello"
+ assert fake.download.call_count == 0
+
+ def test_fetch_and_extract_caches(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content=None, fallback_allowed=True
+ ),
+ ):
+ fake = MagicMock()
+ fake.download.return_value = b"single hello"
+ with patch(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ return_value=fake,
+ ):
+ assert (
+ pl.fetch_and_extract(
+ "https://example.com/s1", content_cache=cache
+ )
+ == "single hello"
+ )
+ fake.download.reset_mock()
+ assert (
+ pl.fetch_and_extract(
+ "https://example.com/s1", content_cache=cache
+ )
+ == "single hello"
+ )
+ assert fake.download.call_count == 0
+
+ def test_specialized_result_cached(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content="arxiv text", fallback_allowed=True
+ ),
+ ):
+ out = pl.batch_fetch_and_extract(
+ ["https://arxiv.org/abs/1234.5678"], content_cache=cache
+ )
+ assert out["https://arxiv.org/abs/1234.5678"] == "arxiv text"
+ assert (
+ cache.get("https://arxiv.org/abs/1234.5678")["content"]
+ == "arxiv text"
+ )
+
+
+def _fetch_cm(content="shared body", title="T", url="https://example.com/s"):
+ fetcher = MagicMock()
+ fetcher.fetch.return_value = {
+ "status": "success",
+ "title": title,
+ "content": content,
+ "url": url,
+ }
+ cm = MagicMock()
+ cm.__enter__.return_value = fetcher
+ cm.__exit__.return_value = False
+ return cm
+
+
+class TestFetchToolSharing:
+ def test_lead_and_subagent_share_one_cache(self):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
+ )
+
+ shared = ResearchContentCache()
+ collector = SearchResultsCollector([])
+ lead = build_fetch_tool(
+ "full",
+ collector,
+ settings_snapshot={},
+ max_fetches=0,
+ subagent_id="lead",
+ content_cache=shared,
+ )
+ sub = build_fetch_tool(
+ "full",
+ collector,
+ settings_snapshot={},
+ max_fetches=0,
+ subagent_id="subagent",
+ content_cache=shared,
+ )
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher",
+ return_value=_fetch_cm(),
+ ):
+ first = lead.invoke({"url": "https://example.com/s"})
+ assert "shared body" in first
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher._get_downloader"
+ ) as downloader:
+ second = sub.invoke({"url": "https://example.com/s"})
+ downloader.assert_not_called()
+ assert "shared body" in second
+ assert shared.stats()["entries"] >= 1
+
+ def test_summary_mode_reuses_raw_but_reruns_extractor(self):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
+ )
+
+ model = MagicMock()
+ message = MagicMock()
+ message.content = "quote1"
+ model.invoke.return_value = message
+ collector = SearchResultsCollector([])
+ shared = ResearchContentCache()
+ first_tool = build_fetch_tool(
+ "summary_focus",
+ collector,
+ model=model,
+ settings_snapshot={},
+ max_fetches=0,
+ subagent_id="lead",
+ content_cache=shared,
+ )
+ second_tool = build_fetch_tool(
+ "summary_focus",
+ collector,
+ model=model,
+ settings_snapshot={},
+ max_fetches=0,
+ subagent_id="subagent",
+ content_cache=shared,
+ )
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher",
+ return_value=_fetch_cm(content="long page about cats and dogs"),
+ ):
+ first_tool.invoke({"url": "https://example.com/m", "focus": "cats"})
+ assert model.invoke.call_count == 1
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher._get_downloader"
+ ) as downloader:
+ second_tool.invoke(
+ {"url": "https://example.com/m", "focus": "dogs"}
+ )
+ downloader.assert_not_called()
+ assert model.invoke.call_count == 2
+
+ def test_summary_prompt_built_from_cached_raw(self, bound_cache):
+ _, bound = bound_cache
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
+ )
+
+ bound.put("https://example.com/p", "cached page text", title="CT")
+ model = MagicMock()
+ message = MagicMock()
+ message.content = "quote"
+ model.invoke.return_value = message
+ tool = build_fetch_tool(
+ "summary_focus",
+ SearchResultsCollector([]),
+ model=model,
+ settings_snapshot={},
+ max_fetches=0,
+ )
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher._get_downloader"
+ ) as downloader:
+ tool.invoke({"url": "https://example.com/p", "focus": "f"})
+ downloader.assert_not_called()
+ prompt = model.invoke.call_args[0][0]
+ assert "cached page text" in prompt
+
+
+class TestEngineCache:
+ def _fake_engine_class(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class FakeEngine(BaseSearchEngine):
+ def __init__(self, **kwargs):
+ super().__init__(search_snippets_only=False, **kwargs)
+ self.calls = 0
+
+ def _get_previews(self, query):
+ return [
+ {
+ "title": "T",
+ "link": "https://example.com/e1",
+ "snippet": "s",
+ }
+ ]
+
+ def _get_full_content(self, items):
+ self.calls += 1
+ for item in items:
+ item["full_content"] = "engine full text"
+ item["full_content_is_complete"] = True
+ return items
+
+ return FakeEngine
+
+ def test_second_run_served_from_cache(self):
+ engine = self._fake_engine_class()(content_cache=ResearchContentCache())
+ first = engine.run("q")
+ assert engine.calls == 1
+ assert first[0]["full_content"] == "engine full text"
+ second = engine.run("q")
+ assert engine.calls == 1
+ assert second[0]["full_content"] == "engine full text"
+
+ def test_without_cache_fetches_every_time(self):
+ engine = self._fake_engine_class()()
+ engine.run("q")
+ engine.run("q")
+ assert engine.calls == 2
+
+ def test_cross_consumer_pipeline_then_engine(self, bound_cache):
+ _, bound = bound_cache
+ bound.put("https://example.com/e1", "pipeline text", title="PT")
+ engine = self._fake_engine_class()()
+ results = engine.run("anything")
+ assert results[0]["full_content"] == "pipeline text"
+ assert engine.calls == 0
+
+ def test_factory_threads_cache_into_engine(self):
+ cache = ResearchContentCache()
+ from local_deep_research.web_search_engines import (
+ search_engine_factory as factory,
+ )
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ created: dict = {}
+
+ class StubEngine(BaseSearchEngine):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ created.update(kwargs)
+
+ def _get_previews(self, query):
+ return []
+
+ fake_config = {
+ "whatever": {
+ "module_path": "fake.module",
+ "class_name": "StubEngine",
+ "default_params": {},
+ }
+ }
+ with (
+ patch.object(factory, "search_config", return_value=fake_config),
+ patch.object(
+ factory, "get_safe_module_class", return_value=StubEngine
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=MagicMock(allowed=True),
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.context_from_snapshot",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.resolve_run_primary_engine",
+ return_value="whatever",
+ ),
+ ):
+ engine = factory.create_search_engine(
+ "whatever",
+ settings_snapshot={"search.tool": "whatever"},
+ content_cache=cache,
+ )
+ assert engine is not None
+ assert engine.content_cache is cache
+
+
+class TestFullSearchCache:
+ def test_run_threads_cache_into_batch_funnel(self):
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ cache = ResearchContentCache()
+ web_search = MagicMock()
+ web_search.invoke.return_value = [
+ {"title": "T", "link": "https://example.com/f1"}
+ ]
+ full = FullSearchResults(
+ llm=None, web_search=web_search, content_cache=cache
+ )
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ return_value={"https://example.com/f1": "page one"},
+ ) as batch:
+ first = full.run("q")
+ assert first[0]["full_content"] == "page one"
+ assert batch.call_count == 1
+ # The shared cache instance must reach the funnel so repeat
+ # URLs (quick phase vs subagents) hit one cache.
+ assert batch.call_args.kwargs.get("content_cache") is cache
+
+ def test_funnel_serves_repeat_urls_from_cache(self):
+ # The funnel-level cache (pinned in TestPipelineCache) is what
+ # serves FullSearchResults repeats end to end; here we prove the
+ # wiring with the real funnel and a mocked downloader.
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+ from local_deep_research.web_search_engines.engines.full_search import (
+ FullSearchResults,
+ )
+
+ cache = ResearchContentCache()
+ web_search = MagicMock()
+ web_search.invoke.return_value = [
+ {"title": "T", "link": "https://example.com/f2"}
+ ]
+ full = FullSearchResults(
+ llm=None, web_search=web_search, content_cache=cache
+ )
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content=None, fallback_allowed=True
+ ),
+ ):
+ fake = MagicMock()
+ fake.download.return_value = b"page two"
+ with patch(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ return_value=fake,
+ ):
+ first = full.run("q")
+ assert first[0]["full_content"] == "page two"
+ fake.download.reset_mock()
+ second = full.run("q")
+ assert second[0]["full_content"] == "page two"
+ assert fake.download.call_count == 0
+
+
+class TestLibraryResolverCache:
+ def test_prepopulated_entry_skips_db(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(
+ "/library/document/12345678123456781234567812345678",
+ "cached doc text",
+ title="DocT",
+ url_out="/library/document/12345678123456781234567812345678",
+ )
+ result = lr.resolve_library_document(
+ "/library/document/12345678123456781234567812345678",
+ username="someone",
+ content_cache=cache,
+ )
+ assert result is not None
+ assert result["content"] == "cached doc text"
+ assert result["title"] == "DocT"
+
+ def test_chunk_and_document_keys_are_distinct(self):
+ cache = ResearchContentCache()
+ cache.put(
+ "/library/document/12345678123456781234567812345678#chunk-3",
+ "chunk3 text",
+ title="D",
+ url_out="/library/document/12345678123456781234567812345678#chunk-3",
+ )
+ assert (
+ cache.get("/library/document/12345678123456781234567812345678")
+ is None
+ )
+ assert (
+ cache.get(
+ "/library/document/12345678123456781234567812345678#chunk-3"
+ )["content"]
+ == "chunk3 text"
+ )
+
+ def test_make_resolver_forwards_cache(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(
+ "/library/document/12345678123456781234567812345678",
+ "cached",
+ title="T",
+ url_out="/library/document/12345678123456781234567812345678",
+ )
+ resolver = lr.make_library_resolver("someone", content_cache=cache)
+ assert (
+ resolver("/library/document/12345678123456781234567812345678")[
+ "content"
+ ]
+ == "cached"
+ )
+
+
+class TestSingleSharedCachePerResearch:
+ def test_system_strategy_and_engine_share_one_instance(self):
+ from unittest.mock import Mock
+
+ from local_deep_research.search_system import AdvancedSearchSystem
+ from local_deep_research.utilities.research_content_cache import (
+ get_cache_for_research,
+ )
+
+ rid = f"sys-{uuid.uuid4().hex}"
+ system = AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ strategy_name="source-based",
+ settings_snapshot={},
+ research_id=rid,
+ )
+ try:
+ assert system.content_cache is not None
+ assert system.strategy.content_cache is system.content_cache
+ assert system.search.content_cache is system.content_cache
+ assert get_cache_for_research(rid) is system.content_cache
+ finally:
+ system.close()
+ assert get_cache_for_research(rid) is None
+
+ def test_strategy_creates_cache_when_standalone(self):
+ from local_deep_research.advanced_search_system.strategies.base_strategy import (
+ BaseSearchStrategy,
+ )
+
+ class Dummy(BaseSearchStrategy):
+ def analyze_topic(self, query):
+ return {}
+
+ first = Dummy()
+ second = Dummy()
+ assert first.content_cache is not None
+ assert second.content_cache is not None
+ assert first.content_cache is not second.content_cache
+ # Explicit sharing works when requested.
+ shared = ResearchContentCache()
+ assert Dummy(content_cache=shared).content_cache is shared
+
+
+class TestProductionCoalescing:
+ """Production-shaped contract: concurrent real fetches collapse to one."""
+
+ def test_concurrent_content_fetcher_calls_fetch_once(self):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher(content_cache=cache)
+ downloader = _mock_downloader(b"shared page body")
+ fetcher._get_downloader = MagicMock(return_value=downloader)
+ results: list = []
+
+ def run():
+ results.append(fetcher.fetch("https://example.com/coalesce"))
+
+ threads = [threading.Thread(target=run) for _ in range(8)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert len(results) == 8
+ assert all(
+ r["status"] == "success" and r["content"] == "shared page body"
+ for r in results
+ )
+ assert downloader.download_with_result.call_count == 1
+
+ def test_truncation_marker_never_overwrites_full(self):
+ """10_001-char page + 10_000 limit: full must survive tool put."""
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ cache = ResearchContentCache()
+ full = "x" * 10_001
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher(content_cache=cache)
+ fetcher._get_downloader = MagicMock(
+ return_value=_mock_downloader(full.encode())
+ )
+ first = fetcher.fetch("https://example.com/long", max_length=10_000)
+ assert first["status"] == "success"
+ assert "[... content truncated ...]" in first["content"]
+ assert (
+ len(cache.get("https://example.com/long")["content"]) == 10_001
+ )
+ # Simulate the tool layer storing its truncated display output:
+ # it must be ignored (contains the marker).
+ truncated_display = first["content"]
+ assert len(truncated_display) > 10_001
+ # Tool-layer guard: skip puts containing the marker.
+ assert "[... content truncated ...]" in truncated_display
+ second = fetcher.fetch(
+ "https://example.com/long", max_length=100_000
+ )
+ assert second["content"] == full
+
+ def test_failure_then_retry_refetches(self):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ fetcher = ContentFetcher(content_cache=cache)
+ failing = MagicMock()
+ failing.download_with_result.return_value = MagicMock(
+ is_success=False, content=None, skip_reason="boom"
+ )
+ fetcher._get_downloader = MagicMock(return_value=failing)
+ assert (
+ fetcher.fetch("https://example.com/flaky")["status"] == "error"
+ )
+ assert len(cache) == 0
+ fetcher._get_downloader = MagicMock(
+ return_value=_mock_downloader(b"recovered")
+ )
+ retry = fetcher.fetch("https://example.com/flaky")
+ assert retry["status"] == "success"
+ assert retry["content"] == "recovered"
+ assert (
+ cache.get("https://example.com/flaky")["content"] == "recovered"
+ )
+
+
+class TestLibraryResolverIsolation:
+ def test_web_url_cache_hit_is_not_library_document(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+
+ cache = ResearchContentCache()
+ cache.put("https://example.com/page", "web body", title="WT")
+ assert (
+ lr.resolve_library_document(
+ "https://example.com/page",
+ username="someone",
+ content_cache=cache,
+ )
+ is None
+ )
+
+ def test_missing_chunk_not_cached_as_source_text(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+ from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ )
+
+ cache = ResearchContentCache()
+ doc_id = "12345678123456781234567812345678"
+ chunk_url = f"/library/document/{doc_id}/chunks#chunk-5"
+
+ doc = MagicMock()
+ doc.id = doc_id
+ doc.title = "Test Doc"
+ doc.text_content = "full doc"
+
+ chunk = MagicMock()
+ chunk.id = 1
+ chunk.chunk_index = 5
+ chunk.chunk_text = "real chunk text"
+ chunk.collection_name = "default"
+
+ chunk_exists = False
+ session = MagicMock()
+
+ def query_mock(model):
+ q = MagicMock()
+ if model == Document:
+ q.filter_by.return_value.first.return_value = doc
+ elif model == DocumentChunk:
+ q.filter.return_value.order_by.return_value.first.return_value = (
+ chunk if chunk_exists else None
+ )
+ return q
+
+ session.query.side_effect = query_mock
+ session_cm = MagicMock()
+ session_cm.__enter__.return_value = session
+ session_cm.__exit__.return_value = False
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=session_cm,
+ ):
+ # Attempt 1: missing chunk returns not found, NOT cached
+ res1 = lr.resolve_library_document(
+ chunk_url, "someone", content_cache=cache
+ )
+ assert res1 is not None
+ assert "Chunk 5 not found" in res1["content"]
+ assert cache.get(chunk_url) is None
+
+ # Attempt 2: chunk becomes available -> retry hits DB and returns real text
+ chunk_exists = True
+ session.query.reset_mock()
+ res2 = lr.resolve_library_document(
+ chunk_url, "someone", content_cache=cache
+ )
+ assert res2 is not None
+ assert res2["content"] == "real chunk text"
+ assert session.query.call_count > 0
+ assert cache.get(chunk_url) is not None
+
+ # Control: repeat returns cached text without DB query
+ session.query.reset_mock()
+ res3 = lr.resolve_library_document(
+ chunk_url, "someone", content_cache=cache
+ )
+ assert res3 is not None
+ assert res3["content"] == "real chunk text"
+ assert session.query.call_count == 0
+
+ def test_quick_phase_to_subsection_shares_via_registry(self, bound_cache):
+ """Quick phase puts via explicit cache; subsection reads via registry."""
+ rid, quick_cache = bound_cache
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ quick_cache.put(
+ "https://example.com/shared", "quick phase body", title="QT"
+ )
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ):
+ # Subsection fetcher has no explicit cache: resolves via
+ # thread-local research context bound above.
+ fetcher = ContentFetcher()
+ downloader = MagicMock()
+ fetcher._get_downloader = MagicMock(return_value=downloader)
+ result = fetcher.fetch("https://example.com/shared")
+ assert result["status"] == "success"
+ assert result["content"] == "quick phase body"
+ assert downloader.download_with_result.call_count == 0
+
+
+class TestChunkCollectionScoping:
+ """Same (document, chunk) in two collections must not share an entry."""
+
+ _DOC = "12345678123456781234567812345678"
+
+ def _chunk_url(self):
+ return f"/library/document/{self._DOC}/chunks#chunk-3"
+
+ def test_keys_differ_per_collection(self):
+ url = self._chunk_url()
+ assert content_cache_key(url, "coll-A") != content_cache_key(
+ url, "coll-B"
+ )
+
+ def test_collection_spellings_collapse(self):
+ url = self._chunk_url()
+ assert content_cache_key(url, "coll-B") == content_cache_key(
+ url, "collection_coll-B"
+ )
+
+ def test_chunk_spellings_merge_for_same_collection(self):
+ base = f"/library/document/{self._DOC}#chunk-3"
+ suffixed = f"/library/document/{self._DOC}/chunks#chunk-3"
+ assert content_cache_key(base, "coll-A") == content_cache_key(
+ suffixed, "coll-A"
+ )
+
+ def test_document_url_ignores_collection(self):
+ doc = f"/library/document/{self._DOC}"
+ assert content_cache_key(doc) == content_cache_key(doc, "coll-A")
+ assert content_cache_key(doc, "coll-A") == content_cache_key(
+ doc, "coll-B"
+ )
+
+ def _collection_engine(self, cache, calls):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class CollEngine(BaseSearchEngine):
+ def __init__(self, **kwargs):
+ super().__init__(search_snippets_only=False, **kwargs)
+
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ for item in items:
+ cid = (item.get("metadata") or {}).get("collection_id")
+ calls[cid] = calls.get(cid, 0) + 1
+ item["full_content"] = f"text-for-{cid}"
+ item["full_content_is_complete"] = True
+ return items
+
+ return CollEngine(content_cache=cache)
+
+ def test_two_collections_same_chunk_do_not_collide(self):
+ """A fills, B fetches its own text, B repeats from cache."""
+ cache = ResearchContentCache()
+ calls: dict = {}
+ engine = self._collection_engine(cache, calls)
+ url = self._chunk_url()
+
+ items_a = [
+ {
+ "link": url,
+ "title": "T",
+ "metadata": {"collection_id": "coll-A", "chunk_index": 3},
+ }
+ ]
+ result_a = engine._get_full_content_cached(items_a)
+ assert result_a[0]["full_content"] == "text-for-coll-A"
+ assert calls == {"coll-A": 1}
+
+ items_b = [
+ {
+ "link": url,
+ "title": "T",
+ "metadata": {"collection_id": "coll-B", "chunk_index": 3},
+ }
+ ]
+ result_b = engine._get_full_content_cached(items_b)
+ # Must be B's text (not A's) and B's DB lookup must have run.
+ assert result_b[0]["full_content"] == "text-for-coll-B"
+ assert calls == {"coll-A": 1, "coll-B": 1}
+
+ # Repeat B: served from B's namespaced entry, no new lookup.
+ items_b2 = [
+ {
+ "link": url,
+ "title": "T",
+ "metadata": {"collection_id": "coll-B", "chunk_index": 3},
+ }
+ ]
+ result_b2 = engine._get_full_content_cached(items_b2)
+ assert result_b2[0]["full_content"] == "text-for-coll-B"
+ assert calls == {"coll-A": 1, "coll-B": 1}
+
+ # Repeat A: still A's text.
+ items_a2 = [
+ {
+ "link": url,
+ "title": "T",
+ "metadata": {"collection_id": "coll-A", "chunk_index": 3},
+ }
+ ]
+ result_a2 = engine._get_full_content_cached(items_a2)
+ assert result_a2[0]["full_content"] == "text-for-coll-A"
+ assert calls == {"coll-A": 1, "coll-B": 1}
+
+ def test_chunk_without_collection_bypasses_shared_entry(self):
+ """No collection → fresh lookup every time, never poisons cache."""
+ cache = ResearchContentCache()
+ calls: dict = {}
+ engine = self._collection_engine(cache, calls)
+ url = self._chunk_url()
+
+ # Seed a scoped entry first.
+ scoped = [
+ {
+ "link": url,
+ "title": "T",
+ "metadata": {"collection_id": "coll-A", "chunk_index": 3},
+ }
+ ]
+ assert (
+ engine._get_full_content_cached(scoped)[0]["full_content"]
+ == "text-for-coll-A"
+ )
+ assert calls == {"coll-A": 1}
+
+ # Unscoped chunk must not hit the scoped entry.
+ unscoped = [{"link": url, "title": "T", "metadata": {}}]
+ first = engine._get_full_content_cached(unscoped)
+ assert first[0]["full_content"] == "text-for-None"
+ second = engine._get_full_content_cached(
+ [{"link": url, "title": "T", "metadata": {}}]
+ )
+ # Bypassed both times: two lookups, never cached.
+ assert calls.get(None) == 2
+ assert second[0]["full_content"] == "text-for-None"
+ # Scoped entry still intact.
+ assert (
+ cache.get(url, collection_id="coll-A")["content"]
+ == "text-for-coll-A"
+ )
+
+
+class TestGrantAwareCache:
+ """Grant x cache: private entries must not leak to non-granted callers."""
+
+ _LOOPBACK = "http://127.0.0.1:9/private-page"
+
+ def test_batch_skips_private_hit_without_grant(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "private secret", title="S")
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content=None, fallback_allowed=True
+ ),
+ ):
+ fake = MagicMock()
+ fake.download.return_value = None
+ with patch(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ return_value=fake,
+ ):
+ out = pl.batch_fetch_and_extract(
+ [self._LOOPBACK],
+ content_cache=cache,
+ allow_private_ips=False,
+ block_link_local=True,
+ )
+ assert out[self._LOOPBACK] is None
+ # Cache bypassed: the downloader gate was consulted.
+ assert fake.download.call_count >= 1
+
+ def test_batch_serves_private_hit_with_grant(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "private secret", title="S")
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content=None, fallback_allowed=True
+ ),
+ ):
+ fake = MagicMock()
+ fake.download.return_value = b"should not be used"
+ with patch(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ return_value=fake,
+ ):
+ out = pl.batch_fetch_and_extract(
+ [self._LOOPBACK],
+ content_cache=cache,
+ allow_private_ips=True,
+ block_link_local=True,
+ )
+ assert out[self._LOOPBACK] == "private secret"
+ assert fake.download.call_count == 0
+
+ def test_fetch_and_extract_singular_skips_private_without_grant(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "private secret", title="S")
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content=None, fallback_allowed=True
+ ),
+ ):
+ fake = MagicMock()
+ fake.download.return_value = None
+ with patch(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ return_value=fake,
+ ):
+ assert (
+ pl.fetch_and_extract(
+ self._LOOPBACK,
+ content_cache=cache,
+ allow_private_ips=False,
+ block_link_local=True,
+ )
+ is None
+ )
+ assert fake.download.call_count >= 1
+
+ def test_engine_fill_skips_private_without_grant(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def __init__(self, **kwargs):
+ super().__init__(search_snippets_only=False, **kwargs)
+ self.calls = 0
+
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ self.calls += 1
+ for item in items:
+ item["full_content"] = "fresh"
+ return items
+
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "cached private", title="T")
+ plain = StubEngine(content_cache=cache)
+ assert plain.allow_private_result_fetch is False
+ items = [{"link": self._LOOPBACK, "title": "T"}]
+ cached, missing = plain._fill_full_content_from_cache(items)
+ assert cached == [] and len(missing) == 1
+ assert items[0].get("full_content") is None
+
+ granted = StubEngine(content_cache=cache)
+ granted.allow_private_result_fetch = True
+ items2 = [{"link": self._LOOPBACK, "title": "T"}]
+ cached2, _ = granted._fill_full_content_from_cache(items2)
+ assert len(cached2) == 1
+ assert items2[0]["full_content"] == "cached private"
+
+ def test_engine_fill_still_serves_public_and_library(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ cache = ResearchContentCache()
+ cache.put("https://example.com/pub", "public body", title="T")
+ doc = "/library/document/12345678123456781234567812345678"
+ cache.put(doc, "doc text", title="D", url_out=doc)
+ engine = StubEngine(content_cache=cache)
+ items = [
+ {"link": "https://example.com/pub", "title": "T"},
+ {"link": doc, "title": "D"},
+ ]
+ cached, missing = engine._fill_full_content_from_cache(items)
+ assert len(cached) == 2 and missing == []
+ assert items[0]["full_content"] == "public body"
+ assert items[1]["full_content"] == "doc text"
+
+
+class TestFetchToolGrantGate:
+ """Item 1: fetch-tool fast path must apply the SSRF grant gate."""
+
+ _LOOPBACK = "http://127.0.0.1:9/private-page"
+
+ def _unprotected_ctx(self):
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ return EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+
+ def _private_ctx(self):
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ return EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+
+ def test_skips_private_hit_under_unprotected(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _fetch_raw_content,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "private secret body", title="S")
+ ctx = self._unprotected_ctx()
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher"
+ ) as mock_cls:
+ inst = mock_cls.return_value.__enter__.return_value
+ inst.fetch.return_value = {
+ "status": "error",
+ "error": "URL failed security validation",
+ "url": self._LOOPBACK,
+ }
+ result, _, _, _ = _fetch_raw_content(
+ self._LOOPBACK,
+ None,
+ MagicMock(),
+ ctx,
+ None,
+ "full",
+ max_fetches=None,
+ content_cache=cache,
+ )
+ # Cache must NOT be served: the fetcher gate is consulted.
+ assert inst.fetch.call_count == 1
+ assert result is not None
+ assert result.get("status") == "error"
+
+ def test_serves_private_hit_with_private_grant(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _fetch_raw_content,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "private secret body", title="S")
+ ctx = self._private_ctx()
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher._get_downloader"
+ ) as downloader:
+ result, _, _, _ = _fetch_raw_content(
+ self._LOOPBACK,
+ None,
+ MagicMock(),
+ ctx,
+ None,
+ "full",
+ max_fetches=None,
+ content_cache=cache,
+ )
+ downloader.assert_not_called()
+ assert result is not None
+ assert result.get("status") == "success"
+ assert result.get("content") == "private secret body"
+
+ def test_does_not_store_private_without_grant(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _fetch_raw_content,
+ )
+
+ cache = ResearchContentCache()
+ ctx = self._unprotected_ctx()
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher"
+ ) as mock_cls:
+ inst = mock_cls.return_value.__enter__.return_value
+ # Mocked fetcher bypasses its own gate (as in unit tests);
+ # the tool layer must still refuse to persist the entry.
+ inst.fetch.return_value = {
+ "status": "success",
+ "content": "private body",
+ "url": self._LOOPBACK,
+ "title": "S",
+ }
+ result, _, _, _ = _fetch_raw_content(
+ self._LOOPBACK,
+ None,
+ MagicMock(),
+ ctx,
+ None,
+ "full",
+ max_fetches=None,
+ content_cache=cache,
+ )
+ assert result is not None
+ assert result.get("status") == "success"
+ assert cache.get(self._LOOPBACK) is None
+
+
+class TestCacheHitUrlLogging:
+ """#7159: the cache-hit INFO event must not log a raw URL.
+
+ The ``source=cache`` event is new in this branch, so it has to redact at
+ the call site like every other ``[FETCH]`` event in the module. A raw URL
+ there would put credentials, query tokens, private paths and the fragment
+ into normal stderr/container logs (INFO, no debug mode needed).
+
+ Two traps this test deliberately pins:
+
+ * the package disables its loguru namespace at import (until
+ ``config_logger`` runs), so the capture must ``logger.enable(...)``
+ first — without it the sink captures nothing and the non-empty
+ ``source=cache`` assertion fails loudly (the test cannot pass
+ silently);
+ * the fragment is the marker that actually leaked. The global record
+ scrubber already strips userinfo and query values, so a test asserting
+ only those two would pass against the unfixed line.
+ """
+
+ # Loopback + PRIVATE_ONLY so the real grant check admits the hit and the
+ # real cache-hit branch is reached (see TestFetchToolGrantGate).
+ _SECRET_URL = (
+ "http://alice:[email protected]:9/private/FAKE_PATH"
+ "?token=FAKE_TOKEN"
+ "#FAKE_FRAGMENT"
+ )
+ _MARKERS = ("FAKE_PASSWORD", "FAKE_PATH", "FAKE_TOKEN", "FAKE_FRAGMENT")
+
+ def _private_ctx(self):
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ return EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+
+ def test_cache_hit_log_redacts_url_and_still_serves_content(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _fetch_raw_content,
+ )
+ from loguru import logger
+
+ cache = ResearchContentCache()
+ cache.put(self._SECRET_URL, "cached body text", title="S")
+ ctx = self._private_ctx()
+
+ # loguru's namespace is disabled at import time; without re-enabling
+ # it the added sink below captures nothing and the non-empty
+ # cache-hit assertion below fails loudly (no silent pass).
+ logger.enable("local_deep_research")
+ records: list[str] = []
+ sink_id = logger.add(
+ lambda message: records.append(str(message)),
+ level="INFO",
+ )
+ try:
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher._get_downloader"
+ ) as downloader:
+ result, _, _, _ = _fetch_raw_content(
+ self._SECRET_URL,
+ None,
+ MagicMock(),
+ ctx,
+ None,
+ "full",
+ max_fetches=None,
+ content_cache=cache,
+ )
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+
+ # The real cache-hit branch ran (no network fetch) and served content.
+ downloader.assert_not_called()
+ assert result is not None
+ assert result.get("status") == "success"
+ assert result.get("content") == "cached body text"
+
+ # The event was actually captured, and the hit was logged.
+ cache_hit = [
+ r for r in records if "source=cache" in r and "mode=full" in r
+ ]
+ assert cache_hit, f"no cache-hit INFO record captured: {records}"
+ assert len(cache_hit) == 1
+
+ # Control: the markers were present in the URL being logged before the
+ # fix, so this assertion is discriminating rather than incidental.
+ for marker in self._MARKERS:
+ assert marker in self._SECRET_URL
+ assert all(marker not in rec for rec in cache_hit), (
+ f"{marker} leaked into the cache-hit log record: {cache_hit}"
+ )
+
+ # The redacted host is still there, so the record is not just empty.
+ assert "127.0.0.1" in cache_hit[0]
+
+
+class TestPipelineGetOrFetchExceptionRedaction:
+ """Optional note from the 6511e834 APPROVED review: pin pipeline.py:767.
+
+ ``fetch_and_extract`` wraps ``_cache.get_or_fetch`` in try/except and
+ logs ``fetch_and_extract failed for {url}``. The message must use
+ ``redact_url_for_log`` (like the file's other two sites) *and* must not
+ attach the traceback: plain ``logger.exception`` renders frame locals
+ via loguru diagnose, so the ``url`` local (credentials, path, query,
+ fragment) leaks even when the message itself is redacted. Reverting just
+ that hunk still passes the whole suite today, so this test guards it.
+
+ Traps pinned deliberately (mirrors ``TestCacheHitUrlLogging``):
+
+ * ``logger.enable(...)`` first — the package disables its loguru
+ namespace at import, so without it the sink captures nothing and the
+ non-empty failure-event assertion fails loudly (no silent pass);
+ * ``diagnose=True`` + ``backtrace=True`` with ``{exception}`` in the
+ format — the sibling ``test_pipeline_logging_sinks.py`` fixture uses
+ ``diagnose=False``, which hides the frame-locals channel this test
+ exists to pin;
+ * all four marker classes asserted, plus an explicit ``Traceback``
+ absence — a generic (secret-free) ``get_or_fetch`` failure means any
+ marker in the output must come from the ``url`` local/message.
+ """
+
+ _SECRET_URL = (
+ "http://alice:[email protected]:9/private/FAKE_PATH"
+ "?token=FAKE_TOKEN"
+ "#FAKE_FRAGMENT"
+ )
+ _MARKERS = ("FAKE_PASSWORD", "FAKE_PATH", "FAKE_TOKEN", "FAKE_FRAGMENT")
+
+ def test_fetch_and_extract_get_or_fetch_failure_redacted_no_traceback(
+ self,
+ ):
+ from io import StringIO
+
+ from loguru import logger
+
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ for marker in self._MARKERS:
+ assert marker in self._SECRET_URL
+
+ logger.enable("local_deep_research")
+ output = StringIO()
+ sink_id = logger.add(
+ output,
+ level="DEBUG",
+ format="{message}\n{exception}",
+ backtrace=True,
+ diagnose=True,
+ )
+ try:
+ with (
+ patch.object(pl, "_is_cache_hit_allowed", return_value=True),
+ patch.object(
+ cache,
+ "get_or_fetch",
+ side_effect=RuntimeError("boom"),
+ ) as mock_fetch,
+ ):
+ result = pl.fetch_and_extract(
+ self._SECRET_URL,
+ content_cache=cache,
+ )
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+
+ # The failing-cache branch ran and surfaced as a miss.
+ assert result is None
+ assert mock_fetch.call_count == 1
+
+ # The failure event was actually captured (no silent pass).
+ rendered = output.getvalue()
+ lines = [
+ line
+ for line in rendered.splitlines()
+ if "fetch_and_extract failed for" in line
+ ]
+ assert lines, f"no failure event captured: {rendered!r}"
+ assert len(lines) == 1
+
+ # Redacted host retained, so the record is not just empty.
+ assert "127.0.0.1" in lines[0]
+
+ # No raw secret reaches the sink via message, exception text, or
+ # diagnose frame locals; and no traceback is attached at all.
+ for marker in self._MARKERS:
+ assert marker not in rendered, (
+ f"{marker} leaked into pipeline failure log: {rendered!r}"
+ )
+ assert "Traceback" not in rendered
+
+
+class TestLibraryAliasGrantGate:
+ """Item 2: absolute alias must pass the egress check; path-only stays exempt."""
+
+ _DOC = "/library/document/12345678123456781234567812345678"
+ _ALIAS = "https://library.document/12345678123456781234567812345678"
+
+ def test_pipeline_path_exempt_alias_requires_check(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ # Path-only: always allowed, even when the SSRF gate would refuse.
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=False,
+ ):
+ assert pl._is_cache_hit_allowed(self._DOC, False, True) is True
+ # Alias: falls through to the egress check.
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=False,
+ ) as mock_v:
+ assert pl._is_cache_hit_allowed(self._ALIAS, True, True) is False
+ assert mock_v.call_count >= 1
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ):
+ assert pl._is_cache_hit_allowed(self._ALIAS, True, True) is True
+
+ def test_engine_path_exempt_alias_requires_check(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ engine = StubEngine(content_cache=ResearchContentCache())
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=False,
+ ):
+ assert engine._is_cache_url_allowed(self._DOC) is True
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=False,
+ ) as mock_v:
+ assert engine._is_cache_url_allowed(self._ALIAS) is False
+ assert mock_v.call_count >= 1
+
+ def test_pipeline_batch_alias_bypasses_cache(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(self._ALIAS, "alias secret", title="A")
+ with patch.object(
+ pl,
+ "_try_specialized_downloader",
+ return_value=pl._SpecializedResult(
+ content=None, fallback_allowed=True
+ ),
+ ):
+ fake = MagicMock()
+ fake.download.return_value = None
+ with patch(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ return_value=fake,
+ ):
+ out = pl.batch_fetch_and_extract(
+ [self._ALIAS],
+ content_cache=cache,
+ allow_private_ips=False,
+ block_link_local=False,
+ )
+ assert out[self._ALIAS] is None
+ assert fake.download.call_count >= 1
+
+ def test_engine_fill_alias_bypasses_cache(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ cache = ResearchContentCache()
+ cache.put(self._ALIAS, "alias secret", title="A")
+ engine = StubEngine(content_cache=cache)
+ items = [{"link": self._ALIAS, "title": "A"}]
+ cached, missing = engine._fill_full_content_from_cache(items)
+ assert cached == [] and len(missing) == 1
+ assert items[0].get("full_content") is None
+
+
+class TestOptionalHardening:
+ """Follow-up to APPROVED-OPTIONAL review at d58a9443.
+
+ - Per-run SSRF-verdict memo removes per-hit getaddrinfo.
+ - All three gates fail closed when the validator import fails.
+ - Engine cache gate is scope-aware (withholds grant + evaluate_url).
+ """
+
+ _LOOPBACK = "http://127.0.0.1:9/private-page"
+
+ def test_pipeline_memoizes_ssrf_verdict(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ) as mock_v:
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/a", False, True, cache
+ )
+ is True
+ )
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/a", False, True, cache
+ )
+ is True
+ )
+ # One DNS-backed validation for two identical hits.
+ assert mock_v.call_count == 1
+ assert cache.stats()["validation_memo"] >= 1
+
+ def test_pipeline_memo_distinguishes_grants(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ side_effect=lambda url, allow_private_ips=False, block_link_local=False: (
+ bool(allow_private_ips) if "127.0.0.1" in url else True
+ ),
+ ) as mock_v:
+ assert (
+ pl._is_cache_hit_allowed(self._LOOPBACK, True, True, cache)
+ is True
+ )
+ assert (
+ pl._is_cache_hit_allowed(self._LOOPBACK, False, True, cache)
+ is False
+ )
+ assert (
+ pl._is_cache_hit_allowed(self._LOOPBACK, True, True, cache)
+ is True
+ )
+ # Two distinct (url, grant) keys → two validations.
+ assert mock_v.call_count == 2
+
+ def test_memoized_success_survives_dns_outage(self):
+ import socket
+
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ):
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/offline", False, True, cache
+ )
+ is True
+ )
+ # DNS down: validator would raise gaierror, but the memoized True
+ # verdict serves without re-resolving.
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ side_effect=socket.gaierror("dns down"),
+ ) as mock_v:
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/offline", False, True, cache
+ )
+ is True
+ )
+ assert mock_v.call_count == 0
+
+ def test_pipeline_fails_closed_on_import_error(self):
+ import sys
+
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.security.ssrf_validator": None},
+ ):
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/pub", False, True, cache
+ )
+ is False
+ )
+
+ def test_engine_fails_closed_on_import_error(self):
+ import sys
+
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ engine = StubEngine(content_cache=ResearchContentCache())
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.security.ssrf_validator": None},
+ ):
+ assert (
+ engine._is_cache_url_allowed("https://example.com/pub") is False
+ )
+
+ def test_fetch_tool_fails_closed_on_import_error(self):
+ import sys
+
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _is_fetch_cache_hit_allowed,
+ )
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ ctx = EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ cache = ResearchContentCache()
+ with patch.dict(
+ sys.modules,
+ {
+ "local_deep_research.security.egress.fetch": None,
+ "local_deep_research.security.ssrf_validator": None,
+ },
+ ):
+ assert (
+ _is_fetch_cache_hit_allowed(
+ "https://example.com/pub", ctx, cache
+ )
+ is False
+ )
+
+ def test_engine_scope_withholds_private_under_public_only(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ public_snapshot = {
+ "policy.egress_scope": {"value": "public_only"},
+ "search.tool": {"value": "arxiv"},
+ }
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "cached private", title="T")
+ engine = StubEngine(
+ content_cache=cache, settings_snapshot=public_snapshot
+ )
+ engine.allow_private_result_fetch = True
+ # Grant is withheld by scope (mirrors _downloader_allow_private_ips)
+ # and evaluate_url denies private under PUBLIC_ONLY.
+ assert engine._is_cache_url_allowed(self._LOOPBACK) is False
+ items = [{"link": self._LOOPBACK, "title": "T"}]
+ cached, missing = engine._fill_full_content_from_cache(items)
+ assert cached == [] and len(missing) == 1
+
+ def test_engine_scope_allows_private_under_private_only(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ private_snapshot = {
+ "policy.egress_scope": {"value": "private_only"},
+ "search.tool": {"value": "library"},
+ }
+ cache = ResearchContentCache()
+ cache.put(self._LOOPBACK, "cached private", title="T")
+ engine = StubEngine(
+ content_cache=cache, settings_snapshot=private_snapshot
+ )
+ engine.allow_private_result_fetch = True
+ assert engine._is_cache_url_allowed(self._LOOPBACK) is True
+
+ def test_fetcher_shares_memo_with_tool_gates(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _is_fetch_cache_hit_allowed,
+ )
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ ctx = EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.security.egress.fetch.policy_aware_validate_url",
+ return_value=True,
+ ) as mock_v:
+ assert (
+ _is_fetch_cache_hit_allowed(
+ "https://example.com/shared", ctx, cache
+ )
+ is True
+ )
+ assert (
+ _is_fetch_cache_hit_allowed(
+ "https://example.com/shared", ctx, cache
+ )
+ is True
+ )
+ assert mock_v.call_count == 1
+
+
+class TestMemoRecoveryAndScopeParity:
+ """Required follow-ups from the 18c65d45 review.
+
+ 1. A transient DNS failure (validate_url maps gaierror to False)
+ must not pin the URL for the run — blip then heal recovers.
+ 2. An unevaluable egress policy must refuse the engine cache hit,
+ matching the network path which disables fetching.
+ 3. Memo keys mirror the computed SSRF booleans across gates.
+ """
+
+ _LOOPBACK = "http://127.0.0.1:9/private-page"
+
+ def test_dns_blip_then_heal_recovers(self):
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ cache = ResearchContentCache()
+ calls = {"n": 0}
+
+ def _flaky(url, allow_private_ips=False, block_link_local=False):
+ calls["n"] += 1
+ # First call: DNS blip (gaierror maps to False in validate_url).
+ return calls["n"] > 1
+
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ side_effect=_flaky,
+ ):
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/blip", False, True, cache
+ )
+ is False
+ )
+ # Heal: recomputed (not pinned), now True and pinned.
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/blip", False, True, cache
+ )
+ is True
+ )
+ assert (
+ pl._is_cache_hit_allowed(
+ "https://example.com/blip", False, True, cache
+ )
+ is True
+ )
+ assert calls["n"] == 2
+ assert (
+ cache.get_validation("https://example.com/blip", False, True)
+ is True
+ )
+
+ def test_tool_gate_blip_then_fetcher_heal(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _is_fetch_cache_hit_allowed,
+ )
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ ctx = EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ cache = ResearchContentCache()
+ url = "https://example.com/blip-heal"
+ with patch(
+ "local_deep_research.security.egress.fetch.policy_aware_validate_url",
+ return_value=False,
+ ):
+ assert _is_fetch_cache_hit_allowed(url, ctx, cache) is False
+ # Blip False is not pinned.
+ assert cache.get_validation(url, False, False) is None
+ # NOTE: fetcher.py binds policy_aware_validate_url at import, so
+ # the fetcher-side symbol (not the source module) is patched.
+ with patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ) as mock_v:
+ fetcher = ContentFetcher(egress_context=ctx, content_cache=cache)
+ with patch.object(fetcher, "_get_downloader", return_value=None):
+ out = fetcher.fetch(url)
+ # Passes the SSRF gate (fails later at downloader),
+ # proving the blip did not pin.
+ assert out.get("error") != (
+ "URL failed security validation "
+ "(blocked by SSRF protection)"
+ )
+ assert mock_v.call_count >= 1
+
+ def test_import_failure_false_not_pinned(self):
+ import sys
+
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _is_fetch_cache_hit_allowed,
+ )
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ ctx = EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ cache = ResearchContentCache()
+ url = "https://example.com/import-blip"
+ with patch.dict(
+ sys.modules,
+ {"local_deep_research.security.egress.fetch": None},
+ ):
+ assert _is_fetch_cache_hit_allowed(url, ctx, cache) is False
+ with patch(
+ "local_deep_research.security.egress.fetch.policy_aware_validate_url",
+ return_value=True,
+ ):
+ assert _is_fetch_cache_hit_allowed(url, ctx, cache) is True
+
+ def test_engine_unevaluable_policy_refuses_cache(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ bogus_snapshot = {
+ "policy.egress_scope": {"value": "bogus_scope"},
+ "search.tool": {"value": "arxiv"},
+ }
+ cache = ResearchContentCache()
+ cache.put("https://example.com/pub", "public body", title="T")
+ engine = StubEngine(
+ content_cache=cache, settings_snapshot=bogus_snapshot
+ )
+ # Network path disables fetching on unevaluable policy; the cache
+ # must refuse too rather than serve SSRF-only.
+ assert engine._is_cache_url_allowed("https://example.com/pub") is False
+ items = [{"link": "https://example.com/pub", "title": "T"}]
+ cached, missing = engine._fill_full_content_from_cache(items)
+ assert cached == [] and len(missing) == 1
+ assert items[0].get("full_content") is None
+
+ def test_engine_no_snapshot_still_ssrf_only(self):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ cache = ResearchContentCache()
+ cache.put("https://example.com/pub", "public body", title="T")
+ engine = StubEngine(content_cache=cache)
+ assert engine._is_cache_url_allowed("https://example.com/pub") is True
+
+ def test_memo_key_mirrors_compute(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _is_fetch_cache_hit_allowed,
+ )
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ )
+
+ ctx = EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine="test",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ cache = ResearchContentCache()
+ with patch(
+ "local_deep_research.security.egress.fetch.policy_aware_validate_url",
+ return_value=True,
+ ):
+ assert (
+ _is_fetch_cache_hit_allowed(
+ "https://example.com/keyed", ctx, cache
+ )
+ is True
+ )
+ # UNPROTECTED computes strict validate_url(url) defaults
+ # (False, False) — the cell must live under that key, not the
+ # pipeline-style (False, True) cell sharing a different compute.
+ assert (
+ cache.get_validation("https://example.com/keyed", False, False)
+ is True
+ )
+ assert (
+ cache.get_validation("https://example.com/keyed", False, True)
+ is None
+ )
+
+
+class TestReviewOptionalFollowups:
+ """Optional notes from the c65fde9f APPROVED review, plus the 557de142
+ APPROVED review.
+
+ 1. Under an unevaluable policy the engine cache refused path-only
+ ``/library/...`` hits while the fetch tool still serves library
+ documents from the local DB without any egress check — local-only
+ content must stay available under a corrupted scope setting.
+ 2. Cache-probe scope checks must not burn the run-wide denial quota —
+ only real fetches count toward ``MAX_DENIED_FETCHES_PER_RUN``.
+ 3. (557de142 #1) Library exemption grammar matches the fetch tool's
+ strict 32/64-hex-or-UUID: slug-shaped routes are not exempt.
+ 4. (557de142 #2) Exhausted quota still refuses cache probes
+ (``denial_quota_exceeded``) — probes cannot evade the cliff.
+ """
+
+ _DOC = "/library/document/12345678123456781234567812345678"
+
+ def _stub_engine(self, cache, snapshot=None):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class StubEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ kwargs = {"content_cache": cache}
+ if snapshot is not None:
+ kwargs["settings_snapshot"] = snapshot
+ return StubEngine(**kwargs)
+
+ def test_unevaluable_policy_still_serves_library(self):
+ bogus_snapshot = {
+ "policy.egress_scope": {"value": "bogus_scope"},
+ "search.tool": {"value": "arxiv"},
+ }
+ cache = ResearchContentCache()
+ cache.put(self._DOC, "local body", title="T")
+ cache.put("https://example.com/pub", "public body", title="T")
+ engine = self._stub_engine(cache, bogus_snapshot)
+ # Web still fails closed (matches the network path disabling fetch).
+ assert engine._is_cache_url_allowed("https://example.com/pub") is False
+ # Library is a local DB read — same as the fetch tool's
+ # _try_resolve_url fast path which skips the egress gate.
+ assert engine._is_cache_url_allowed(self._DOC) is True
+ items = [
+ {"link": self._DOC, "title": "T"},
+ {"link": "https://example.com/pub", "title": "T"},
+ ]
+ cached, missing = engine._fill_full_content_from_cache(items)
+ assert {i["link"] for i in cached} == {self._DOC}
+ assert {i["link"] for i in missing} == {"https://example.com/pub"}
+ assert items[0].get("full_content") == "local body"
+
+ def test_evaluate_url_no_record_matches_verdict_without_quota(self):
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ MAX_DENIED_FETCHES_PER_RUN,
+ evaluate_url,
+ )
+
+ ctx = EgressContext(
+ scope=EgressScope.PUBLIC_ONLY,
+ primary_engine="arxiv",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ # Same verdict both ways for a scope-mismatched private host.
+ denied_recorded = evaluate_url("http://10.0.0.5/", ctx)
+ assert denied_recorded.allowed is False
+ assert denied_recorded.reason == "scope_mismatch_public_only"
+ assert ctx._fetch_denial_count["count"] == 1
+ denied_probe = evaluate_url(
+ "http://10.0.0.6/", ctx, record_denial=False
+ )
+ assert denied_probe.allowed is False
+ assert denied_probe.reason == "scope_mismatch_public_only"
+ assert ctx._fetch_denial_count["count"] == 1
+ # Allowed verdicts never touch the quota either way.
+ allowed = evaluate_url(
+ "http://93.184.216.34/", ctx, record_denial=False
+ )
+ assert allowed.allowed is True
+ assert ctx._fetch_denial_count["count"] == 1
+ # Flooding probes past the cap never trips denial_quota_exceeded.
+ for _ in range(MAX_DENIED_FETCHES_PER_RUN + 5):
+ d = evaluate_url("http://10.0.0.5/", ctx, record_denial=False)
+ assert d.reason == "scope_mismatch_public_only"
+ assert ctx._fetch_denial_count["count"] == 1
+
+ def test_engine_cache_probes_do_not_burn_quota(self):
+ public_snapshot = {
+ "policy.egress_scope": {"value": "public_only"},
+ "search.tool": {"value": "arxiv"},
+ }
+ cache = ResearchContentCache()
+ loopback = "http://127.0.0.1:9/private-page"
+ cache.put(loopback, "cached private", title="T")
+ engine = self._stub_engine(cache, public_snapshot)
+ engine.allow_private_result_fetch = True
+ # 60 scope-mismatched cache candidates — the old recording probe
+ # would have hit the 50-denial cliff; the non-recording probe must
+ # leave the run counter at zero.
+ for _ in range(60):
+ assert engine._is_cache_url_allowed(loopback) is False
+ egress_ctx = engine._get_cache_egress_context()
+ assert egress_ctx is not None
+ assert egress_ctx._fetch_denial_count["count"] == 0
+ # The run can still fetch an allowed public URL (quota intact).
+ from local_deep_research.security.egress.policy import evaluate_url
+
+ decision = evaluate_url("http://93.184.216.34/", egress_ctx)
+ assert decision.allowed is True
+
+ def test_engine_exhausted_quota_refuses_cache_probes(self):
+ """Exhausted denial quota fails closed on cache probes too.
+
+ Optional note #2 from the 557de142 APPROVED review: the
+ non-recording probe verdict flips to refusal past the
+ ``MAX_DENIED_FETCHES_PER_RUN`` cliff, same as the fetch path —
+ so a probe cannot serve as a quota-evading oracle.
+ """
+ from local_deep_research.security.egress.policy import (
+ MAX_DENIED_FETCHES_PER_RUN,
+ evaluate_url,
+ )
+
+ public_snapshot = {
+ "policy.egress_scope": {"value": "public_only"},
+ "search.tool": {"value": "arxiv"},
+ }
+ cache = ResearchContentCache()
+ public_url = "http://93.184.216.34/"
+ cache.put(public_url, "public body", title="T")
+ engine = self._stub_engine(cache, public_snapshot)
+ # Sanity: allowed before the cliff (SSRF passes for a public
+ # IP literal; scope allows it under PUBLIC_ONLY).
+ assert engine._is_cache_url_allowed(public_url) is True
+ egress_ctx = engine._get_cache_egress_context()
+ assert egress_ctx is not None
+ # Exhaust the run quota via the recording fetch path.
+ for _ in range(MAX_DENIED_FETCHES_PER_RUN):
+ denied = evaluate_url("http://10.0.0.5/", egress_ctx)
+ assert denied.allowed is False
+ assert (
+ egress_ctx._fetch_denial_count["count"]
+ == MAX_DENIED_FETCHES_PER_RUN
+ )
+ # The non-recording probe now refuses with the quota reason.
+ probe = evaluate_url(public_url, egress_ctx, record_denial=False)
+ assert probe.allowed is False
+ assert probe.reason == "denial_quota_exceeded"
+ # And the engine cache gate follows it fail-closed.
+ assert engine._is_cache_url_allowed(public_url) is False
+ # The cliff never records, so the counter stays pinned at the cap.
+ assert (
+ egress_ctx._fetch_denial_count["count"]
+ == MAX_DENIED_FETCHES_PER_RUN
+ )
+
+ def test_library_still_served_past_quota_cliff(self):
+ """Valid library routes stay servable past the quota cliff.
+
+ Optional note from the 488e1865 APPROVED review: library
+ servability past an exhausted quota depends on the exemption
+ running before the quota check inside the gate — that ordering
+ is what spares local DB reads. This pins it (the quota test
+ above pins only the web refusal).
+ """
+ from local_deep_research.security.egress.policy import (
+ MAX_DENIED_FETCHES_PER_RUN,
+ evaluate_url,
+ )
+
+ public_snapshot = {
+ "policy.egress_scope": {"value": "public_only"},
+ "search.tool": {"value": "arxiv"},
+ }
+ cache = ResearchContentCache()
+ public_url = "http://93.184.216.34/"
+ cache.put(public_url, "public body", title="T")
+ cache.put(self._DOC, "local body", title="T")
+ engine = self._stub_engine(cache, public_snapshot)
+ # Sanity: both servable before the cliff.
+ assert engine._is_cache_url_allowed(public_url) is True
+ assert engine._is_cache_url_allowed(self._DOC) is True
+ egress_ctx = engine._get_cache_egress_context()
+ assert egress_ctx is not None
+ # Exhaust the run quota via the recording fetch path.
+ for _ in range(MAX_DENIED_FETCHES_PER_RUN):
+ denied = evaluate_url("http://10.0.0.5/", egress_ctx)
+ assert denied.allowed is False
+ assert (
+ egress_ctx._fetch_denial_count["count"]
+ == MAX_DENIED_FETCHES_PER_RUN
+ )
+ # Web now fails closed on the quota cliff ...
+ assert engine._is_cache_url_allowed(public_url) is False
+ # ... but the path-only library exemption runs before the quota
+ # check, so local DB reads stay servable (same as the fetch
+ # tool's _try_resolve_url fast path and the unevaluable-policy
+ # exemption).
+ assert engine._is_cache_url_allowed(self._DOC) is True
+ items = [
+ {"link": self._DOC, "title": "T"},
+ {"link": public_url, "title": "T"},
+ ]
+ cached, missing = engine._fill_full_content_from_cache(items)
+ assert {i["link"] for i in cached} == {self._DOC}
+ assert {i["link"] for i in missing} == {public_url}
+ assert items[0].get("full_content") == "local body"
+ # Library probes must not burn quota either — counter stays
+ # pinned at the cap.
+ assert (
+ egress_ctx._fetch_denial_count["count"]
+ == MAX_DENIED_FETCHES_PER_RUN
+ )
+
+ def test_library_exemption_matches_fetch_tool_grammar(self):
+ """Engine/pipeline exemption uses the fetch tool's strict grammar.
+
+ Optional note #1 from the 557de142 APPROVED review: the old
+ exemption used ``library_display_url`` (any ``[0-9A-Za-z_-]+``
+ slug), while the fetch tool's resolver accepts only
+ 32/64-hex or UUID ids. A slug-shaped route can never resolve via
+ the fetch tool, so exempting it here would let the two surfaces
+ drift. Both gates now share ``parse_library_url``.
+ """
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ parse_library_url,
+ )
+
+ strict = "/library/document/12345678123456781234567812345678"
+ strict_chunk = (
+ "/library/document/12345678123456781234567812345678/chunks#chunk-3"
+ )
+ slug = "/library/document/report"
+ # Fetch-tool ground truth.
+ assert parse_library_url(strict) is not None
+ assert parse_library_url(strict_chunk) is not None
+ assert parse_library_url(slug) is None
+ # Engine mirrors it (SSRF mocked to refuse, so only the
+ # exemption can return True).
+ engine = self._stub_engine(ResearchContentCache())
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=False,
+ ):
+ assert engine._is_cache_url_allowed(strict) is True
+ assert engine._is_cache_url_allowed(strict_chunk) is True
+ assert engine._is_cache_url_allowed(slug) is False
+ # Pipeline mirrors it too.
+ from local_deep_research.research_library.downloaders.extraction import (
+ pipeline as pl,
+ )
+
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=False,
+ ):
+ assert pl._is_cache_hit_allowed(strict, False, True) is True
+ assert pl._is_cache_hit_allowed(strict_chunk, False, True) is True
+ assert pl._is_cache_hit_allowed(slug, False, True) is False
diff --git a/tests/utilities/test_research_content_cache_recovery.py b/tests/utilities/test_research_content_cache_recovery.py
new file mode 100644
index 0000000000..411f514356
--- /dev/null
+++ b/tests/utilities/test_research_content_cache_recovery.py
@@ -0,0 +1,143 @@
+"""Cache ownership and bounded waiter failure contracts."""
+
+import threading
+from unittest.mock import Mock
+from uuid import uuid4
+
+import pytest
+
+from local_deep_research.search_system import AdvancedSearchSystem
+from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+ bind_cache_to_research,
+ get_cache_for_research,
+ unbind_cache_from_research,
+)
+
+
[email protected]("already_bound", [False, True])
+def test_failed_system_construction_preserves_registry(
+ monkeypatch, already_bound
+):
+ rid = str(uuid4())
+ prior_cache = ResearchContentCache() if already_bound else None
+ if prior_cache is not None:
+ bind_cache_to_research(rid, prior_cache)
+
+ def fail_strategy(**kwargs):
+ raise RuntimeError("strategy initialization failed")
+
+ monkeypatch.setattr(
+ "local_deep_research.search_system_factory.create_strategy",
+ fail_strategy,
+ )
+ try:
+ with pytest.raises(
+ RuntimeError, match="strategy initialization failed"
+ ):
+ AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ strategy_name="source-based",
+ settings_snapshot={},
+ research_id=rid,
+ )
+ assert get_cache_for_research(rid) is prior_cache
+ finally:
+ unbind_cache_from_research(rid)
+
+
+def test_waiter_timeout_preserves_owner_and_its_later_result():
+ cache = ResearchContentCache()
+ started = threading.Event()
+ release = threading.Event()
+
+ def owner_fetch():
+ started.set()
+ assert release.wait(5)
+ return {"content": "owner result"}
+
+ thread = threading.Thread(
+ target=lambda: cache.get_or_fetch("https://example.com/p", owner_fetch)
+ )
+ thread.start()
+ try:
+ assert started.wait(2)
+ with pytest.raises(TimeoutError, match="Timed out waiting"):
+ cache.get_or_fetch(
+ "https://example.com/p",
+ lambda: {"content": "fallback"},
+ wait_timeout=0,
+ )
+ finally:
+ release.set()
+ thread.join(2)
+ assert not thread.is_alive()
+
+ fallback = Mock(side_effect=AssertionError("owner result was lost"))
+ assert (
+ cache.get_or_fetch("https://example.com/p", fallback)["content"]
+ == "owner result"
+ )
+ fallback.assert_not_called()
+
+
+def test_closing_older_system_preserves_replacement_binding():
+ rid = str(uuid4())
+ first = AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ strategy_name="source-based",
+ settings_snapshot={},
+ research_id=rid,
+ )
+ second = None
+ try:
+ second = AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ strategy_name="source-based",
+ settings_snapshot={},
+ research_id=rid,
+ )
+ first.close()
+ assert get_cache_for_research(rid) is second.content_cache
+ finally:
+ first.close()
+ if second is not None:
+ second.close()
+ unbind_cache_from_research(rid)
+ assert get_cache_for_research(rid) is None
+
+
[email protected]("primary", [" arxiv ", {"value": " arxiv "}])
+def test_cache_uses_canonical_run_primary(primary):
+ engine = _cache_engine({"search.tool": primary})
+ assert engine._get_cache_egress_context().primary_engine == "arxiv"
+
+
[email protected]("operator_scope", [False, True])
+def test_strict_cache_without_saved_primary_refuses_web_hit(
+ monkeypatch, operator_scope
+):
+ snapshot = {"policy.egress_scope": "strict"}
+ if operator_scope:
+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "strict")
+ snapshot = {}
+ engine = _cache_engine(snapshot)
+ assert engine._get_cache_egress_context() is None
+ assert engine._is_cache_url_allowed("http://93.184.216.34/article") is False
+
+
+def _cache_engine(snapshot):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class Engine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ engine = Engine(settings_snapshot=snapshot, programmatic_mode=True)
+ engine._engine_name = "arxiv"
+ return engine
diff --git a/tests/utilities/test_url_utils.py b/tests/utilities/test_url_utils.py
index f5f504b233..a41bd0f344 100644
--- a/tests/utilities/test_url_utils.py
+++ b/tests/utilities/test_url_utils.py
@@ -473,6 +473,110 @@ class TestCanonicalUrlKey:
)
+class TestContentWebCacheKey:
+ """Content-fetch identity — NOT bibliography dedup (PR #6759).
+
+ ``content_web_cache_key`` shares the safe normalisations (scheme/host
+ case, default ports, fragments, tracking params — accepting over-merge
+ on sites varying content per tracking param) but preserves the
+ two distinctions the bibliography key collapses: a non-root trailing
+ slash (``/article`` vs ``/article/`` serve different bytes) and URL
+ userinfo (different credentials select different views).
+ """
+
+ def setup_method(self):
+ from local_deep_research.utilities.url_utils import (
+ content_web_cache_key,
+ )
+
+ content_web_cache_key.cache_clear()
+
+ def test_trailing_slash_stays_distinct(self):
+ from local_deep_research.utilities.url_utils import (
+ canonical_url_key,
+ content_web_cache_key,
+ )
+
+ canonical_url_key.cache_clear()
+ # Bibliography still collapses (unchanged behaviour).
+ assert canonical_url_key("https://example.com/p") == canonical_url_key(
+ "https://example.com/p/"
+ )
+ # Content must not.
+ assert content_web_cache_key(
+ "https://example.com/p"
+ ) != content_web_cache_key("https://example.com/p/")
+ assert content_web_cache_key(
+ "http://127.0.0.1:9/article"
+ ) != content_web_cache_key("http://127.0.0.1:9/article/")
+
+ def test_userinfo_stays_distinct(self):
+ from local_deep_research.utilities.url_utils import (
+ canonical_url_key,
+ content_web_cache_key,
+ )
+
+ canonical_url_key.cache_clear()
+ assert canonical_url_key(
+ "https://user:[email protected]/p"
+ ) == canonical_url_key("https://example.com/p")
+ assert content_web_cache_key(
+ "https://user:[email protected]/p"
+ ) != content_web_cache_key("https://example.com/p")
+ # Different credentials are different views.
+ assert content_web_cache_key(
+ "https://[email protected]/p"
+ ) != content_web_cache_key("https://[email protected]/p")
+ # Host still lowercased around preserved userinfo.
+ assert content_web_cache_key(
+ "https://User:[email protected]/p"
+ ) == content_web_cache_key("https://User:[email protected]/p")
+
+ def test_query_and_shared_normalisations(self):
+ from local_deep_research.utilities.url_utils import (
+ content_web_cache_key,
+ )
+
+ # Semantically meaningful queries stay apart.
+ assert content_web_cache_key(
+ "https://example.com/p?a=1"
+ ) != content_web_cache_key("https://example.com/p?a=2")
+ assert content_web_cache_key(
+ "https://example.com/p?foo=1"
+ ) != content_web_cache_key("https://example.com/p")
+ # Tracking params still collapse (content-free, as in bibliography;
+ # accepts over-merge on sites that vary content per param).
+ assert content_web_cache_key(
+ "https://example.com/p?utm_source=x&foo=1"
+ ) == content_web_cache_key("https://example.com/p?foo=1")
+ # Default ports name one endpoint; scheme/host case names one host;
+ # tracking params collapse. Fragments are preserved: client-routed SPAs
+ # render distinct views per fragment under JS rendering.
+ assert content_web_cache_key(
+ "https://example.com/p#section"
+ ) != content_web_cache_key("https://example.com/p")
+ assert content_web_cache_key(
+ "https://spa.example.com/app#/route-alpha"
+ ) != content_web_cache_key("https://spa.example.com/app#/route-beta")
+ assert content_web_cache_key(
+ "https://example.com:443/p"
+ ) == content_web_cache_key("https://example.com/p")
+ assert content_web_cache_key(
+ "HTTPS://EXAMPLE.COM/p"
+ ) == content_web_cache_key("https://example.com/p")
+ # Path case still selects distinct resources.
+ assert content_web_cache_key(
+ "https://example.com/P"
+ ) != content_web_cache_key("https://example.com/p")
+ # Non-default ports stay distinct, incl. with userinfo + IPv6.
+ assert content_web_cache_key(
+ "https://example.com:8443/p"
+ ) != content_web_cache_key("https://example.com/p")
+ assert content_web_cache_key(
+ "http://user:pass@[::1]:8080/p"
+ ) != content_web_cache_key("http://[::1]:8080/p")
+
+
class TestLibraryRouteHardening:
"""Round-2 follow-up (#5685): the relative and absolute spellings of a
library route must enforce identical rules."""
diff --git a/tests/web_search_engines/engines/test_guardian_coverage.py b/tests/web_search_engines/engines/test_guardian_coverage.py
index 1622c92172..3c2e0f39f7 100644
--- a/tests/web_search_engines/engines/test_guardian_coverage.py
+++ b/tests/web_search_engines/engines/test_guardian_coverage.py
@@ -484,6 +484,7 @@ class TestGetAllDataLogic:
"author",
"content",
"full_content",
+ "full_content_is_complete",
"keywords",
}
diff --git a/tests/web_search_engines/engines/test_guardian_snippets_contract.py b/tests/web_search_engines/engines/test_guardian_snippets_contract.py
index e599aea27f..27a6c240e1 100644
--- a/tests/web_search_engines/engines/test_guardian_snippets_contract.py
+++ b/tests/web_search_engines/engines/test_guardian_snippets_contract.py
@@ -4,6 +4,9 @@ from unittest.mock import Mock, patch
import pytest
+from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+)
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
GuardianSearchEngine,
)
@@ -132,3 +135,94 @@ def test_relevance_filter_keeps_selected_article_in_both_modes(snippets_only):
assert ("full_content" in results[0]) is (not snippets_only)
if not snippets_only:
assert results[0]["full_content"] == "Body two"
+
+
+def cached_guardian_engine():
+ engine = GuardianSearchEngine(
+ api_key="test-key",
+ adaptive_search=False,
+ optimize_queries=False,
+ search_snippets_only=False,
+ )
+ engine.content_cache = ResearchContentCache()
+ engine.rate_tracker.apply_rate_limit = Mock(return_value=0)
+ with patch(
+ "local_deep_research.security.ssrf_validator.validate_url",
+ return_value=True,
+ ):
+ yield engine
+
+
[email protected]("cached_body", [None, "Previously fetched body"])
+def test_snippets_never_restore_or_populate_shared_cache(
+ cached_guardian_engine, cached_body
+):
+ engine = cached_guardian_engine
+ engine.search_snippets_only = True
+ url = "https://www.theguardian.com/one"
+ if cached_body is not None:
+ engine.content_cache.put(url, cached_body)
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ return_value=_api_response(_article("one", "Unrequested body")),
+ ):
+ results = engine.run("climate policy")
+
+ assert len(results) == 1
+ assert results[0]["snippet"] == "Preview one"
+ assert "content" not in results[0]
+ assert "full_content" not in results[0]
+ assert "full_content_is_complete" not in results[0]
+ cached = engine.content_cache.get(url)
+ if cached_body is None:
+ assert cached is None
+ else:
+ assert cached["content"] == cached_body
+
+
+def test_full_content_reuses_shared_cache_after_local_cleanup(
+ cached_guardian_engine,
+):
+ engine = cached_guardian_engine
+ url = "https://www.theguardian.com/one"
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ side_effect=[
+ _api_response(_article("one", "Complete body")),
+ _api_response(_article("one", "")),
+ ],
+ ):
+ first = engine.run("climate policy")
+ assert first[0]["full_content"] == "Complete body"
+ assert not hasattr(engine, "_full_articles")
+ assert engine.content_cache.get(url)["content"] == "Complete body"
+
+ second = engine.run("related climate policy")
+
+ assert second[0]["full_content"] == "Complete body"
+ assert second[0]["full_content_is_complete"] is True
+ assert not hasattr(engine, "_full_articles")
+
+
+def test_missing_body_does_not_prevent_later_complete_fetch(
+ cached_guardian_engine,
+):
+ engine = cached_guardian_engine
+ url = "https://www.theguardian.com/one"
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ side_effect=[
+ _api_response(_article("one", "")),
+ _api_response(_article("one", "Complete body")),
+ ],
+ ):
+ first = engine.run("climate policy")
+ assert first[0]["full_content_is_complete"] is False
+ assert engine.content_cache.get(url) is None
+
+ second = engine.run("related climate policy")
+
+ assert second[0]["full_content"] == "Complete body"
+ assert engine.content_cache.get(url)["content"] == "Complete body"