~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(strategy): add per-topic fetch budget cap for langgraph-agent (#5815) (#6379)
S35083b2e57c2
diff --git a/changelog.d/5815.bugfix.md b/changelog.d/5815.bugfix.mdnew file mode 100644index 0000000000..125e140794--- /dev/null+++ b/changelog.d/5815.bugfix.md@@ -0,0 +1 @@+Added a configurable per-subagent (and lead agent) call budget cap (`search.fetch.max_per_topic`, default: 2) for `fetch_content` tool invocations in the `langgraph-agent` strategy. Previously, `fetch_content` had no per-topic budget, allowing agents to repeatedly fetch pages and exhaust their entire turn recursion limit without synthesizing findings. The budget only counts requests that reach the network (egress policy denials and local library document resolutions do not consume slots). When the budget is reached, further `fetch_content` calls return a clear message directing the agent to synthesize findings or rely on search snippets, without making redundant HTTP requests or LLM extraction calls. The tool description advertises the budget to the model, and successful fetches report progress ("N of M page fetches used"). Setting `search.fetch.max_per_topic = 0` preserves unlimited fetches. Step heartbeats now also report the count of page fetch attempts alongside distinct sources gathered.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex ac00e0e855..bcc4c82d2b 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -628,6 +628,7 @@ They are not available in the Web UI because they are needed to start the applic| `search.engine.web.zenodo.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_ZENODO_USE_IN_AUTO_SEARCH` | `false` | Include Zenodo in auto search mode | SEARCH || `search.engine.web.zenodo.weaknesses` | `LDR_SEARCH_ENGINE_WEB_ZENODO_WEAKNESSES` | ``["research focus", "variable quality", "metadata only"]`` | Limitations of Zenodo. | SEARCH || `search.favorites` | `LDR_SEARCH_FAVORITES` | ``["arxiv", "searxng", "library", "openalex"]`` | List of favorite search engine IDs that appear at the top of the dropdown. Edit as JSON array, e.g. ["arxiv", "brave"] | SEARCH |+| `search.fetch.max_per_topic` | `LDR_SEARCH_FETCH_MAX_PER_TOPIC` | `2` | Maximum number of page content fetches (fetch_content calls) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets). | SEARCH || `search.fetch.mode` | `LDR_SEARCH_FETCH_MODE` | `summary_focus_query` | Controls the LangGraph agent's fetch_content tool. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes the tool entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled. | SEARCH || `search.final_max_results` | `LDR_SEARCH_FINAL_MAX_RESULTS` | `100` | Maximum unique sources to include in the final research output. Applied in pipeline/source-based strategies once after all search iterations complete, deduplicating and filtering across all accumulated results. Note: Autonomous agent strategies (like langgraph-agent) manage context autonomously and do not cap final results. | SEARCH || `search.iterations` | `LDR_SEARCH_ITERATIONS` | `3` | Number of search-and-refine cycles to run. Each iteration generates follow-up questions based on previous results to progressively deepen the research. More iterations yield better coverage but increase search and LLM API usage. | 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.pyindex 1be2d71bd5..5de90239f9 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@@ -14,7 +14,9 @@ import reimport threadingimport timeimport unicodedata+import uuidfrom concurrent.futures import ThreadPoolExecutor+from contextvars import ContextVarfrom datetime import UTC, datetimefrom typing import Any, Dict, Optional@@ -52,7 +54,12 @@ from ...utilities.url_utils import ()from ...utilities.json_utils import get_llm_response_textfrom ...database.thread_local_session import thread_cleanup-from ..tools.fetch import FETCH_MODES, build_fetch_tool, make_library_resolver+from ..tools.fetch import (+ DEFAULT_MAX_FETCHES_PER_TOPIC,+ FETCH_MODES,+ build_fetch_tool,+ make_library_resolver,+)from .base_strategy import (BaseSearchStrategy,CHECK_CONTEXT_AGENT_STREAM,@@ -299,6 +306,11 @@ def _strip_unvalidated_chunk_fragments(result: dict) -> dict:return cleaned if cleaned is not None else result+_current_subagent_context: ContextVar[str | None] = ContextVar(+ "_current_subagent_context", default=None+)++class SearchResultsCollector:"""Accumulates search results from the lead agent and subagents.@@ -370,6 +382,8 @@ class SearchResultsCollector:# duplicates.self._sources_seen: set[str] = set()self._lock = threading.Lock()+ self._fetch_counts: dict[str, int] = {}+ self._total_fetch_count = 0self._all_links = all_links if all_links is not None else []# Canonical URL -> the FIRST citation index allocated for it.# No longer the dedup key (see ``_pair_to_index``): a source can@@ -1026,12 +1040,53 @@ class SearchResultsCollector:continuereturn None+ def try_record_fetch(+ self, max_fetches: int, subagent_id: str | None = None+ ) -> tuple[bool, int]:+ """Atomically check budget and increment fetch count if allowed.++ Returns (allowed, current_count). If max_fetches <= 0, fetches are unlimited.+ Each subagent (and lead agent) maintains its own independent budget counter.+ """+ with self._lock:+ sid = _current_subagent_context.get() or subagent_id or "lead"+ current = self._fetch_counts.get(sid, 0)+ if max_fetches > 0 and current >= max_fetches:+ return False, current+ current += 1+ self._fetch_counts[sid] = current+ self._total_fetch_count += 1+ return True, current++ def record_fetch(self, subagent_id: str | None = None) -> int:+ """Increment and return the current fetch count for this subagent/topic."""+ with self._lock:+ sid = _current_subagent_context.get() or subagent_id or "lead"+ current = self._fetch_counts.get(sid, 0) + 1+ self._fetch_counts[sid] = current+ self._total_fetch_count += 1+ return current++ @property+ def fetch_count(self) -> int:+ """Total number of content fetches executed across all subagents and lead agent since last reset()."""+ with self._lock:+ return self._total_fetch_count++ def get_fetch_count(self, subagent_id: str | None = None) -> int:+ """Fetch count for a specific subagent (or lead agent) since last reset()."""+ with self._lock:+ sid = _current_subagent_context.get() or subagent_id or "lead"+ return self._fetch_counts.get(sid, 0)+def reset(self) -> None:"""Clear per-call state. ``_all_links`` is intentionally kept."""with self._lock:self._results.clear()self._sources.clear()self._sources_seen.clear()+ self._fetch_counts.clear()+ self._total_fetch_count = 0@propertydef results(self) -> list[dict]:@@ -1455,6 +1510,7 @@ def _make_research_subtopic_tool(max_subagent_workers: int = MAX_SUBAGENT_WORKERS,library_resolver: Any = None,web_search_description: str = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,+ max_fetches_per_topic: int | None = None,):"""Create the ``research_subtopic`` tool that spawns parallel subagents.@@ -1551,6 +1607,8 @@ def _make_research_subtopic_tool(settings_snapshot=settings_snapshot,egress_context=egress_context,library_resolver=library_resolver,+ max_fetches=max_fetches_per_topic,+ subagent_id="subagent",)if sub_fetch is not None:sub_tools.append(sub_fetch)@@ -1638,6 +1696,11 @@ def _make_research_subtopic_tool()def run_subagent(topic: str) -> str:+ token = None+ if _current_subagent_context.get() is None:+ token = _current_subagent_context.set(+ f"subagent_{uuid.uuid4().hex}"+ )try:# create_agent() calls model.bind_tools(); ProcessingLLMWrapper# (config/llm_config.py) overrides bind_tools to re-wrap the@@ -1672,6 +1735,9 @@ def _make_research_subtopic_tool(return sanitize_error_for_agent(f"Research on '{topic}' failed: {exc}")+ finally:+ if token is not None:+ _current_subagent_context.reset(token)# Capture the lead thread's search context (it carries the user's DB# password) so each pool worker can open the per-user ENCRYPTED database@@ -1694,6 +1760,9 @@ def _make_research_subtopic_tool(def _run_subagent_with_egress(task: tuple[int, str]) -> str:task_id, topic = task+ sub_token = _current_subagent_context.set(+ f"subagent_{uuid.uuid4().hex}"+ )with task_state_changed:task_start_times[task_id] = time.monotonic()task_state_changed.notify_all()@@ -1716,6 +1785,7 @@ def _make_research_subtopic_tool(return run_subagent(topic)return run_subagent(topic)finally:+ _current_subagent_context.reset(sub_token)with task_state_changed:task_end_times[task_id] = time.monotonic()task_state_changed.notify_all()@@ -1967,6 +2037,27 @@ class LangGraphAgentStrategy(BaseSearchStrategy):self.fetch_mode = fetch_modelogger.info(f"LangGraph agent fetch_mode={self.fetch_mode}")+ # Cap on fetch_content tool calls per subagent (and lead agent) per topic/subsection+ # (prevents agents from exhausting their recursion limit on fetches alone).+ # Default is 2: subagents typically only need 1-2 key page fetches to complement+ # search snippets, so a conservative per-agent cap prevents runaway page fetches+ # from exhausting recursion turns while scaling safely across multiple parallel subtopics.+ # Set to 0 for unlimited.+ raw_max_fetches = self.get_setting(+ "search.fetch.max_per_topic", DEFAULT_MAX_FETCHES_PER_TOPIC+ )+ try:+ limit = int(raw_max_fetches)+ if limit < 0:+ self.max_fetches_per_topic = DEFAULT_MAX_FETCHES_PER_TOPIC+ else:+ self.max_fetches_per_topic = min(50, limit)+ except (TypeError, ValueError):+ self.max_fetches_per_topic = DEFAULT_MAX_FETCHES_PER_TOPIC+ logger.info(+ f"LangGraph agent max_fetches_per_topic={self.max_fetches_per_topic}"+ )+# User-tunable pool size for parallel subagents (follow-up to #5014).# Lets users match their LLM backend's parallel-request capacity --# Ollama / LMStudio / llama.cpp ``OLLAMA_NUM_PARALLEL``, an OpenAI@@ -2238,7 +2329,9 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# ``fetch_content`` denial framing, not a generic string-substring# match.if tool_name == "fetch_content" and (- raw.startswith("Cannot fetch ") or raw.startswith("Error fetching ")+ raw.startswith("Cannot fetch ")+ or raw.startswith("Error fetching ")+ or raw.startswith("Fetch content budget exhausted")):return None@@ -2275,11 +2368,17 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# it found", which is what the ## Sources block will show.sources_so_far = count_distinct_sources(self.all_links_of_system)names = getattr(self, "_tool_names", []) or []+ fetch_count = self.collector.fetch_count+ fetch_part = (+ f" · {fetch_count} page fetch attempt{'s' if fetch_count != 1 else ''}"+ if fetch_count > 0+ else ""+ )if sources_so_far == 0:return (f"Step {iteration} · planning approach "f"with {len(names)} research tool"- f"{'s' if len(names) != 1 else ''} available…"+ f"{'s' if len(names) != 1 else ''} available…{fetch_part}")listing = ", ".join(_HEARTBEAT_TOOL_LABELS.get(n) or self._display_tool_name(n)@@ -2287,7 +2386,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):)return (f"Step {iteration} · {sources_so_far} source"- f"{'s' if sources_so_far != 1 else ''} gathered · "+ f"{'s' if sources_so_far != 1 else ''} gathered{fetch_part} · "f"selecting next action from {listing}")@@ -2496,6 +2595,8 @@ class LangGraphAgentStrategy(BaseSearchStrategy):settings_snapshot=self.settings_snapshot,egress_context=policy_ctx,library_resolver=library_resolver,+ max_fetches=self.max_fetches_per_topic,+ subagent_id="lead",)if fetch is not None:tools.append(fetch)@@ -2546,6 +2647,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):max_subagent_workers=self.max_subagent_workers,library_resolver=library_resolver,web_search_description=primary_search_description,+ max_fetches_per_topic=self.max_fetches_per_topic,))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__.pyindex 4540fa2bc8..e43d0409ab 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@@ -20,7 +20,7 @@ Modes:Each tool registers fetched URLs in the strategy's``SearchResultsCollector`` for citation tracking, returning the result as-``[N] Title: ...\\nURL: ...\\n\\n<body>`` exactly like the original+``[N] Title: ...\nURL: ...\n\n<body>`` exactly like the originalin-strategy implementation, so downstream prompt formatting is unchanged."""@@ -39,6 +39,7 @@ from local_deep_research.security import (redact_url_for_log,sanitize_error_for_agent,)+from local_deep_research.utilities.type_utils import unwrap_settingfrom local_deep_research.utilities.llm_utils import invoke_llm_syncfrom .library_resolver import (@@ -63,6 +64,91 @@ FETCH_MODES = ("summary_focus_query",)+# Default call budget for fetch_content per subagent (and lead agent) per topic.+# Prevents autonomous agents from exhausting recursion limits on fetches.+DEFAULT_MAX_FETCHES_PER_TOPIC = 2+++def _read_max_fetches_setting(+ settings_snapshot: dict | None,+ default: int = DEFAULT_MAX_FETCHES_PER_TOPIC,+) -> int:+ """Read the ``search.fetch.max_per_topic`` setting from a settings snapshot.++ Retained as a fallback for direct callers of ``build_fetch_tool`` outside+ ``LangGraphAgentStrategy`` (which passes ``max_fetches`` explicitly).++ Returns the configured non-negative integer limit, or default if missing/invalid.+ Negative values fall back to default, and values above 50 are clamped to 50.+ 0 means unlimited fetches.+ """+ if not settings_snapshot:+ return default+ val = settings_snapshot.get("search.fetch.max_per_topic")+ if val is None:+ return default+ unwrapped = unwrap_setting(val)+ try:+ limit = int(unwrapped)+ if limit < 0:+ return default+ return min(50, limit)+ except (TypeError, ValueError):+ return default+++_warned_collector_missing_fetch_cap = False+++def _warn_collector_lacks_fetch_recording() -> None:+ global _warned_collector_missing_fetch_cap+ if not _warned_collector_missing_fetch_cap:+ _warned_collector_missing_fetch_cap = True+ logger.warning(+ "Collector does not implement try_record_fetch; fetch content budget cap is disabled."+ )+++def _check_and_record_fetch(+ collector: Any,+ max_fetches: int,+ subagent_id: str | None = None,+) -> tuple[str | None, int | None]:+ """Check if the fetch budget has been exhausted. If not, record the fetch attempt.++ Requires ``try_record_fetch`` on the collector (provided by+ ``SearchResultsCollector``). If collector is None, budget enforcement is skipped.+ If collector does not implement ``try_record_fetch``, a one-time warning is logged.++ Accounting: Only invocations that reach the network consume a slot. Pre-resolved+ local library reads and egress policy denials do not consume budget slots.++ Returns:+ (budget_err, current_count)+ budget_err is an informative error string if budget is exhausted, or None if the fetch can proceed.+ current_count is the current fetch count for this subagent/topic, or None.+ """+ if collector is not None and hasattr(collector, "try_record_fetch"):+ try:+ allowed, count = collector.try_record_fetch(+ max_fetches, subagent_id=subagent_id+ )+ except TypeError:+ allowed, count = collector.try_record_fetch(max_fetches)+ if not allowed:+ logger.warning(+ f"fetch_content call budget exhausted ({count}/{max_fetches}) for this topic"+ )+ return (+ f"Fetch content budget exhausted ({count}/{max_fetches}) for this topic. "+ "Rely on search snippets or synthesize your findings with the information already gathered.",+ count,+ )+ return None, count+ if collector is not None:+ _warn_collector_lacks_fetch_recording()+ return None, None+def _register_in_collector(collector: Any,@@ -291,13 +377,16 @@ def _fetch_raw_content(egress_context: Any,settings_snapshot: dict | None,mode_label: str,-) -> tuple[dict | None, str, str | None]:+ max_fetches: int | None = None,+ subagent_id: str | None = None,+) -> tuple[dict | None, str, str | None, int | None]:"""Pre-resolve non-network URL shapes or fetch via HTTP.Returns:- (result, final_url, error_string)- If error_string is not None, a pre-resolution error occurred (already- scrubbed) and should be returned immediately by the fetch tool.+ (result, final_url, error_string, current_count)+ If error_string is not None, a pre-resolution error or budget exhaustion+ occurred (already scrubbed) and should be returned immediately by the fetch tool.+ current_count is the current fetch count if a network fetch was recorded, or None."""from local_deep_research.content_fetcher import ContentFetcher@@ -306,10 +395,11 @@ def _fetch_raw_content(if pre is not None:kind, payload = preif kind == _KIND_ERROR:- return None, url, sanitize_error_for_agent(payload)+ return None, url, sanitize_error_for_agent(payload), Noneif kind == _KIND_RESULT:# A local library document was resolved directly from the user DB.# Skip both the egress gate (local read) and ContentFetcher (no HTTP).+ # It does not consume a network fetch budget slot.result = payloadurl = result.get("url") or urllogger.info(@@ -319,14 +409,24 @@ def _fetch_raw_content(else: # _KIND_REWRITTEN — citation marker resolved to a URLurl = payload+ current_count: int | None = Noneif result is None:# Either no pre-resolution or a citation-marker rewrite —# run the normal HTTP path. Per-URL egress gate (pre-fetch)# + ContentFetcher's own per-redirect gate both raise- # PolicyDeniedError on an out-of-scope URL. Run the gate- # INSIDE the try so the denial is returned as a recoverable- # tool message.+ # PolicyDeniedError on an out-of-scope URL.+ # Check the egress gate BEFORE recording the fetch so that+ # egress denials do not consume budget slots._enforce_url_policy(url, egress_context)++ # Egress check passed! Only count fetches that reach the network.+ if max_fetches is not None:+ budget_err, current_count = _check_and_record_fetch(+ collector, max_fetches, subagent_id=subagent_id+ )+ if budget_err is not None:+ return None, url, budget_err, current_count+enable_js = _read_js_rendering_setting(settings_snapshot)with ContentFetcher(timeout=CONTENT_FETCH_TIMEOUT,@@ -335,7 +435,7 @@ def _fetch_raw_content() as fetcher:result = fetcher.fetch(url, max_length=CONTENT_MAX_LENGTH)- return result, url, None+ return result, url, None, current_countdef _make_full_fetch_tool(@@ -343,10 +443,23 @@ def _make_full_fetch_tool(settings_snapshot: dict | None = None,egress_context: Any = None,library_resolver: Any = None,+ max_fetches: int | None = None,+ subagent_id: str | None = None,):mode_label = "full"+ limit = (+ max_fetches+ if max_fetches is not None+ else _read_max_fetches_setting(settings_snapshot)+ )+ desc = (+ "Download and read the full text content from a URL. "+ "Use when search snippets aren't detailed enough."+ )+ if limit > 0:+ desc += f" (Up to {limit} page fetches allowed per topic.)"- @tool+ @tool("fetch_content", description=desc)def fetch_content(url: str) -> str:"""Download and read the full text content from a URL. Use when search snippets aren't detailed enough."""from local_deep_research.security.egress.policy import (@@ -354,13 +467,15 @@ def _make_full_fetch_tool()try:- result, url, err_msg = _fetch_raw_content(+ result, url, err_msg, current_count = _fetch_raw_content(url,library_resolver,collector,egress_context,settings_snapshot,mode_label,+ max_fetches=limit,+ subagent_id=subagent_id,)if err_msg is not None:return err_msg@@ -371,7 +486,10 @@ def _make_full_fetch_tool(cite_idx = _register_in_collector(collector, url, title, content)- return f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{content}"+ msg = f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{content}"+ if limit > 0 and current_count is not None:+ msg += f"\n\n({current_count} of {limit} page fetches used)"+ return msg# result['error'] comes from ContentFetcher, which returns a# raw str(exception) — scrub it (and the url) before this# reaches the agent/LLM and user-visible output (#4633).@@ -418,6 +536,8 @@ def _make_summary_fetch_tool(settings_snapshot: dict | None = None,egress_context: Any = None,library_resolver: Any = None,+ max_fetches: int | None = None,+ subagent_id: str | None = None,):"""Build the summary-mode fetch tool.@@ -428,8 +548,20 @@ def _make_summary_fetch_tool(template = SUMMARY_FOCUS_QUERY_PROMPT if use_query else SUMMARY_FOCUS_PROMPTmode_label = "summary_focus_query" if use_query else "summary_focus"+ limit = (+ max_fetches+ if max_fetches is not None+ else _read_max_fetches_setting(settings_snapshot)+ )+ desc = (+ "Fetch a URL and return only the spans of text relevant to `focus`. "+ "Pass the specific question or claim you want answered as `focus` — "+ "the tool will quote relevant facts verbatim and discard unrelated content."+ )+ if limit > 0:+ desc += f" (Up to {limit} page fetches allowed per topic.)"- @tool+ @tool("fetch_content", description=desc)def fetch_content(url: str, focus: str) -> str:"""Fetch a URL and return only the spans of text relevant to ``focus``.Pass the specific question or claim you want answered as ``focus`` —@@ -440,13 +572,15 @@ def _make_summary_fetch_tool()try:- result, url, err_msg = _fetch_raw_content(+ result, url, err_msg, current_count = _fetch_raw_content(url,library_resolver,collector,egress_context,settings_snapshot,mode_label,+ max_fetches=limit,+ subagent_id=subagent_id,)if err_msg is not None:return err_msg@@ -538,7 +672,10 @@ def _make_summary_fetch_tool(return f"NOT RELEVANT (no spans matched focus at {url})"cite_idx = _register_in_collector(collector, url, title, summary)- return f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{summary}"+ msg = f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{summary}"+ if limit > 0 and current_count is not None:+ msg += f"\n\n({current_count} of {limit} page fetches used)"+ return msgexcept PolicyDeniedError as exc:# Recoverable per-URL denial — return a tool message so both the# lead agent and pooled subagents handle it identically and the@@ -578,6 +715,8 @@ def build_fetch_tool(settings_snapshot: dict | None = None,egress_context: Any = None,library_resolver: Any = None,+ max_fetches: int | None = None,+ subagent_id: str | None = None,):"""Build the agent-facing ``fetch_content`` tool for *mode*.@@ -610,6 +749,8 @@ def build_fetch_tool(settings_snapshot=settings_snapshot,egress_context=egress_context,library_resolver=library_resolver,+ max_fetches=max_fetches,+ subagent_id=subagent_id,)if mode == "summary_focus":if model is None:@@ -621,6 +762,8 @@ def build_fetch_tool(settings_snapshot=settings_snapshot,egress_context=egress_context,library_resolver=library_resolver,+ max_fetches=max_fetches,+ subagent_id=subagent_id,)if mode == "summary_focus_query":if model is None:@@ -634,10 +777,17 @@ def build_fetch_tool(settings_snapshot=settings_snapshot,egress_context=egress_context,library_resolver=library_resolver,+ max_fetches=max_fetches,+ subagent_id=subagent_id,)raise ValueError(f"Unknown fetch mode {mode!r}; expected one of {FETCH_MODES}")-__all__ = ["FETCH_MODES", "build_fetch_tool", "make_library_resolver"]+__all__ = [+ "DEFAULT_MAX_FETCHES_PER_TOPIC",+ "FETCH_MODES",+ "build_fetch_tool",+ "make_library_resolver",+]diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex b3202ba8eb..b75e5d7e08 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -975,6 +975,20 @@"value": "summary_focus_query","visible": true},+ "search.fetch.max_per_topic": {+ "category": "search_parameters",+ "description": "Maximum number of page content fetches (fetch_content calls) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets).",+ "editable": true,+ "max_value": 50,+ "min_value": 0,+ "name": "Max Fetches Per Topic",+ "options": null,+ "step": 1,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 2,+ "visible": true+ },"search.iterations": {"category": null,"description": "Number of search-and-refine cycles to run. Each iteration generates follow-up questions based on previous results to progressively deepen the research. More iterations yield better coverage but increase search and LLM API usage.",diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.pyindex 7cd4dfb634..6ca3406217 100644--- a/tests/advanced_search_system/tools/test_fetch_modes.py+++ b/tests/advanced_search_system/tools/test_fetch_modes.py@@ -1181,3 +1181,333 @@ def test_register_in_collector_raises_when_unresolvable():)with pytest.raises(RuntimeError, match="Failed to register fetched URL"):_register_in_collector(collector, "http://a.com", "A", "body")+++# ---------------------------------------------------------------------------+# Fetch budget cap per topic/subsection (#5815).+# ---------------------------------------------------------------------------+++def test_full_mode_enforces_fetch_budget_cap():+ """When the fetch budget is exhausted, full-mode fetch returns a message+ without calling ContentFetcher or making network calls."""+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector, max_fetches=2)++ cm = _fetcher_cm(title="Page", content="Page content")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke({"url": "https://example.com/1"})+ out2 = tool.invoke({"url": "https://example.com/2"})+ out3 = tool.invoke({"url": "https://example.com/3"})++ assert "Title: Page" in out1+ assert out1.endswith("(1 of 2 page fetches used)")+ assert "Title: Page" in out2+ assert out2.endswith("(2 of 2 page fetches used)")+ assert "Fetch content budget exhausted (2/2) for this topic." in out3+ assert "Rely on search snippets" in out3+ # Only 2 network fetches were performed+ assert cm.__enter__.return_value.fetch.call_count == 2+ assert collector.fetch_count == 2++[email protected]("fetch_mode", ["summary_focus", "summary_focus_query"])+def test_summary_mode_enforces_fetch_budget_cap(fetch_mode):+ """When the fetch budget is exhausted, summary-mode fetch (both summary_focus+ and summary_focus_query) returns a message without calling ContentFetcher+ or model.invoke."""+ collector = SearchResultsCollector([])+ model = _model_returning("Extracted summary")+ tool = build_fetch_tool(+ fetch_mode,+ collector,+ model=model,+ overall_query="What is quantum computing?",+ max_fetches=2,+ )++ cm = _fetcher_cm(title="Page", content="Page content")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke({"url": "https://example.com/1", "focus": "fact 1"})+ out2 = tool.invoke({"url": "https://example.com/2", "focus": "fact 2"})+ out3 = tool.invoke({"url": "https://example.com/3", "focus": "fact 3"})++ assert "Extracted summary" in out1+ assert out1.endswith("(1 of 2 page fetches used)")+ assert "Extracted summary" in out2+ assert out2.endswith("(2 of 2 page fetches used)")+ assert "Fetch content budget exhausted (2/2) for this topic." in out3+ assert cm.__enter__.return_value.fetch.call_count == 2+ assert model.invoke.call_count == 2+ assert collector.fetch_count == 2+++def test_fetch_budget_cap_zero_allows_unlimited():+ """Setting max_fetches=0 disables the cap and allows unlimited fetches."""+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector, max_fetches=0)++ cm = _fetcher_cm(title="Page", content="Page content")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ for i in range(10):+ out = tool.invoke({"url": f"https://example.com/{i}"})+ assert "Title: Page" in out++ assert cm.__enter__.return_value.fetch.call_count == 10+ assert collector.fetch_count == 10+++def test_fetch_budget_cap_resets_with_collector_reset():+ """Calling collector.reset() resets the fetch count, allowing new fetches."""+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector, max_fetches=1)++ cm = _fetcher_cm(title="Page", content="Page content")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke({"url": "https://example.com/1"})+ out2 = tool.invoke({"url": "https://example.com/2"})+ assert "Title: Page" in out1+ assert "Fetch content budget exhausted (1/1)" in out2++ collector.reset()+ assert collector.fetch_count == 0++ out3 = tool.invoke({"url": "https://example.com/3"})+ assert "Title: Page" in out3+ assert collector.fetch_count == 1+++def test_fetch_budget_reads_from_settings_snapshot():+ """When max_fetches is not explicitly passed, the limit is read from settings_snapshot."""+ collector = SearchResultsCollector([])+ settings = {"search.fetch.max_per_topic": {"value": 1}}+ tool = build_fetch_tool("full", collector, settings_snapshot=settings)++ cm = _fetcher_cm(title="Page", content="Page content")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke({"url": "https://example.com/1"})+ out2 = tool.invoke({"url": "https://example.com/2"})++ assert "Title: Page" in out1+ assert "Fetch content budget exhausted (1/1)" in out2+++def test_fetch_budget_skipped_for_collector_without_try_record_fetch():+ """Collectors lacking try_record_fetch (or None) skip budget enforcement."""++ class LegacyCollector:+ def __init__(self):+ self.results = []++ def find_or_add_result(self, result, engine_name):+ return 1++ collector = LegacyCollector()+ tool = build_fetch_tool("full", collector, max_fetches=1)++ cm = _fetcher_cm(title="Page", content="Page content")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke({"url": "https://example.com/1"})+ out2 = tool.invoke({"url": "https://example.com/2"})++ assert "Title: Page" in out1+ assert "Title: Page" in out2+++def test_fetch_budget_consumed_on_failed_fetch():+ """Option A accounting: failed network fetches consume a budget slot."""+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector, max_fetches=1)++ cm = _fetcher_cm(status="error")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke({"url": "https://example.com/fail"})+ out2 = tool.invoke({"url": "https://example.com/next"})++ assert "Failed to fetch" in out1+ assert collector.fetch_count == 1+ assert "Fetch content budget exhausted (1/1) for this topic." in out2+++def test_fetch_budget_consumed_on_guard_empty_content():+ """Option A accounting: empty page content (Guard 1 returning NOT RELEVANT)+ consumes a budget slot because the invocation expended an agent turn."""+ collector = SearchResultsCollector([])+ model = _model_returning("summary")+ tool = build_fetch_tool(+ "summary_focus", collector, model=model, max_fetches=1+ )++ cm = _fetcher_cm(title="Empty", content=" \n ")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke(+ {"url": "https://example.com/empty", "focus": "fact"}+ )+ out2 = tool.invoke({"url": "https://example.com/next", "focus": "fact"})++ assert "NOT RELEVANT (no extractable content" in out1+ assert collector.fetch_count == 1+ assert "Fetch content budget exhausted (1/1) for this topic." in out2+++def test_fetch_budget_consumed_on_guard_no_matching_spans():+ """Option A accounting: empty summary from model (Guard 2 returning NOT RELEVANT)+ consumes a budget slot because the invocation expended an agent turn."""+ collector = SearchResultsCollector([])+ model = _model_returning("") # Empty response => Guard 2+ tool = build_fetch_tool(+ "summary_focus", collector, model=model, max_fetches=1+ )++ cm = _fetcher_cm(title="Page", content="Some page text")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out1 = tool.invoke(+ {"url": "https://example.com/mismatch", "focus": "unrelated fact"}+ )+ out2 = tool.invoke({"url": "https://example.com/next", "focus": "fact"})++ assert "NOT RELEVANT (no spans matched focus" in out1+ assert collector.fetch_count == 1+ assert "Fetch content budget exhausted (1/1) for this topic." in out2+++def test_fetch_tool_description_contains_budget_cap():+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector, max_fetches=2)+ assert "(Up to 2 page fetches allowed per topic.)" in tool.description++ tool_unlimited = build_fetch_tool("full", collector, max_fetches=0)+ assert "page fetches allowed per topic" not in tool_unlimited.description+++def test_policy_denied_fetch_does_not_consume_budget():+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector, max_fetches=1)++ with patch(+ "local_deep_research.advanced_search_system.tools.fetch._enforce_url_policy"+ ) as mock_enforce:+ from local_deep_research.security.egress.policy import PolicyDeniedError++ mock_enforce.side_effect = PolicyDeniedError(+ MagicMock(reason="host_not_allowed"), target="https://blocked.com"+ )++ out = tool.invoke({"url": "https://blocked.com"})+ assert (+ "Cannot fetch https://blocked.com: blocked by egress policy" in out+ )+ assert collector.fetch_count == 0++ # Budget slot remains available+ cm = _fetcher_cm(title="Allowed", content="Allowed content")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out2 = tool.invoke({"url": "https://allowed.com"})+ assert "Title: Allowed" in out2+ assert out2.endswith("(1 of 1 page fetches used)")+ assert collector.fetch_count == 1+++def test_library_resolution_does_not_consume_budget():+ collector = SearchResultsCollector([])+ tool = build_fetch_tool(+ "full",+ collector,+ max_fetches=1,+ )+ with patch(+ "local_deep_research.advanced_search_system.tools.fetch._try_resolve_url",+ return_value=(+ "result",+ {+ "title": "Local Doc",+ "content": "Local document text",+ "status": "success",+ },+ ),+ ):+ out = tool.invoke({"url": "/library/document/12345"})+ assert "Title: Local Doc" in out+ assert "(1 of 1 page fetches used)" not in out+ assert collector.fetch_count == 0++ # Budget slot is still intact for network fetch+ cm = _fetcher_cm(title="Network", content="Network page")+ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out2 = tool.invoke({"url": "https://example.com/net"})+ assert "Title: Network" in out2+ assert out2.endswith("(1 of 1 page fetches used)")+ assert collector.fetch_count == 1+++def test_collector_without_try_record_fetch_warns_once(loguru_caplog):+ import local_deep_research.advanced_search_system.tools.fetch as fetch_mod++ fetch_mod._warned_collector_missing_fetch_cap = False++ with loguru_caplog.at_level("WARNING"):+ fetch_mod._warn_collector_lacks_fetch_recording()+ fetch_mod._warn_collector_lacks_fetch_recording()++ records = [+ r+ for r in loguru_caplog.records+ if "does not implement try_record_fetch" in r.message+ ]+ assert len(records) == 1+++def test_read_max_fetches_setting_clamping():+ from local_deep_research.advanced_search_system.tools.fetch import (+ _read_max_fetches_setting,+ DEFAULT_MAX_FETCHES_PER_TOPIC,+ )++ assert _read_max_fetches_setting(None) == DEFAULT_MAX_FETCHES_PER_TOPIC+ assert _read_max_fetches_setting({}) == DEFAULT_MAX_FETCHES_PER_TOPIC+ assert (+ _read_max_fetches_setting({"search.fetch.max_per_topic": {"value": 5}})+ == 5+ )+ assert (+ _read_max_fetches_setting({"search.fetch.max_per_topic": {"value": 0}})+ == 0+ )+ assert (+ _read_max_fetches_setting(+ {"search.fetch.max_per_topic": {"value": 100}}+ )+ == 50+ )+ assert (+ _read_max_fetches_setting({"search.fetch.max_per_topic": {"value": -5}})+ == DEFAULT_MAX_FETCHES_PER_TOPIC+ )+ assert (+ _read_max_fetches_setting(+ {"search.fetch.max_per_topic": {"value": "invalid"}}+ )+ == DEFAULT_MAX_FETCHES_PER_TOPIC+ )diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex d3f6301fe7..bb973ed52f 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -8876,6 +8876,20 @@],"visible": true},+ "search.fetch.max_per_topic": {+ "category": "search_parameters",+ "description": "Maximum number of page content fetches (fetch_content calls) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets).",+ "editable": true,+ "max_value": 50,+ "min_value": 0,+ "name": "Max Fetches Per Topic",+ "options": null,+ "step": 1,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 2,+ "visible": true+ },"search.fetch.mode": {"category": "search_parameters","description": "Controls the LangGraph agent's fetch_content tool. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes the tool entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex 1bff2ce6bf..3876a89447 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -3428,6 +3428,610 @@ class TestHeartbeatMessage:assert "1 source gathered" in out+ def test_heartbeat_includes_single_fetched_page(self):+ strategy = self._make_strategy(links=[{"link": "http://a.com"}])+ strategy._tool_names = ["web_search"]+ strategy.collector.record_fetch()++ out = strategy._heartbeat_message(2)++ assert (+ "1 source gathered · 1 page fetch attempt · selecting next action from the web (SearXNG)"+ in out+ )++ def test_heartbeat_includes_multiple_fetched_pages(self):+ strategy = self._make_strategy(+ links=[{"link": "http://a.com"}, {"link": "http://b.com"}]+ )+ strategy._tool_names = ["web_search"]+ strategy.collector.record_fetch()+ strategy.collector.record_fetch()+ strategy.collector.record_fetch()++ out = strategy._heartbeat_message(3)++ assert (+ "2 sources gathered · 3 page fetch attempts · selecting next action from the web (SearXNG)"+ in out+ )++ def test_heartbeat_zero_sources_includes_fetched_pages(self):+ strategy = self._make_strategy()+ strategy._tool_names = ["web_search"]+ strategy.collector.record_fetch()++ out = strategy._heartbeat_message(1)++ assert (+ out+ == "Step 1 · planning approach with 1 research tool available… · 1 page fetch attempt"+ )+++class TestSearchResultsCollectorFetchTracking:+ """Test fetch counting and budget check in SearchResultsCollector."""++ def test_collector_fetch_count_and_try_record_fetch(self):+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ SearchResultsCollector,+ )++ collector = SearchResultsCollector([])+ assert collector.fetch_count == 0++ # try_record_fetch under budget+ allowed, count = collector.try_record_fetch(2)+ assert allowed is True+ assert count == 1+ assert collector.fetch_count == 1++ allowed, count = collector.try_record_fetch(2)+ assert allowed is True+ assert count == 2+ assert collector.fetch_count == 2++ # Exceeds budget+ allowed, count = collector.try_record_fetch(2)+ assert allowed is False+ assert count == 2+ assert collector.fetch_count == 2++ # Reset clears fetch count+ collector.reset()+ assert collector.fetch_count == 0++ # Allows again after reset+ allowed, count = collector.try_record_fetch(2)+ assert allowed is True+ assert count == 1++ def test_strategy_loads_max_fetches_setting(self):+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ )++ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": 8}},+ )+ assert strategy.max_fetches_per_topic == 8++ def test_strategy_default_max_fetches(self):+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ DEFAULT_MAX_FETCHES_PER_TOPIC,+ )++ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={},+ )+ assert strategy.max_fetches_per_topic == DEFAULT_MAX_FETCHES_PER_TOPIC++ def test_build_tools_honors_mutated_max_fetches(self):+ """Verify single-read contract: mutating strategy.max_fetches_per_topic+ is honored by _build_tools without redundant re-reading from snapshot."""+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ )++ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": 5}},+ )+ assert strategy.max_fetches_per_topic == 5+ strategy.max_fetches_per_topic = 2++ with (+ patch(+ "local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy.build_fetch_tool"+ ) as mock_build_fetch,+ patch(+ "local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy._make_research_subtopic_tool"+ ) as mock_make_sub,+ ):+ mock_build_fetch.return_value = MagicMock(name="fetch_content")+ mock_make_sub.return_value = MagicMock(name="research_subtopic")+ strategy._build_tools("overall query")++ assert mock_build_fetch.call_args.kwargs["max_fetches"] == 2+ assert mock_make_sub.call_args.kwargs["max_fetches_per_topic"] == 2++ def test_subagent_budget_wiring_and_shared_collector(self):+ """Verify subagent wiring:+ (a) the sub fetch tool is built with configured budget from strategy,+ (b) lead tool and subagent tool both draw from shared SearchResultsCollector+ and cap at max_fetches,+ (c) collector.reset() resets the budget allowance."""+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ )++ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": 2}},+ )+ assert strategy.max_fetches_per_topic == 2++ captured_sub_tools = []++ def fake_create_agent(model, tools, **kwargs):+ captured_sub_tools.extend(tools)+ agent = MagicMock()+ agent.invoke.return_value = {+ "messages": [MagicMock(content="findings")]+ }+ return agent++ with patch(+ "langchain.agents.create_agent", side_effect=fake_create_agent+ ):+ tools = strategy._build_tools("query")+ lead_fetch = next(t for t in tools if t.name == "fetch_content")+ research_subtopic = next(+ t for t in tools if t.name == "research_subtopic"+ )+ # Invoke subtopic to trigger creation of subagent tools+ research_subtopic.invoke({"subtopics": ["subtopic 1"]})++ sub_fetch = next(+ t for t in captured_sub_tools if t.name == "fetch_content"+ )++ def make_cm(title="Page", content="Body text"):+ fetcher = MagicMock()+ fetcher.fetch.return_value = {+ "status": "success",+ "title": title,+ "content": content,+ }+ cm = MagicMock()+ cm.__enter__.return_value = fetcher+ cm.__exit__.return_value = False+ return cm++ cm = make_cm()+ strategy.model.invoke.return_value = MagicMock(content="summary text")++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher",+ return_value=cm,+ ):+ # Lead agent gets up to 2 fetches+ out1 = lead_fetch.invoke(+ {"url": "https://example.com/lead", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in out1+ assert strategy.collector.fetch_count == 1++ out2 = lead_fetch.invoke(+ {"url": "https://example.com/lead2", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in out2+ assert strategy.collector.fetch_count == 2++ out3 = lead_fetch.invoke(+ {"url": "https://example.com/lead3", "focus": "fact"}+ )+ assert "Fetch content budget exhausted (2/2)" in out3+ assert strategy.collector.fetch_count == 2++ # Subagent has its own independent budget (2 slots)+ out4 = sub_fetch.invoke(+ {"url": "https://example.com/sub", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in out4+ assert strategy.collector.fetch_count == 3++ out5 = sub_fetch.invoke(+ {"url": "https://example.com/sub2", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in out5+ assert strategy.collector.fetch_count == 4++ out6 = sub_fetch.invoke(+ {"url": "https://example.com/sub3", "focus": "fact"}+ )+ assert "Fetch content budget exhausted (2/2)" in out6+ assert strategy.collector.fetch_count == 4++ # collector.reset() resets count (subsection boundary)+ strategy.collector.reset()+ assert strategy.collector.fetch_count == 0++ # Fetches can proceed again after reset+ out7 = sub_fetch.invoke(+ {"url": "https://example.com/sub4", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in out7+ assert strategy.collector.fetch_count == 1++ def test_subtopics_and_lead_agent_have_per_agent_fetch_budget(self):+ """Each subagent and the lead agent have their own independent budget:+ With search.fetch.max_per_topic = 2, when multiple subtopics are investigated,+ each subagent gets up to 2 fetches without starving other subagents.+ The lead agent also has its own limit of 2."""+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ )++ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": 2}},+ )+ assert strategy.max_fetches_per_topic == 2+ # Use 1 worker to execute subtopics sequentially and deterministically+ strategy.max_subagent_workers = 1++ subagent_fetch_results = {}++ def fake_create_agent(model, tools, **kwargs):+ fetch_tool = next(t for t in tools if t.name == "fetch_content")+ agent = MagicMock()++ def fake_invoke(inputs, config=None):+ topic = inputs["messages"][0]["content"]+ # Each subagent attempts to fetch 3 URLs for its topic (cap is 2)+ res1 = fetch_tool.invoke(+ {+ "url": f"https://example.com/{topic}/page1",+ "focus": "fact",+ }+ )+ res2 = fetch_tool.invoke(+ {+ "url": f"https://example.com/{topic}/page2",+ "focus": "fact",+ }+ )+ res3 = fetch_tool.invoke(+ {+ "url": f"https://example.com/{topic}/page3",+ "focus": "fact",+ }+ )+ subagent_fetch_results[topic] = [res1, res2, res3]+ return {+ "messages": [MagicMock(content=f"Findings for {topic}")]+ }++ agent.invoke.side_effect = fake_invoke+ return agent++ fetcher_mock = MagicMock()+ fetcher_mock.fetch.return_value = {+ "status": "success",+ "title": "Mock Title",+ "content": "Mock Content",+ }+ cm = MagicMock()+ cm.__enter__.return_value = fetcher_mock+ cm.__exit__.return_value = False++ strategy.model.invoke.return_value = MagicMock(+ content="Summary of content"+ )++ with (+ patch(+ "langchain.agents.create_agent", side_effect=fake_create_agent+ ),+ patch(+ "local_deep_research.content_fetcher.ContentFetcher",+ return_value=cm,+ ),+ ):+ tools = strategy._build_tools("overall query")+ research_subtopic = next(+ t for t in tools if t.name == "research_subtopic"+ )+ lead_fetch = next(t for t in tools if t.name == "fetch_content")++ # Run 2 subtopics: "subtopic_A" and "subtopic_B"+ research_subtopic.invoke(+ {"subtopics": ["subtopic_A", "subtopic_B"]}+ )++ # Subtopic A consumes its 2 slots, 3rd is exhausted+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_A"][0]+ )+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_A"][1]+ )+ assert (+ "Fetch content budget exhausted (2/2) for this topic."+ in subagent_fetch_results["subtopic_A"][2]+ )++ # Subtopic B is NOT starved by Subtopic A; it gets its own 2 slots+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_B"][0]+ )+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_B"][1]+ )+ assert (+ "Fetch content budget exhausted (2/2) for this topic."+ in subagent_fetch_results["subtopic_B"][2]+ )++ # Total network fetches across subtopics is 4 (2 for A + 2 for B)+ assert fetcher_mock.fetch.call_count == 4+ assert strategy.collector.fetch_count == 4++ # Lead agent gets its own 2 slots as well+ lead_res1 = lead_fetch.invoke(+ {"url": "https://example.com/lead/page1", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in lead_res1++ lead_res2 = lead_fetch.invoke(+ {"url": "https://example.com/lead/page2", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in lead_res2++ lead_res3 = lead_fetch.invoke(+ {"url": "https://example.com/lead/page3", "focus": "fact"}+ )+ assert (+ "Fetch content budget exhausted (2/2) for this topic."+ in lead_res3+ )+ assert fetcher_mock.fetch.call_count == 6+ assert strategy.collector.fetch_count == 6++ # Resetting the collector (subsection boundary) resets the counters+ strategy.collector.reset()+ assert strategy.collector.fetch_count == 0++ # After reset, a fetch can succeed again+ after_reset = lead_fetch.invoke(+ {"url": "https://example.com/next_section", "focus": "fact"}+ )+ assert "Fetch content budget exhausted" not in after_reset+ assert fetcher_mock.fetch.call_count == 7+ assert strategy.collector.fetch_count == 1++ def test_observation_milestone_suppresses_budget_exhausted(self):+ """Verify that _format_tool_observation_milestone suppresses+ 'Fetch content budget exhausted' messages for fetch_content."""+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ )++ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={},+ )+ msg = MagicMock()+ msg.name = "fetch_content"+ msg.content = "Fetch content budget exhausted (2/2) for this topic."+ res = strategy._observation_event(msg)+ assert res is None++ def test_consecutive_research_subtopic_calls_have_independent_budgets(self):+ """Verify that consecutive research_subtopic calls (e.g. second delegation wave)+ each get independent per-invocation subagent budgets instead of colliding+ on batch-relative indices or inheriting exhausted budgets."""+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ )++ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": 2}},+ )+ strategy.max_subagent_workers = 1++ subagent_fetch_results = {}++ def fake_create_agent(model, tools, **kwargs):+ fetch_tool = next(t for t in tools if t.name == "fetch_content")+ agent = MagicMock()++ def fake_invoke(inputs, config=None):+ topic = inputs["messages"][0]["content"]+ # Each subagent attempts 3 fetches (cap is 2)+ res1 = fetch_tool.invoke(+ {+ "url": f"https://example.com/{topic}/page1",+ "focus": "fact",+ }+ )+ res2 = fetch_tool.invoke(+ {+ "url": f"https://example.com/{topic}/page2",+ "focus": "fact",+ }+ )+ res3 = fetch_tool.invoke(+ {+ "url": f"https://example.com/{topic}/page3",+ "focus": "fact",+ }+ )+ subagent_fetch_results[topic] = [res1, res2, res3]+ return {+ "messages": [MagicMock(content=f"Findings for {topic}")]+ }++ agent.invoke.side_effect = fake_invoke+ return agent++ fetcher_mock = MagicMock()+ fetcher_mock.fetch.return_value = {+ "status": "success",+ "title": "Mock Title",+ "content": "Mock Content",+ }+ cm = MagicMock()+ cm.__enter__.return_value = fetcher_mock+ cm.__exit__.return_value = False++ strategy.model.invoke.return_value = MagicMock(+ content="Summary of content"+ )++ with (+ patch(+ "langchain.agents.create_agent", side_effect=fake_create_agent+ ),+ patch(+ "local_deep_research.content_fetcher.ContentFetcher",+ return_value=cm,+ ),+ ):+ tools = strategy._build_tools("overall query")+ research_subtopic = next(+ t for t in tools if t.name == "research_subtopic"+ )++ # First delegation wave: subtopics A and B+ research_subtopic.invoke(+ {"subtopics": ["subtopic_A", "subtopic_B"]}+ )++ # Both subtopics in wave 1 used their 2 allowed fetches+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_A"][0]+ )+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_A"][1]+ )+ assert (+ "Fetch content budget exhausted (2/2) for this topic."+ in subagent_fetch_results["subtopic_A"][2]+ )++ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_B"][0]+ )+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_B"][1]+ )+ assert (+ "Fetch content budget exhausted (2/2) for this topic."+ in subagent_fetch_results["subtopic_B"][2]+ )++ assert fetcher_mock.fetch.call_count == 4+ assert strategy.collector.fetch_count == 4++ # Second delegation wave: subtopics C and D (WITHOUT collector.reset())+ research_subtopic.invoke(+ {"subtopics": ["subtopic_C", "subtopic_D"]}+ )++ # Subtopics C and D in wave 2 must NOT start exhausted+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_C"][0]+ )+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_C"][1]+ )+ assert (+ "Fetch content budget exhausted (2/2) for this topic."+ in subagent_fetch_results["subtopic_C"][2]+ )++ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_D"][0]+ )+ assert (+ "Fetch content budget exhausted"+ not in subagent_fetch_results["subtopic_D"][1]+ )+ assert (+ "Fetch content budget exhausted (2/2) for this topic."+ in subagent_fetch_results["subtopic_D"][2]+ )++ # Total network fetches across both waves is 8 (2 per subtopic * 4 subtopics)+ assert fetcher_mock.fetch.call_count == 8+ assert strategy.collector.fetch_count == 8++ # Collector reset clears all counts+ strategy.collector.reset()+ assert strategy.collector.fetch_count == 0++ def test_strategy_max_fetches_clamping(self):+ """Values < 0 fall back to default, > 50 clamp to 50, and 0 is unlimited."""+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+ DEFAULT_MAX_FETCHES_PER_TOPIC,+ )++ strat_high = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": 100}},+ )+ assert strat_high.max_fetches_per_topic == 50++ strat_neg = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": -5}},+ )+ assert strat_neg.max_fetches_per_topic == DEFAULT_MAX_FETCHES_PER_TOPIC++ strat_zero = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.fetch.max_per_topic": {"value": 0}},+ )+ assert strat_zero.max_fetches_per_topic == 0+# ---------------------------------------------------------------------------# Citation offset for detailed report mode