~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(langgraph-agent): per-subagent deadline from actual start + expose max_subagent_workers (#5014) (#5091)
Sd8935a7e1974
diff --git a/changelog.d/5014.bugfix.md b/changelog.d/5014.bugfix.mdnew file mode 100644index 0000000000..ae085c51a5--- /dev/null+++ b/changelog.d/5014.bugfix.md@@ -0,0 +1 @@+langgraph-agent: fix subagents falsely marked "timed out" by the shared drain-loop timer (#5014). Each subagent now gets a per-task deadline measured from its *actual* start time, so a queued subagent that begins late is no longer killed by a shared overall budget. The timeout message reports the subagent's real elapsed time (not a hard-coded 1800s), and a generous overall safety cap only fires for genuinely hung tasks. Also exposes `langgraph_agent.max_subagent_workers` as a user setting so the parallel-subagent pool size can match the LLM backend's parallel-request capacity (Ollama/LMStudio/llama.cpp, OpenAI tier limits, etc.). Follow-up for #5091: the drain loop now wakes on actual worker start/finish via a `threading.Condition` (replacing `as_completed`, which can only signal completion), so completed-but-over-budget futures are reported at their true per-task elapsed time instead of slipping through; queued tasks that never start before the overall safety cap report `(queued for Xs)` with an honest "budget begins at task start" note; and `_coerce_max_subagent_workers` now rejects non-finite values (`inf`/`-inf`/`nan`) raised by `int(float(...))`.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 2d9c228af3..95527ce181 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@@ -8,9 +8,11 @@ questions can be decomposed into subtopics researched in parallel by subagents.from __future__ import annotations+import mathimport reimport threading-from concurrent.futures import ThreadPoolExecutor, TimeoutError, as_completed+import time+from concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetimefrom typing import Any, Dict@@ -34,7 +36,10 @@ DEFAULT_MAX_ITERATIONS = (50 # agent needs many more cycles than pipeline strategies)MIN_ITERATIONS = 10 # below this the agent can barely do anything useful-SUBAGENT_TIMEOUT_SECONDS = 1800 # 30 minutes per subagent+SUBAGENT_TIMEOUT_SECONDS = 1800 # 30 minutes per subagent, measured from+# each subagent's *actual* start time (not from the drain-loop start, which+# used to make queued subagents inherit the wall-clock of everything that+# ran before them -- see #5014).# User-facing sentinel for "the agent produced nothing". _finalize must# not run the accumulated-sources citation pass over it — that would# dress the failure up as a cited synthesis instead of surfacing it.@@ -45,7 +50,17 @@ MAX_SUBTOPICS = 5 # must match the "pass 2-5" contract in the lead prompt# and the research_subtopic tool docstring. Values above this are dropped# at the call site, with the dropped subtopics named in the tool's reply# so the lead agent can re-issue or avoid citing them.-MAX_SUBAGENT_WORKERS = 4+MAX_SUBAGENT_WORKERS = 4 # default pool size when the user has not set+# ``langgraph_agent.max_subagent_workers``. Surplus subtopics queue and+# start as workers free up; each queued subagent keeps its own per-task+# budget from its actual start time.+SUBAGENT_TIMEOUT_OVERALL_MULTIPLIER = 2 # safety cap multiplier: the overall+# drain-loop wall-clock is bounded to ``SUBAGENT_TIMEOUT_SECONDS * multiplier``+# seconds so a pathological hang cannot block the lead forever. This is a+# backstop only -- the per-task deadline above is what actually kills an+# individual subagent. The multiplier is intentionally small (2) because the+# worst case (queued subtopics) is already covered by per-task deadlines; we+# only need the overall cap to bound genuinely deadlocked / hung tasks.# CONTENT_FETCH_TIMEOUT and CONTENT_MAX_LENGTH live alongside the fetch# tool builders in advanced_search_system/tools/fetch/.@@ -338,6 +353,7 @@ def _make_research_subtopic_tool(fetch_mode: str = "summary_focus_query",overall_query: str = "",egress_context=None,+ max_subagent_workers: int = MAX_SUBAGENT_WORKERS,):"""Create the ``research_subtopic`` tool that spawns parallel subagents.@@ -345,6 +361,13 @@ def _make_research_subtopic_tool(strategy; it's forwarded to summary-mode fetch tools so the per-pageextractor sees both the agent's per-fetch focus and the originalresearch question.++ ``max_subagent_workers`` bounds the pool size. Surplus subtopics queue+ and start as workers free up; each queued subagent gets its own per-task+ deadline measured from when *it* actually begins executing (not from+ drain-loop start -- see #5014). The value comes from the user setting+ ``langgraph_agent.max_subagent_workers`` and falls back to+ ``MAX_SUBAGENT_WORKERS`` when unset / invalid."""@tool@@ -457,68 +480,204 @@ def _make_research_subtopic_tool(# @preserve_research_context; captured ONCE here on the lead thread.captured_search_context = get_search_context()- def _run_subagent_with_egress(topic: str) -> str:- # threading.local is NOT inherited by ThreadPoolExecutor workers,- # so the PEP-578 audit-hook backstop armed on the parent thread is- # inactive here. Re-arm it for the subagent's lifetime (LLM,- # web-search and fetch connects) so the secondary egress net has- # parity with the main thread under PRIVATE_ONLY/STRICT. The- # primary snapshot-based PEPs already gate these calls; this- # restores defense-in-depth. active_egress_context is a no-op when- # egress_context is None (fail-open build).- from ...security.egress.audit_hook import active_egress_context-- with active_egress_context(egress_context):- # search_context sets the password ContextVar for this worker- # and clears it on exit (preventing leak across pooled tasks).- if captured_search_context is not None:- with search_context(captured_search_context):- return run_subagent(topic)- return run_subagent(topic)-- ordered_results: dict[str, str] = {}- num_workers = min(MAX_SUBAGENT_WORKERS, len(subtopics))- with ThreadPoolExecutor(max_workers=num_workers) as executor:+ # Worker lifecycle timestamps are written under a condition so the+ # drain loop wakes both when a queued task actually starts and when a+ # running task finishes. Submit time is deliberately not tracked: it+ # includes time spent waiting for a free worker and caused #5014. Task+ # IDs keep duplicate subtopic strings independent.+ task_state_changed = threading.Condition()+ task_start_times: dict[int, float] = {}+ task_end_times: dict[int, float] = {}++ def _run_subagent_with_egress(task: tuple[int, str]) -> str:+ task_id, topic = task+ with task_state_changed:+ task_start_times[task_id] = time.monotonic()+ task_state_changed.notify_all()++ try:+ # threading.local is NOT inherited by ThreadPoolExecutor+ # workers, so re-arm the PEP-578 audit-hook backstop for the+ # subagent's lifetime.+ from ...security.egress.audit_hook import active_egress_context++ with active_egress_context(egress_context):+ # search_context sets the password ContextVar for this+ # worker and clears it on exit, preventing pool reuse from+ # leaking credentials between tasks.+ if captured_search_context is not None:+ with search_context(captured_search_context):+ return run_subagent(topic)+ return run_subagent(topic)+ finally:+ with task_state_changed:+ task_end_times[task_id] = time.monotonic()+ task_state_changed.notify_all()++ ordered_results: dict[int, str] = {}+ # Clamp to >=1 so a misconfigured setting cannot produce a 0-worker+ # pool that silently deadlocks the drain loop. len(subtopics) >= 1+ # is guaranteed by the early-return at the top of the tool body.+ effective_workers = max(1, min(max_subagent_workers, len(subtopics)))+ # Overall safety cap for the drain loop. Sized to cover the worst-+ # case queue wait (ceil(subtopics/workers) waves) plus slack. This is+ # only a backstop; each started task has its own earlier deadline.+ overall_timeout_seconds = (+ SUBAGENT_TIMEOUT_SECONDS+ * max(1, math.ceil(len(subtopics) / effective_workers))+ * SUBAGENT_TIMEOUT_OVERALL_MULTIPLIER+ )+ drain_start = time.monotonic()+ overall_deadline = drain_start + overall_timeout_seconds++ def _record_per_task_timeout(+ task_id: int, topic: str, elapsed: float+ ) -> None:+ logger.warning(+ f"Subagent timed out (per-task): {topic[:80]} "+ f"ran {elapsed:.1f}s of "+ f"{SUBAGENT_TIMEOUT_SECONDS}s budget"+ )+ ordered_results[task_id] = (+ f"Research on '{topic}' timed out after {elapsed:.1f}s "+ f"(per-subagent budget is {SUBAGENT_TIMEOUT_SECONDS}s)."+ )++ executor = ThreadPoolExecutor(max_workers=effective_workers)+ futures = {}+ try:futures = {- executor.submit(_run_subagent_with_egress, t): t- for t in subtopics+ executor.submit(_run_subagent_with_egress, (task_id, topic)): (+ task_id,+ topic,+ )+ for task_id, topic in enumerate(subtopics)}- try:- for future in as_completed(- futures, timeout=SUBAGENT_TIMEOUT_SECONDS- ):- topic = futures[future]- try:- ordered_results[topic] = future.result(- timeout=SUBAGENT_TIMEOUT_SECONDS+ pending = set(futures)++ while pending:+ completed = []+ expired = []+ overall_expired = False++ with task_state_changed:+ while True:+ now = time.monotonic()+ completed = [+ future+ for future in pending+ if futures[future][0] in task_end_times+ ]+ if completed:+ break++ expired = [+ future+ for future in pending+ if (+ futures[future][0] in task_start_times+ and now - task_start_times[futures[future][0]]+ >= SUBAGENT_TIMEOUT_SECONDS+ )+ ]+ if expired:+ break++ if now >= overall_deadline:+ overall_expired = True+ break++ deadlines = [overall_deadline]+ deadlines.extend(+ task_start_times[futures[future][0]]+ + SUBAGENT_TIMEOUT_SECONDS+ for future in pending+ if futures[future][0] in task_start_times)- except TimeoutError:- logger.warning(f"Subagent timed out for: {topic[:80]}")- ordered_results[topic] = (- f"Research on '{topic}' timed out."+ task_state_changed.wait(+ timeout=max(0.0, min(deadlines) - now))++ # A completed future can still have exceeded its own budget.+ # Check the worker-recorded duration before accepting its+ # result; future.result(timeout=...) cannot do this after a+ # completion iterator has already yielded the future.+ for future in completed:+ pending.remove(future)+ task_id, topic = futures[future]+ start = task_start_times[task_id]+ elapsed = max(0.0, task_end_times[task_id] - start)+ if elapsed >= SUBAGENT_TIMEOUT_SECONDS:+ _record_per_task_timeout(task_id, topic, elapsed)+ continue+ try:+ ordered_results[task_id] = future.result()except Exception as exc:logger.exception(f"Subagent failed for: {topic[:80]}")- ordered_results[topic] = _scrub_tool_error(+ ordered_results[task_id] = _scrub_tool_error(f"Research on '{topic}' failed: {exc}")- except TimeoutError:- # as_completed itself timed out — some futures didn't finish- for future, topic in futures.items():- if topic not in ordered_results:- logger.warning(- f"Subagent timed out (overall): {topic[:80]}"- )- ordered_results[topic] = (- f"Research on '{topic}' timed out after "- f"{SUBAGENT_TIMEOUT_SECONDS}s."- )++ # These futures are still running, but their individual+ # deadline has arrived. ThreadPoolExecutor cannot preempt a+ # running Python callable, so ignore its eventual result and+ # let shutdown(wait=False) release the lead agent promptly.+ now = time.monotonic()+ for future in expired:+ pending.remove(future)+ task_id, topic = futures[future]+ elapsed = max(0.0, now - task_start_times[task_id])+ _record_per_task_timeout(task_id, topic, elapsed)+ future.cancel()++ if overall_expired:+ now = time.monotonic()+ for future in pending:+ task_id, topic = futures[future]+ start = task_start_times.get(task_id)+ if start is None:+ queued_elapsed = max(0.0, now - drain_start)+ logger.warning(+ f"Subagent exceeded overall safety cap: "+ f"{topic[:80]} remained queued for "+ f"{queued_elapsed:.1f}s and never started"+ )+ ordered_results[task_id] = (+ f"Research on '{topic}' did not start before "+ f"the overall safety budget of "+ f"{overall_timeout_seconds}s expired "+ f"(queued for {queued_elapsed:.1f}s; its "+ f"{SUBAGENT_TIMEOUT_SECONDS}s per-subagent "+ f"budget begins at task start)."+ )+ else:+ elapsed = max(0.0, now - start)+ logger.warning(+ f"Subagent exceeded overall safety cap: "+ f"{topic[:80]} ran {elapsed:.1f}s of "+ f"{overall_timeout_seconds}s overall / "+ f"{SUBAGENT_TIMEOUT_SECONDS}s per-task budget"+ )+ ordered_results[task_id] = (+ f"Research on '{topic}' did not finish within "+ f"the overall safety budget of "+ f"{overall_timeout_seconds}s (ran "+ f"{elapsed:.1f}s; per-subagent budget is "+ f"{SUBAGENT_TIMEOUT_SECONDS}s)."+ )+ future.cancel()+ pending.clear()+ finally:+ for future in futures:+ if not future.done():+ future.cancel()+ executor.shutdown(wait=False, cancel_futures=True)# Return results in original orderparts = []- for topic in subtopics:+ for task_id, topic in enumerate(subtopics):parts.append(- f"## {topic}\n{ordered_results.get(topic, 'No results')}"+ f"## {topic}\n{ordered_results.get(task_id, 'No results')}")result_text = "\n\n---\n\n".join(parts)@@ -603,9 +762,61 @@ class LangGraphAgentStrategy(BaseSearchStrategy):self.fetch_mode = fetch_modelogger.info(f"LangGraph agent fetch_mode={self.fetch_mode}")+ # 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+ # tier limit, etc. -- without code changes. Falls back to the+ # constant default on missing/invalid input so a misconfigured+ # setting cannot silently break the drain loop.+ raw_max_workers = self.get_setting(+ "langgraph_agent.max_subagent_workers", MAX_SUBAGENT_WORKERS+ )+ self.max_subagent_workers = self._coerce_max_subagent_workers(+ raw_max_workers+ )+# Derive the search engine name for creating fresh instancesself._search_engine_name = self._resolve_engine_name()+ @staticmethod+ def _coerce_max_subagent_workers(raw: Any) -> int:+ """Validate and clamp the user-supplied pool size.++ - Non-numeric, non-finite, or unparsable values fall back to+ ``MAX_SUBAGENT_WORKERS`` with a warning so a misconfigured setting+ cannot crash the constructor or silently produce a 0-worker pool.+ - Values below 1 are clamped up to 1; a 0-worker pool would deadlock+ the drain loop waiting on tasks no thread will ever run.+ - Values above 32 are clamped down -- past that point the bottleneck+ is almost always the LLM/search backend, not pool size, and an+ unbounded value invites accidental denial-of-service against the+ user's own infrastructure.+ """+ try:+ value = int(raw)+ except (TypeError, ValueError, OverflowError):+ logger.warning(+ f"langgraph_agent.max_subagent_workers={raw!r} is not an "+ f"integer; falling back to MAX_SUBAGENT_WORKERS="+ f"{MAX_SUBAGENT_WORKERS}"+ )+ return MAX_SUBAGENT_WORKERS+ if value < 1:+ logger.warning(+ f"langgraph_agent.max_subagent_workers={value} is below 1; "+ f"clamping to 1 to avoid a deadlocked pool"+ )+ return 1+ if value > 32:+ logger.warning(+ f"langgraph_agent.max_subagent_workers={value} is above the "+ f"32-thread soft cap; clamping to 32. Set via env or "+ f"settings only if your LLM/search backend explicitly "+ f"supports it."+ )+ return 32+ return value+def _resolve_engine_name(self) -> str:"""Best-effort extraction of the configured engine name."""# Try settings first@@ -961,6 +1172,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):fetch_mode=self.fetch_mode,overall_query=overall_query,egress_context=policy_ctx,+ max_subagent_workers=self.max_subagent_workers,))diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 6e0791ec33..53437e152f 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -1075,6 +1075,20 @@"value": true,"visible": true},+ "langgraph_agent.max_subagent_workers": {+ "category": "langgraph_agent",+ "description": "Maximum number of subagents that may run in parallel when the lead agent fans out subtopics via research_subtopic. Each worker thread serves one subagent at a time; any surplus subtopics queue and start as workers free up (a queued subagent keeps its own per-task budget — it is NOT killed by a shared loop timer). Tune this to match what your LLM backend can sustain in parallel (Ollama / LMStudio / llama.cpp `OLLAMA_NUM_PARALLEL`, an OpenAI tier limit, etc.). Lower values reduce load; higher values increase parallelism at the cost of more concurrent LLM/search traffic.",+ "editable": true,+ "max_value": 32,+ "min_value": 1,+ "name": "Max Parallel Subagents",+ "options": null,+ "step": 1,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 4,+ "visible": true+ },"focused_iteration.adaptive_questions": {"category": "focused_iteration","description": "When enabled (1), the system monitors recent search success and warns the LLM to broaden queries if 3+ searches in a recent window returned no results. When disabled (0), queries are generated without feedback from previous result counts.",diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 979d162434..b71a124eba 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -1092,6 +1092,20 @@"value": 8,"visible": true},+ "langgraph_agent.max_subagent_workers": {+ "category": "langgraph_agent",+ "description": "Maximum number of subagents that may run in parallel when the lead agent fans out subtopics via research_subtopic. Each worker thread serves one subagent at a time; any surplus subtopics queue and start as workers free up (a queued subagent keeps its own per-task budget — it is NOT killed by a shared loop timer). Tune this to match what your LLM backend can sustain in parallel (Ollama / LMStudio / llama.cpp `OLLAMA_NUM_PARALLEL`, an OpenAI tier limit, etc.). Lower values reduce load; higher values increase parallelism at the cost of more concurrent LLM/search traffic.",+ "editable": true,+ "max_value": 32,+ "min_value": 1,+ "name": "Max Parallel Subagents",+ "options": null,+ "step": 1,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 4,+ "visible": true+ },"llm.allowed_local_hostnames": {"category": "policy","description": "Hostnames the policy will treat as local in addition to loopback / RFC1918 / link-local. Use for self-hosted services on custom hostnames (e.g. 'ollama.lan'). Public hostnames added here are rejected at save time.",diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex 3ab8c448b9..835f142d4d 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -1835,38 +1835,6 @@ class TestEgressScopePolicyAddendum:# ----------------------------------------------------------------------------class _ImmediateFuture:- """Minimal future that runs the callable synchronously on result()."""-- def __init__(self, fn, arg):- self._fn = fn- self._arg = arg-- def result(self, timeout=None):- return self._fn(self._arg)---class _ImmediateExecutor:- """ThreadPoolExecutor stand-in that runs tasks synchronously."""-- def __init__(self, max_workers=None):- self._max_workers = max_workers-- def __enter__(self):- return self-- def __exit__(self, *exc):- return False-- def submit(self, fn, arg):- return _ImmediateFuture(fn, arg)---def _fake_as_completed(futures, timeout=None):- for f in futures:- yield f--class TestResearchSubtopicToolTruncation:"""Regression tests for #5012: MAX_SUBTOPICS vs the 'pass 2-5' contract.@@ -1913,13 +1881,7 @@ class TestResearchSubtopicToolTruncation:with patch("langchain.agents.create_agent", return_value=agent_mock):- with patch.object(- mod, "ThreadPoolExecutor", _ImmediateExecutor- ):- with patch.object(- mod, "as_completed", _fake_as_completed- ):- result = tool.invoke({"subtopics": subtopics})+ result = tool.invoke({"subtopics": subtopics})return result, max_subdef test_constant_matches_prompt_contract(self):diff --git a/tests/strategies/test_langgraph_subagent_timeout_5014.py b/tests/strategies/test_langgraph_subagent_timeout_5014.pynew file mode 100644index 0000000000..4b75a4fdd4--- /dev/null+++ b/tests/strategies/test_langgraph_subagent_timeout_5014.py@@ -0,0 +1,244 @@+"""Regression tests for #5014: langgraph-agent subagent timeout.++The ``research_subtopic`` fan-out used a single shared+``as_completed(futures, timeout=SUBAGENT_TIMEOUT_SECONDS)`` budget for the+whole drain loop. Because ``ThreadPoolExecutor`` has no work-stealing, when+``MAX_SUBTOPICS > MAX_SUBAGENT_WORKERS`` the surplus subtopics queue and only+start executing near the end of the window -- then the shared timer killed them+and reported ``"timed out after 1800s"`` even though they had run for seconds.++The fix (Option A) gives each subagent a per-task deadline measured from its+*actual* start time, plus a generous overall safety cap that only fires for+genuinely hung tasks. The follow-up comment additionally requires exposing+``MAX_SUBAGENT_WORKERS`` as the user setting+``langgraph_agent.max_subagent_workers``.++These tests drive the REAL production drain loop with a REAL+``ThreadPoolExecutor``. To keep them fast and deterministic we patch the+module-level ``SUBAGENT_TIMEOUT_SECONDS`` to a small value (e.g. 0.2s) and let+subagents "work" by sleeping real (short) amounts of time. The per-task+deadline is therefore exercised against real wall-clock elapsed times, so the+queued-subagent false-positive and the actual-elapsed reporting are both+genuinely validated.+"""++import time+from unittest.mock import MagicMock, patch++import local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy as mod+from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ MAX_SUBAGENT_WORKERS,+ LangGraphAgentStrategy,+ SearchResultsCollector,+ _make_research_subtopic_tool,+)++# Small budget so tests run in well under a second while still exercising the+# per-task timeout path.+TEST_TIMEOUT = 0.2+++def _build_tool(max_subagent_workers=MAX_SUBAGENT_WORKERS, sleep_map=None):+ """Build a research_subtopic tool whose subagents sleep per ``sleep_map``.++ ``sleep_map``: subtopic -> seconds the subagent sleeps (simulated work).+ Returns (tool, agent_mock).+ """+ sleep_map = sleep_map or {}++ collector = SearchResultsCollector([])+ tool = _make_research_subtopic_tool(+ search_engine_name="duckduckgo",+ model=MagicMock(),+ settings_snapshot={"search.tool": {"value": "duckduckgo"}},+ collector=collector,+ max_sub_iterations=8,+ max_subagent_workers=max_subagent_workers,+ )++ agent_mock = MagicMock()++ def _fake_invoke(payload, _config=None):+ topic = payload["messages"][0]["content"]+ # Simulate real work so wall-clock elapsed time is meaningful.+ time.sleep(sleep_map.get(topic, 0.0))+ return {"messages": [MagicMock(content=f"finding for {topic}")]}++ agent_mock.invoke.side_effect = _fake_invoke+ return tool, agent_mock+++class TestResearchSubtopicPerTaskTimeout:+ """#5014: per-subagent deadline from actual start time + user workers."""++ def _run(self, sleep_map, max_subagent_workers=4):+ tool, agent_mock = _build_tool(+ max_subagent_workers=max_subagent_workers, sleep_map=sleep_map+ )+ with patch.object(+ mod, "_make_web_search_tool", return_value=MagicMock()+ ):+ with patch.object(mod, "build_fetch_tool", return_value=None):+ with patch(+ "langchain.agents.create_agent", return_value=agent_mock+ ):+ with patch.object(+ mod, "SUBAGENT_TIMEOUT_SECONDS", TEST_TIMEOUT+ ):+ return tool.invoke(+ {"subtopics": list(sleep_map.keys())}+ )++ def test_queued_subagent_not_falsely_timed_out(self):+ """Reproduce the #5014 false-positive scenario with a short budget:+ 5 subtopics, 4 workers, the first 4 each take most of the budget, the+ 5th is queued and starts late but runs only briefly. Under the OLD+ shared-timer code the 5th would be flagged "timed out after <budget>"+ despite running for milliseconds. Under the fix it returns a result."""+ topics = [f"topic {i}" for i in range(5)]+ # The first wave plus the queued task exceeds the old shared 0.2s+ # drain budget, while the queued task's own 0.06s runtime stays well+ # inside its individual budget. This fails against the pre-PR loop.+ sleep_map = {+ t: TEST_TIMEOUT * 0.9 if i < 4 else TEST_TIMEOUT * 0.3+ for i, t in enumerate(topics)+ }++ result = self._run(sleep_map, max_subagent_workers=4)++ # The queued 5th subtopic must NOT be reported as timed out.+ assert "topic 4" in result+ assert "Research on 'topic 4' timed out" not in result+ # All five return real findings.+ assert result.count("finding for topic") >= 5++ def test_subagent_finishing_after_own_deadline_times_out(self):+ """One slow future among normal finishers is reported at its 0.2s+ task deadline even though it finishes by the 0.4s overall cap. This is+ the reviewer-requested proof that the per-task path is live."""+ result = self._run(+ {+ "fast topic": 0.01,+ "slow topic": TEST_TIMEOUT * 1.5,+ },+ max_subagent_workers=2,+ )++ assert "finding for fast topic" in result+ assert "Research on 'slow topic' timed out after" in result+ assert "finding for slow topic" not in result+ assert "did not finish within the overall safety budget" not in result++ def test_per_task_deadline_from_actual_start_not_submit(self):+ """Even when a subagent is queued for a long time, its per-task budget+ is measured from its *actual* start, so a short-running queued task is+ never killed. 3 tasks serialised behind 1 worker, each brief."""+ topics = [f"topic {i}" for i in range(3)]+ sleep_map = {t: 0.01 for t in topics}++ result = self._run(sleep_map, max_subagent_workers=1)++ for t in topics:+ assert f"## {t}" in result+ assert f"Research on '{t}' timed out" not in result++ def test_overall_cap_reports_never_started_task_as_queued(self):+ """A task stuck behind a timed-out worker must not be described as+ having run since drain start; its own budget never began."""+ sleep_map = {+ "hung topic": TEST_TIMEOUT * 6,+ "queued topic": 0.01,+ }++ result = self._run(sleep_map, max_subagent_workers=1)++ assert "Research on 'hung topic' timed out after" in result+ assert (+ "Research on 'queued topic' did not start before the overall "+ "safety budget"+ ) in result+ assert "(queued for " in result+ assert "budget begins at task start" in result+ assert "finding for queued topic" not in result++ def test_max_subagent_workers_setting_is_respected(self):+ """The user setting ``langgraph_agent.max_subagent_workers`` must flow+ through to the pool size used by the tool (follow-up to #5014)."""+ collector = SearchResultsCollector([])+ captured = {}++ real_tpe = mod.ThreadPoolExecutor++ def _spy_executor(max_workers=None, **kw):+ captured["max_workers"] = max_workers+ return real_tpe(max_workers=max_workers, **kw)++ tool = _make_research_subtopic_tool(+ search_engine_name="duckduckgo",+ model=MagicMock(),+ settings_snapshot={"search.tool": {"value": "duckduckgo"}},+ collector=collector,+ max_sub_iterations=8,+ max_subagent_workers=7,+ )+ agent_mock = MagicMock()+ agent_mock.invoke.return_value = {"messages": [MagicMock(content="ok")]}+ with patch.object(+ mod, "_make_web_search_tool", return_value=MagicMock()+ ):+ with patch.object(mod, "build_fetch_tool", return_value=None):+ with patch(+ "langchain.agents.create_agent", return_value=agent_mock+ ):+ with patch.object(mod, "ThreadPoolExecutor", _spy_executor):+ tool.invoke({"subtopics": ["a", "b", "c"]})++ # Pool size is min(max_subagent_workers, len(subtopics)) = min(7, 3) = 3+ assert captured["max_workers"] == 3++ def test_coerce_clamps_invalid_setting(self):+ """``_coerce_max_subagent_workers`` must fall back to the constant for+ non-integer input and clamp out-of-range values."""+ assert LangGraphAgentStrategy._coerce_max_subagent_workers("oops") == (+ MAX_SUBAGENT_WORKERS+ )+ assert (+ LangGraphAgentStrategy._coerce_max_subagent_workers(float("inf"))+ == MAX_SUBAGENT_WORKERS+ )+ assert (+ LangGraphAgentStrategy._coerce_max_subagent_workers(float("-inf"))+ == MAX_SUBAGENT_WORKERS+ )+ assert (+ LangGraphAgentStrategy._coerce_max_subagent_workers(float("nan"))+ == MAX_SUBAGENT_WORKERS+ )+ assert LangGraphAgentStrategy._coerce_max_subagent_workers(0) == 1+ assert LangGraphAgentStrategy._coerce_max_subagent_workers(-5) == 1+ assert LangGraphAgentStrategy._coerce_max_subagent_workers(100) == 32+ assert LangGraphAgentStrategy._coerce_max_subagent_workers(8) == 8++ def test_strategy_reads_setting_default_when_absent(self):+ """With no setting present, the strategy defaults to+ ``MAX_SUBAGENT_WORKERS``."""+ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ settings_snapshot={},+ max_sub_iterations=8,+ )+ assert strategy.max_subagent_workers == MAX_SUBAGENT_WORKERS++ def test_strategy_reads_user_setting(self):+ """A user-supplied ``langgraph_agent.max_subagent_workers`` is honoured+ (when valid)."""+ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(),+ settings_snapshot={+ "langgraph_agent.max_subagent_workers": {"value": 6}+ },+ max_sub_iterations=8,+ )+ assert strategy.max_subagent_workers == 6