fix(sandbox): report retryable capacity errors from tools (#8608)

* fix(sandbox): report retryable capacity errors from tools

* fix(sandbox): distinguish capacity service failures

* test(logging): isolate urllib3 emitter log levels

* test(coordination): use SQLite WAL for worker recovery

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
chaodidiao 2026-11-26 08:50:18 +08:00 committed by GitHub
parent 75b6f6ae65
commit b63dd7a794
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 163 additions and 22 deletions

View File

@ -214,6 +214,7 @@ def _format_hint(meta: ToolResultMeta) -> str:
action_map = {
"rewrite_query": "Try rephrasing your search query with different keywords or approach.",
"try_alternative": "Consider using a different tool or strategy.",
"retry_later": "Wait before retrying. If the failure persists, tell the user to try again later.",
"summarize": "Consider summarizing your current findings and moving forward.",
"stop": "Do not retry this operation — it is not recoverable.",
# Near-duplicate success results: recommended_next_action is "continue" by default,
@ -225,6 +226,7 @@ def _format_hint(meta: ToolResultMeta) -> str:
"not_found": "[PROGRESS HINT] The resource was not found repeatedly.",
"rate_limited": "[PROGRESS HINT] The tool is being rate-limited.",
"transient": "[PROGRESS HINT] The tool encountered repeated transient failures.",
"capacity": "[PROGRESS HINT] Sandbox capacity is temporarily unavailable.",
"partial_success": "[PROGRESS HINT] The tool has returned incomplete results multiple times.",
# Jaccard near-duplicate success: the tool is returning the same content repeatedly.
"success": "[PROGRESS HINT] The tool is returning duplicate results.",

View File

@ -21,7 +21,7 @@ TOOL_META_KEY = "deerflow_tool_meta"
PROGRESS_GUARD_ERROR_TYPE = "blocked_by_progress_guard"
ToolResultStatus = Literal["success", "error", "partial_success"]
RecommendedNextAction = Literal["continue", "rewrite_query", "try_alternative", "summarize", "stop"]
RecommendedNextAction = Literal["continue", "rewrite_query", "try_alternative", "retry_later", "summarize", "stop"]
TOOL_RESULT_STATUSES = frozenset(get_args(ToolResultStatus)) | {"unknown"}
TOOL_RESULT_NEXT_ACTIONS = frozenset(get_args(RecommendedNextAction)) | {"unknown"}
@ -36,6 +36,7 @@ class ToolResultMeta:
recommended_next_action: RecommendedNextAction
source: Literal["exception", "tool_return", "content_analysis", "progress_middleware"]
exit_code: int | None = None
retry_after_seconds: float | None = None
_UNKNOWN_ERROR: dict[str, object] = {
@ -43,7 +44,7 @@ _UNKNOWN_ERROR: dict[str, object] = {
"recoverable_by_model": True,
"recommended_next_action": "try_alternative",
}
TOOL_RESULT_ERROR_TYPES = frozenset({"auth", "rate_limited", "transient", "config", "permission", "no_results", "not_found", "internal", "unknown", PROGRESS_GUARD_ERROR_TYPE})
TOOL_RESULT_ERROR_TYPES = frozenset({"auth", "rate_limited", "transient", "capacity", "config", "permission", "no_results", "not_found", "internal", "unknown", PROGRESS_GUARD_ERROR_TYPE})
class _ModelToolResultText(str):

View File

@ -16,6 +16,7 @@ from pathlib import Path
from langchain.tools import tool
from langchain_core.messages import ToolMessage
from deerflow.agents.middlewares.tool_result_meta import TOOL_META_KEY
from deerflow.agents.thread_state import ThreadDataState
from deerflow.authz.sandbox_authz import (
authorize_sandbox_execution,
@ -31,6 +32,7 @@ from deerflow.runtime.user_context import resolve_runtime_user_id
from deerflow.sandbox.command_scope import command_owner
from deerflow.sandbox.exceptions import (
SandboxAuthorizationError,
SandboxCapacityExceededError,
SandboxError,
SandboxFileNotFoundError,
SandboxNotFoundError,
@ -2401,6 +2403,36 @@ async def ensure_sandbox_initialized_async(runtime: Runtime | None = None) -> Sa
return sandbox
def _sandbox_capacity_result(runtime: Runtime, error: SandboxCapacityExceededError, tool_name: str | None) -> str | ToolMessage:
reason = {
"capacity": "The sandbox pool is busy",
"capacity_backend": "The sandbox capacity service is unavailable",
"capacity_initializing": "The sandbox capacity service is initializing",
"shutdown": "The sandbox provider is shutting down",
}.get(error.reason, "Sandbox capacity is temporarily unavailable")
retry_after = error.retry_after_seconds
content = f"Error: {reason}. Retry in about {retry_after:g} seconds. If the sandbox is still unavailable, tell the user to try again later."
call_id = getattr(runtime, "tool_call_id", None)
if not isinstance(call_id, str) or not call_id:
return content
return ToolMessage(
content=content,
name=tool_name,
tool_call_id=call_id,
status="error",
additional_kwargs={
TOOL_META_KEY: {
"status": "error",
"error_type": "capacity",
"recoverable_by_model": True,
"recommended_next_action": "retry_later",
"retry_after_seconds": retry_after,
"source": "tool_return",
}
},
)
async def _run_sync_tool_after_async_sandbox_init(
func: Callable[..., str | ToolMessage] | None,
runtime: Runtime,
@ -2421,6 +2453,10 @@ async def _run_sync_tool_after_async_sandbox_init(
if func is bash_tool.func and owner and getattr(sandbox, "supports_command_cancellation", False):
signal_cancel = partial(sandbox.request_command_cancel, owner)
return await run_sync_lifecycle_operation(func, runtime, *args, _on_cancel=signal_cancel)
except SandboxCapacityExceededError as e:
# Built-in tool callbacks are named <tool name>_tool.
tool_name = getattr(func, "__name__", "").removesuffix("_tool") or None
return _sandbox_capacity_result(runtime, e, tool_name)
except SandboxError as e:
text = f"Error: {e}"
return _error_result(text, e) if _error_result else text
@ -2923,6 +2959,8 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str | To
)
content = _truncate_bash_output(mask_secret_values(output, injected_env), max_chars)
return _bash_command_result(runtime, output, content)
except SandboxCapacityExceededError as e:
return _sandbox_capacity_result(runtime, e, "bash")
except SandboxError as e:
return mask_secret_values(f"Error: {e}", redaction_env)
except PermissionError as e:
@ -2965,7 +3003,7 @@ bash_tool.coroutine = _bash_tool_async
@tool("ls", parse_docstring=True)
def ls_tool(runtime: Runtime, path: str, description: str = "") -> str:
def ls_tool(runtime: Runtime, path: str, description: str = "") -> str | ToolMessage:
"""List the contents of a directory up to 2 levels deep in tree format.
Args:
@ -3018,6 +3056,8 @@ def ls_tool(runtime: Runtime, path: str, description: str = "") -> str:
except Exception:
max_chars = 20000
return _truncate_ls_output(output, max_chars)
except SandboxCapacityExceededError as e:
return _sandbox_capacity_result(runtime, e, "ls")
except SandboxError as e:
return f"Error: {e}"
except FileNotFoundError:
@ -3029,7 +3069,7 @@ def ls_tool(runtime: Runtime, path: str, description: str = "") -> str:
return f"Error: Unexpected error listing directory: {_sanitize_error(e, runtime)}"
async def _ls_tool_async(runtime: Runtime, path: str, description: str = "") -> str:
async def _ls_tool_async(runtime: Runtime, path: str, description: str = "") -> str | ToolMessage:
return await _run_sync_tool_after_async_sandbox_init(ls_tool.func, runtime, path, description)
@ -3044,7 +3084,7 @@ def glob_tool(
description: str = "",
include_dirs: bool = False,
max_results: int = _DEFAULT_GLOB_MAX_RESULTS,
) -> str:
) -> str | ToolMessage:
"""Find files or directories that match a glob pattern under a root directory.
Args:
@ -3082,6 +3122,8 @@ def glob_tool(
# so a root above a disabled skill still surfaces its files.
matches = _drop_disabled_skill_paths(matches, user_id=user_id)
return _format_glob_results(requested_path, matches, truncated)
except SandboxCapacityExceededError as e:
return _sandbox_capacity_result(runtime, e, "glob")
except SandboxError as e:
return f"Error: {e}"
except FileNotFoundError:
@ -3102,7 +3144,7 @@ async def _glob_tool_async(
description: str = "",
include_dirs: bool = False,
max_results: int = _DEFAULT_GLOB_MAX_RESULTS,
) -> str:
) -> str | ToolMessage:
return await _run_sync_tool_after_async_sandbox_init(
glob_tool.func,
runtime,
@ -3127,7 +3169,7 @@ def grep_tool(
literal: bool = False,
case_sensitive: bool = False,
max_results: int = _DEFAULT_GREP_MAX_RESULTS,
) -> str:
) -> str | ToolMessage:
"""Search for matching lines inside a text file or files under a root directory.
Args:
@ -3183,6 +3225,8 @@ def grep_tool(
allowed = set(_drop_disabled_skill_paths([match.path for match in matches], user_id=user_id))
matches = [match for match in matches if match.path in allowed]
return _format_grep_results(requested_path, matches, truncated)
except SandboxCapacityExceededError as e:
return _sandbox_capacity_result(runtime, e, "grep")
except SandboxError as e:
return f"Error: {e}"
except FileNotFoundError:
@ -3207,7 +3251,7 @@ async def _grep_tool_async(
literal: bool = False,
case_sensitive: bool = False,
max_results: int = _DEFAULT_GREP_MAX_RESULTS,
) -> str:
) -> str | ToolMessage:
return await _run_sync_tool_after_async_sandbox_init(
grep_tool.func,
runtime,
@ -3373,6 +3417,8 @@ def read_file_tool(
if max_chars == 0 or len(numbered) <= max_chars:
output = numbered
return _read_file_result(runtime, output, status="partial_success" if max_chars != 0 and len(content) > max_chars else "success")
except SandboxCapacityExceededError as e:
return _sandbox_capacity_result(runtime, e, "read_file")
except SandboxError as e:
return _read_file_failure(runtime, f"Error: {e}", e)
except FileNotFoundError as e:
@ -3444,7 +3490,7 @@ def write_file_tool(
content: str,
description: str = "",
append: bool = False,
) -> str:
) -> str | ToolMessage:
"""Write text content to a file. By default this overwrites the target file; set append=True to add content to the end without replacing existing content.
READ-BEFORE-WRITE (issue #3857): if the target file already exists (including
@ -3516,6 +3562,8 @@ def write_file_tool(
with get_file_operation_lock(sandbox, path):
sandbox.write_file(path, content, append)
return "OK"
except SandboxCapacityExceededError as e:
return _sandbox_capacity_result(runtime, e, "write_file")
except SandboxError as e:
return _format_write_file_error(requested_path, e, runtime)
except PermissionError:
@ -3540,7 +3588,7 @@ async def _write_file_tool_async(
content: str,
description: str = "",
append: bool = False,
) -> str:
) -> str | ToolMessage:
placeholder_error = _reject_elision_placeholder_content(content)
if placeholder_error is not None:
return placeholder_error
@ -3579,7 +3627,7 @@ def str_replace_tool(
new_str: str,
description: str = "",
replace_all: bool = False,
) -> str:
) -> str | ToolMessage:
"""Replace a substring in a file with another substring.
If `replace_all` is False (default), the substring to replace must appear **exactly once** in the file.
@ -3618,6 +3666,8 @@ def str_replace_tool(
content = content.replace(old_str, new_str, 1)
sandbox.write_file(path, content)
return "OK"
except SandboxCapacityExceededError as e:
return _sandbox_capacity_result(runtime, e, "str_replace")
except SandboxError as e:
return f"Error: {e}"
except FileNotFoundError:
@ -3635,7 +3685,7 @@ async def _str_replace_tool_async(
new_str: str,
description: str = "",
replace_all: bool = False,
) -> str:
) -> str | ToolMessage:
return await _run_sync_tool_after_async_sandbox_init(
str_replace_tool.func,
runtime,

View File

@ -4,20 +4,32 @@ from __future__ import annotations
import asyncio
import threading
from unittest.mock import AsyncMock, Mock
import pytest
from langchain.tools import ToolRuntime
from langchain_core.messages import AIMessage, ToolMessage
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.types import Overwrite
from deerflow.sandbox.exceptions import SandboxNotFoundError
from deerflow.agents.middlewares.tool_result_meta import TOOL_META_KEY, normalize_tool_message, tool_result_for_model
from deerflow.sandbox.exceptions import SandboxCapacityExceededError, SandboxNotFoundError
from deerflow.sandbox.lease import SANDBOX_LEASE_OWNER_CONTEXT_KEY, get_sandbox_lease_manager
from deerflow.sandbox.sandbox import Sandbox
from deerflow.sandbox.sandbox_provider import SandboxProvider, reset_sandbox_provider, set_sandbox_provider
from deerflow.sandbox.search import GrepMatch
from deerflow.sandbox.tools import (
_run_sync_tool_after_async_sandbox_init,
bash_tool,
ensure_sandbox_initialized,
ensure_sandbox_initialized_async,
glob_tool,
grep_tool,
ls_tool,
read_file_tool,
str_replace_tool,
write_file_tool,
)
@ -144,6 +156,56 @@ def _make_runtime(state: dict) -> ToolRuntime:
)
@pytest.mark.anyio
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
@pytest.mark.parametrize(
("tool", "args", "reason", "explanation"),
[
(bash_tool, {"command": "echo test"}, "capacity", "sandbox pool is busy"),
(ls_tool, {"path": "/mnt/user-data/workspace"}, "capacity", "sandbox pool is busy"),
(glob_tool, {"path": "/mnt/user-data/workspace", "pattern": "*.txt"}, "capacity", "sandbox pool is busy"),
(grep_tool, {"path": "/mnt/user-data/workspace", "pattern": "test"}, "capacity", "sandbox pool is busy"),
(read_file_tool, {"path": "/mnt/user-data/workspace/note.txt"}, "capacity", "sandbox pool is busy"),
(str_replace_tool, {"path": "/mnt/user-data/workspace/note.txt", "old_str": "a", "new_str": "b"}, "capacity", "sandbox pool is busy"),
(write_file_tool, {"path": "/mnt/user-data/workspace/note.txt", "content": "note"}, "shutdown", "provider is shutting down"),
(ls_tool, {"path": "/mnt/user-data/workspace"}, "capacity_backend", "sandbox capacity service is unavailable"),
(ls_tool, {"path": "/mnt/user-data/workspace"}, "capacity_initializing", "sandbox capacity service is initializing"),
(ls_tool, {"path": "/mnt/user-data/workspace"}, "other", "capacity is temporarily unavailable"),
],
ids=["bash", "ls", "glob", "grep", "read-file", "str-replace", "write-file", "backend-unavailable", "initializing", "other-reason"],
)
async def test_capacity_rejection_reaches_the_model(tool, args, reason, explanation, asynchronous, monkeypatch):
error = SandboxCapacityExceededError(replicas=2, retry_after_seconds=17, reason=reason)
provider = _FallthroughProvider()
acquire = AsyncMock(side_effect=error) if asynchronous else Mock(side_effect=error)
monkeypatch.setattr(provider, "acquire_async" if asynchronous else "acquire", acquire)
graph = StateGraph(MessagesState).add_node("tools", ToolNode([tool])).add_edge(START, "tools").compile()
inputs = {"messages": [AIMessage(content="", tool_calls=[{"name": tool.name, "args": args, "id": "call-1"}])]}
config = {"configurable": {"thread_id": "capacity-test"}}
set_sandbox_provider(provider)
try:
result = await graph.ainvoke(inputs, config) if asynchronous else await asyncio.to_thread(graph.invoke, inputs, config)
finally:
reset_sandbox_provider()
acquire.assert_called_once()
if asynchronous:
acquire.assert_awaited_once()
message = result["messages"][-1]
assert isinstance(message, ToolMessage)
assert (message.tool_call_id, message.name, message.status) == ("call-1", tool.name, "error")
meta = normalize_tool_message(message).additional_kwargs[TOOL_META_KEY]
assert meta["error_type"] == "capacity"
assert meta["recommended_next_action"] == "retry_later"
assert meta["retry_after_seconds"] == 17
assert meta["recoverable_by_model"] is True
model_message = tool_result_for_model(message)
assert explanation in model_message.content
assert "17 seconds" in model_message.content
assert "tell the user" in model_message.content
def test_post_acquire_lookup_failure_unwinds_sync_execution_lease() -> None:
provider = _PostAcquireLookupFailureProvider()
set_sandbox_provider(provider)

View File

@ -802,6 +802,9 @@ async def worker_gateway(runtime, tmp_path):
runs, state, request, entered, _ = runtime
engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'workers.db'}")
# Match the Gateway journal mode so concurrent readers do not block worker commits.
async with engine.connect() as connection:
await connection.exec_driver_sql("PRAGMA journal_mode=WAL")
await bootstrap_schema(engine, backend="sqlite")
factory = async_sessionmaker(engine)
async with factory.begin() as session:
@ -930,6 +933,7 @@ async def test_coordinator_recovers_its_decision_and_runs_dependent_workers(work
from langchain_core.messages import AIMessage
from langchain_core.outputs import ChatGeneration, LLMResult
from sqlalchemy import text
client, runs, state, entered, _ = worker_gateway
@ -983,9 +987,13 @@ async def test_coordinator_recovers_its_decision_and_runs_dependent_workers(work
assert report["status"] == research["status"] == "queued"
assert report["run_settings"] == research["run_settings"] == settings
await _restart_coordination(state)
state.coordination_workers.start_recovery()
await asyncio.wait_for(entered.wait(), 8)
# Keep a read transaction open while recovery admits the first worker.
async with state.coordination_workers.repo._sessions() as reader:
await reader.execute(text("BEGIN"))
assert await reader.scalar(text("SELECT id FROM coord_tasks WHERE id = :task_id"), {"task_id": task_id}) == task_id
await _restart_coordination(state)
state.coordination_workers.start_recovery()
await asyncio.wait_for(entered.wait(), 8)
waiting = (await client.get(f"{url}/{report['id']}")).raise_for_status().json()
assert waiting["execution"] is None
state.release_worker.set()

View File

@ -3,6 +3,7 @@ import logging
from types import SimpleNamespace
import httpx
import pytest
from deerflow.logging_config import TraceContextFilter, configure_logging
from deerflow.trace_context import request_trace_context
@ -119,7 +120,13 @@ def test_url_redaction_filter_rewrites_request_records() -> None:
assert plain.getMessage() == "keep this"
def test_url_redaction_filter_covers_urllib3_redirect_records() -> None:
@pytest.fixture
def urllib3_debug_logging(caplog: pytest.LogCaptureFixture) -> None:
# SDK setup can pin the urllib3 parent to WARNING, regardless of the root level.
caplog.set_level(logging.DEBUG, logger="urllib3")
def test_url_redaction_filter_covers_urllib3_redirect_records(urllib3_debug_logging) -> None:
"""Real-emitter wiring: urllib3 logs through CHILD loggers, and a filter on
the bare ``urllib3`` logger never sees propagated records (logger filters
are not inherited). Verified against the installed urllib3 2.7.0:
@ -214,7 +221,7 @@ def test_url_redaction_filter_covers_urllib3_request_line_records() -> None:
assert "BearerSecret" not in http2.getMessage()
def test_url_redaction_filter_covers_urllib3_request_line_through_real_emit() -> None:
def test_url_redaction_filter_covers_urllib3_request_line_through_real_emit(urllib3_debug_logging) -> None:
"""Real-emitter wiring for the per-request line: urllib3 logs through the
``urllib3.connectionpool`` child logger at DEBUG, so only the
handler-level filters installed by configure_logging can rewrite the
@ -386,7 +393,7 @@ def test_url_redaction_filter_covers_urllib3_retry_lines() -> None:
assert plain_conn.getMessage() == "Starting new HTTP connection (1): cdn.example:443"
def test_url_redaction_filter_covers_urllib3_retry_lines_through_real_emit() -> None:
def test_url_redaction_filter_covers_urllib3_retry_lines_through_real_emit(urllib3_debug_logging) -> None:
"""Real-emitter wiring for the retry lines: the increment line is produced
by actually calling ``Retry.increment`` (retry.py:545 logs through the
``urllib3.util.retry`` child logger at DEBUG), and the connectionpool

View File

@ -333,13 +333,20 @@ def test_recoverable_errors_stay_warned_indefinitely():
assert state.consecutive_problems == 10
def test_recoverable_error_re_injects_hint_past_escalation():
@pytest.mark.parametrize(
("error_type", "action", "hint_text"),
[
("no_results", "rewrite_query", "rephrasing your search"),
("capacity", "retry_later", "try again later"),
],
)
def test_recoverable_error_re_injects_hint_past_escalation(error_type, action, hint_text):
# After crossing threshold+escalation for a recoverable error, each additional
# problem call should still queue a hint.
mw = _make_mw(stagnation_threshold=2, warn_escalation_count=1, inject_assessment=True)
rt = _make_runtime()
req = _make_tool_request(runtime=rt)
error_msg = _make_error_message()
error_msg = _make_error_message(error_type=error_type, recommended_next_action=action)
def handler(_r):
return error_msg
@ -353,7 +360,7 @@ def test_recoverable_error_re_injects_hint_past_escalation():
# not just the initial WARNED hint at call 2.
hints = mw._drain_pending(rt)
assert len(hints) >= 2
assert all("PROGRESS HINT" in h for h in hints)
assert all("PROGRESS HINT" in hint and hint_text in hint for hint in hints)
# ---------------------------------------------------------------------------

View File

@ -20,6 +20,10 @@ unanswerable approval cannot block the chat.
See [HITL Tool Approval](../../backend/docs/CONFIGURATION.md#hitl-tool-approval) for
configuration and safety semantics.
When a sandbox provider rejects a tool call because capacity is unavailable,
the tool tells the agent how long to wait before retrying. If capacity remains
unavailable, the result asks the agent to tell the user to try again later.
Agents can call the read-only `inspect_run_status` tool to inspect visible run
token usage, message and tool-call counts, an approximate context-window fill,
and whether a summary or unfinished to-dos exist. It returns counts only, not