Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(research): enforce tool timeout and retry policy (#1357)

evan188199-tech30e0f7c3a2b1
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.py
index 91acc30a3..f9c173e9f 100644
--- a/deeptutor/agents/research/pipeline.py
+++ b/deeptutor/agents/research/pipeline.py
@@ -396,6 +396,22 @@ class ResearchPipeline:
key="max_iterations",
default=DEFAULT_BLOCK_MAX_ITERATIONS,
)
+ self.tool_timeout = max(
+ 1,
+ _read_int(
+ researching,
+ key="tool_timeout",
+ default=60,
+ ),
+ )
+ self.tool_max_retries = max(
+ 0,
+ _read_int(
+ researching,
+ key="tool_max_retries",
+ default=3,
+ ),
+ )
self.max_parallel_topics = max(
1,
_read_int(
@@ -2582,6 +2598,8 @@ class _BlockLoopHost:
default=f"Error executing {tn}.",
),
trace_id_prefix=f"research-{self._block.block_id}-iter",
+ tool_timeout=self._pipeline.tool_timeout,
+ tool_max_retries=self._pipeline.tool_max_retries,
)
pageindex_sources = [
source for source in outcome.sources if source.get("type") == "pageindex"
diff --git a/deeptutor/runtime/agentic/tool_dispatch.py b/deeptutor/runtime/agentic/tool_dispatch.py
index e23fcbde2..1f4a9e7ec 100644
--- a/deeptutor/runtime/agentic/tool_dispatch.py
+++ b/deeptutor/runtime/agentic/tool_dispatch.py
@@ -105,6 +105,8 @@ async def dispatch_tool_calls(
too_many_tool_calls_message: str | None = None,
unknown_error_message_factory: UnknownErrorMessageFactory | None = None,
trace_id_prefix: str = "iter",
+ tool_timeout: float | None = None,
+ tool_max_retries: int = 0,
) -> DispatchOutcome:
"""Execute tool calls in parallel and assemble a :class:`DispatchOutcome`."""
registry = registry or get_tool_registry()
@@ -193,6 +195,9 @@ async def dispatch_tool_calls(
)
if rejection is not None:
return rejection
+ # Pause tools intentionally wait for user interaction. A wall-clock
+ # tool timeout must not cancel that wait.
+ policy_exempt = tool_name in PAUSE_LAST_TOOLS
return await execute_tool_call(
registry=registry,
tool_name=tool_name,
@@ -214,6 +219,8 @@ async def dispatch_tool_calls(
start_retrieval_message=start_retrieval_message,
unknown_error_message_factory=unknown_error_message_factory,
retrieve_label=retrieve_label,
+ tool_timeout=None if policy_exempt else tool_timeout,
+ tool_max_retries=0 if policy_exempt else tool_max_retries,
)
def _rebind(indices: list[int]) -> None:
@@ -595,6 +602,8 @@ async def execute_tool_call(
start_retrieval_message: str = "Starting retrieval",
retrieve_label: str = "Retrieve",
unknown_error_message_factory: UnknownErrorMessageFactory | None = None,
+ tool_timeout: float | None = None,
+ tool_max_retries: int = 0,
) -> dict[str, Any]:
"""Run one tool, streaming its state (and any intermediate progress) into
the tool's own sub-trace.
@@ -652,17 +661,40 @@ async def execute_tool_call(
call_state="running",
),
)
+
+ async def _execute_with_policy() -> Any:
+ attempts = max(1, int(tool_max_retries) + 1)
+ for attempt in range(1, attempts + 1):
+ try:
+ return await asyncio.wait_for(
+ registry.execute(
+ tool_name,
+ # Withheld when there is nowhere to publish (a bare call with
+ # neither meta): tools branch on the sink being present to decide
+ # whether to do the work at all — ``rag`` installs a log-capture
+ # handler for it — so handing over one that discards everything is
+ # strictly worse than handing over none.
+ event_sink=_event_sink if status_meta is not None else None,
+ **tool_args,
+ ),
+ timeout=tool_timeout,
+ )
+ except (asyncio.TimeoutError, ConnectionError) as exc:
+ if attempt >= attempts:
+ if isinstance(exc, asyncio.TimeoutError) and tool_timeout is not None:
+ raise TimeoutError(
+ f"{tool_name} timed out after {tool_timeout:g} seconds"
+ ) from exc
+ raise
+ retry_reason = "timed out" if isinstance(exc, asyncio.TimeoutError) else str(exc)
+ await _event_sink(
+ "tool_log",
+ f"{tool_name} {retry_reason}; retrying attempt {attempt + 1}/{attempts}",
+ {"retry_attempt": attempt + 1, "max_attempts": attempts},
+ )
+
try:
- result = await registry.execute(
- tool_name,
- # Withheld when there is nowhere to publish (a bare call with
- # neither meta): tools branch on the sink being present to decide
- # whether to do the work at all — ``rag`` installs a log-capture
- # handler for it — so handing over one that discards everything is
- # strictly worse than handing over none.
- event_sink=_event_sink if status_meta is not None else None,
- **tool_args,
- )
+ result = await _execute_with_policy()
if status_meta is not None:
await stream.progress(
(
diff --git a/tests/agents/research/test_block_tool_policy.py b/tests/agents/research/test_block_tool_policy.py
new file mode 100644
index 000000000..df751f174
--- /dev/null
+++ b/tests/agents/research/test_block_tool_policy.py
@@ -0,0 +1,80 @@
+"""Research-specific tool execution policy propagation."""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.agents.research.data_structures import DynamicTopicQueue, TopicBlock
+from deeptutor.agents.research.pipeline import ResearchPipeline, _BlockLoopHost
+from deeptutor.core.context import UnifiedContext
+from deeptutor.runtime.agentic.tool_dispatch import DispatchOutcome
+from deeptutor.runtime.stream_bus import StreamBus
+
+
+class _FakeLLM:
+ binding = "openai"
+ model = "gpt-x"
+ api_key = "k"
+ base_url = "u"
+ api_version = None
+ extra_headers = {}
+
+
+class _FakeRegistry:
+ def build_openai_schemas(self, _names):
+ return []
+
+ def build_prompt_text(self, _names, **_kwargs):
+ return "- none"
+
+ def get(self, _name):
+ return None
+
+ def get_enabled(self, _names):
+ return []
+
+
+async def test_block_host_passes_tool_policy_to_dispatcher(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+
+ async def fake_dispatch_tool_calls(**kwargs):
+ captured.update(kwargs)
+ return DispatchOutcome()
+
+ monkeypatch.setattr("deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM())
+ monkeypatch.setattr(
+ "deeptutor.agents.research.pipeline.get_tool_registry", lambda: _FakeRegistry()
+ )
+ monkeypatch.setattr(
+ "deeptutor.agents.research.pipeline.dispatch_tool_calls",
+ fake_dispatch_tool_calls,
+ )
+
+ pipeline = ResearchPipeline(
+ language="en",
+ runtime_config={
+ "researching": {"tool_timeout": 7, "tool_max_retries": 2},
+ },
+ )
+ queue = DynamicTopicQueue("topic", max_length=1)
+ host = _BlockLoopHost(
+ pipeline=pipeline,
+ block=TopicBlock(block_id="block_1", sub_topic="topic", overview=""),
+ queue=queue,
+ citations=object(),
+ topic="topic",
+ stream=StreamBus(),
+ context=UnifiedContext(session_id="s1", user_message="m"),
+ client=None,
+ )
+
+ await host.dispatch_tools(
+ iteration=0,
+ tool_calls=[{"id": "c1", "name": "web_search", "arguments": "{}"}],
+ )
+
+ assert captured["tool_timeout"] == 7
+ assert captured["tool_max_retries"] == 2
diff --git a/tests/core/agentic/test_tool_dispatch_events.py b/tests/core/agentic/test_tool_dispatch_events.py
index e406d7d5c..d0a43db7d 100644
--- a/tests/core/agentic/test_tool_dispatch_events.py
+++ b/tests/core/agentic/test_tool_dispatch_events.py
@@ -37,6 +37,30 @@ class _Registry:
return ToolResult(content="ok", success=True)
+class _SlowRegistry:
+ async def execute(self, name: str, **kwargs: Any) -> ToolResult:
+ await asyncio.sleep(0.05)
+ return ToolResult(content="too late", success=True)
+
+
+class _FlakyConnectionRegistry:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ async def execute(self, name: str, **kwargs: Any) -> ToolResult:
+ self.calls += 1
+ if self.calls == 1:
+ raise ConnectionError("provider offline")
+ return ToolResult(content="recovered", success=True)
+
+
+class _PausingRegistry:
+ async def execute(self, name: str, **kwargs: Any) -> ToolResult:
+ assert name == "ask_user"
+ await asyncio.sleep(0.02)
+ return ToolResult(content="user card", success=True)
+
+
class _SensitiveArgRegistry(_Registry):
"""A tool whose schema marks one argument as not-for-display."""
@@ -110,6 +134,8 @@ async def _run_dispatch(
registry: Any,
kwarg_augmenter: Any = None,
retrieve_meta_factory: Any = None,
+ tool_timeout: float | None = None,
+ tool_max_retries: int = 0,
) -> list[StreamEvent]:
"""Dispatch through a real StreamBus and return everything it emitted."""
bus = StreamBus()
@@ -132,6 +158,8 @@ async def _run_dispatch(
registry=registry,
kwarg_augmenter=kwarg_augmenter,
retrieve_meta_factory=retrieve_meta_factory,
+ tool_timeout=tool_timeout,
+ tool_max_retries=tool_max_retries,
)
await bus.close()
await consumer
@@ -158,6 +186,48 @@ def _call_id_of(event: StreamEvent) -> str:
return str((event.metadata or {}).get("call_id") or "")
+async def test_tool_timeout_returns_actionable_error() -> None:
+ events = await _run_dispatch(
+ [{"id": "c1", "name": "web_search", "arguments": '{"query": "x"}'}],
+ registry=_SlowRegistry(),
+ tool_timeout=0.01,
+ tool_max_retries=0,
+ )
+
+ status_events = _status_events(events)
+ assert status_events
+ assert _call_states(events) == ["running", "error"]
+ assert "web_search timed out after" in str(status_events[-1].metadata.get("error"))
+
+
+async def test_transient_connection_error_is_retried() -> None:
+ registry = _FlakyConnectionRegistry()
+
+ events = await _run_dispatch(
+ [{"id": "c1", "name": "web_search", "arguments": '{"query": "x"}'}],
+ registry=registry,
+ tool_timeout=1,
+ tool_max_retries=1,
+ )
+
+ assert registry.calls == 2
+ assert _call_states(events) == ["running", "complete"]
+
+
+async def test_pause_tool_waits_beyond_tool_timeout() -> None:
+ events = await _run_dispatch(
+ [{"id": "c1", "name": "ask_user", "arguments": '{"question": "continue?"}'}],
+ registry=_PausingRegistry(),
+ tool_timeout=0.001,
+ tool_max_retries=0,
+ )
+
+ assert _call_states(events) == ["running", "complete"]
+
+
@pytest.mark.asyncio
async def test_tool_call_event_args_exclude_private_kwargs() -> None:
events = await _run_dispatch(