-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Improve tool efficiency: connection pooling, parallel execution, dedu… #305
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
b4l4-sec
wants to merge
1
commit into
usestrix:main
Choose a base branch
from
b4l4-sec:claude/improve-tool-efficiency-X7Qsk
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+186
−31
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| import asyncio | ||
| import inspect | ||
| import os | ||
| from typing import Any | ||
|
|
@@ -25,6 +26,31 @@ | |
| SANDBOX_EXECUTION_TIMEOUT = _SERVER_TIMEOUT + 30 | ||
| SANDBOX_CONNECT_TIMEOUT = float(Config.get("strix_sandbox_connect_timeout") or "10") | ||
|
|
||
| # Connection pool: reuse HTTP clients per sandbox instead of creating one per call | ||
| _sandbox_clients: dict[str, httpx.AsyncClient] = {} | ||
|
|
||
|
|
||
| def _get_sandbox_client(sandbox_id: str) -> httpx.AsyncClient: | ||
| """Get or create a persistent HTTP client for a sandbox, enabling connection reuse.""" | ||
| if sandbox_id not in _sandbox_clients: | ||
| timeout = httpx.Timeout( | ||
| timeout=SANDBOX_EXECUTION_TIMEOUT, | ||
| connect=SANDBOX_CONNECT_TIMEOUT, | ||
| ) | ||
| _sandbox_clients[sandbox_id] = httpx.AsyncClient( | ||
| trust_env=False, | ||
| timeout=timeout, | ||
| limits=httpx.Limits(max_connections=10, max_keepalive_connections=5), | ||
| ) | ||
| return _sandbox_clients[sandbox_id] | ||
|
|
||
|
|
||
| async def close_sandbox_client(sandbox_id: str) -> None: | ||
| """Close and remove the HTTP client for a sandbox when it's torn down.""" | ||
| client = _sandbox_clients.pop(sandbox_id, None) | ||
| if client: | ||
| await client.aclose() | ||
|
Comment on lines
+48
to
+52
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Prompt To Fix With AIThis is a comment left during a code review.
Path: strix/tools/executor.py
Line: 48:52
Comment:
`close_sandbox_client` is defined but never called in the codebase. Connection pool clients accumulate without cleanup when sandboxes are torn down, leading to resource leaks.
How can I resolve this? If you propose a fix, please make it concise. |
||
|
|
||
|
|
||
| async def execute_tool(tool_name: str, agent_state: Any | None = None, **kwargs: Any) -> Any: | ||
| execute_in_sandbox = should_execute_in_sandbox(tool_name) | ||
|
|
@@ -71,31 +97,27 @@ async def _execute_tool_in_sandbox(tool_name: str, agent_state: Any, **kwargs: A | |
| "Content-Type": "application/json", | ||
| } | ||
|
|
||
| timeout = httpx.Timeout( | ||
| timeout=SANDBOX_EXECUTION_TIMEOUT, | ||
| connect=SANDBOX_CONNECT_TIMEOUT, | ||
| ) | ||
| client = _get_sandbox_client(agent_state.sandbox_id) | ||
|
|
||
| async with httpx.AsyncClient(trust_env=False) as client: | ||
| try: | ||
| response = await client.post( | ||
| request_url, json=request_data, headers=headers, timeout=timeout | ||
| ) | ||
| response.raise_for_status() | ||
| response_data = response.json() | ||
| if response_data.get("error"): | ||
| posthog.error("tool_execution_error", f"{tool_name}: {response_data['error']}") | ||
| raise RuntimeError(f"Sandbox execution error: {response_data['error']}") | ||
| return response_data.get("result") | ||
| except httpx.HTTPStatusError as e: | ||
| posthog.error("tool_http_error", f"{tool_name}: HTTP {e.response.status_code}") | ||
| if e.response.status_code == 401: | ||
| raise RuntimeError("Authentication failed: Invalid or missing sandbox token") from e | ||
| raise RuntimeError(f"HTTP error calling tool server: {e.response.status_code}") from e | ||
| except httpx.RequestError as e: | ||
| error_type = type(e).__name__ | ||
| posthog.error("tool_request_error", f"{tool_name}: {error_type}") | ||
| raise RuntimeError(f"Request error calling tool server: {error_type}") from e | ||
| try: | ||
| response = await client.post( | ||
| request_url, json=request_data, headers=headers | ||
| ) | ||
| response.raise_for_status() | ||
| response_data = response.json() | ||
| if response_data.get("error"): | ||
| posthog.error("tool_execution_error", f"{tool_name}: {response_data['error']}") | ||
| raise RuntimeError(f"Sandbox execution error: {response_data['error']}") | ||
| return response_data.get("result") | ||
| except httpx.HTTPStatusError as e: | ||
| posthog.error("tool_http_error", f"{tool_name}: HTTP {e.response.status_code}") | ||
| if e.response.status_code == 401: | ||
| raise RuntimeError("Authentication failed: Invalid or missing sandbox token") from e | ||
| raise RuntimeError(f"HTTP error calling tool server: {e.response.status_code}") from e | ||
| except httpx.RequestError as e: | ||
| error_type = type(e).__name__ | ||
| posthog.error("tool_request_error", f"{tool_name}: {error_type}") | ||
| raise RuntimeError(f"Request error calling tool server: {error_type}") from e | ||
|
|
||
|
|
||
| async def _execute_tool_locally(tool_name: str, agent_state: Any | None, **kwargs: Any) -> Any: | ||
|
|
@@ -310,6 +332,13 @@ def _get_tracer_and_agent_id(agent_state: Any | None) -> tuple[Any | None, str]: | |
| return tracer, agent_id | ||
|
|
||
|
|
||
| # Tools that modify shared state and must run sequentially | ||
| _SEQUENTIAL_TOOLS = frozenset({ | ||
| "finish_scan", "agent_finish", "delegate_task", "send_message", | ||
| "wait_for_message", "create_agent", | ||
| }) | ||
|
|
||
|
|
||
| async def process_tool_invocations( | ||
| tool_invocations: list[dict[str, Any]], | ||
| conversation_history: list[dict[str, Any]], | ||
|
|
@@ -321,7 +350,42 @@ async def process_tool_invocations( | |
|
|
||
| tracer, agent_id = _get_tracer_and_agent_id(agent_state) | ||
|
|
||
| # Partition into parallelizable and sequential tools | ||
| parallel_batch: list[dict[str, Any]] = [] | ||
| sequential_queue: list[dict[str, Any]] = [] | ||
|
|
||
| for tool_inv in tool_invocations: | ||
| tool_name = tool_inv.get("toolName", "unknown") | ||
| if tool_name in _SEQUENTIAL_TOOLS: | ||
| sequential_queue.append(tool_inv) | ||
| else: | ||
| parallel_batch.append(tool_inv) | ||
|
|
||
| # Execute parallelizable tools concurrently | ||
| if parallel_batch: | ||
| tasks = [ | ||
| _execute_single_tool(tool_inv, agent_state, tracer, agent_id) | ||
| for tool_inv in parallel_batch | ||
| ] | ||
| results = await asyncio.gather(*tasks, return_exceptions=True) | ||
|
|
||
| for i, result in enumerate(results): | ||
| if isinstance(result, Exception): | ||
| tool_name = parallel_batch[i].get("toolName", "unknown") | ||
| error_xml = ( | ||
| f"<tool_result>\n<tool_name>{tool_name}</tool_name>\n" | ||
| f"<result>Error executing {tool_name}: {result!s}</result>\n</tool_result>" | ||
| ) | ||
| observation_parts.append(error_xml) | ||
| else: | ||
| observation_xml, images, tool_should_finish = result | ||
| observation_parts.append(observation_xml) | ||
| all_images.extend(images) | ||
| if tool_should_finish: | ||
| should_agent_finish = True | ||
|
|
||
| # Execute sequential tools one at a time (order matters) | ||
| for tool_inv in sequential_queue: | ||
| observation_xml, images, tool_should_finish = await _execute_single_tool( | ||
| tool_inv, agent_state, tracer, agent_id | ||
| ) | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_token_cachegrows unbounded. For long-running agents with many unique messages, this will consume increasing memory. Consider adding LRU eviction or size limits.Prompt To Fix With AI