fix(agent): redact private recovery and reconnect diagnostics
This commit is contained in:
1 parent
2640251076
commit
d37d7c07c0
6 files changed
+160
-14
No files matched your search
+14
-2
@@ -1458,6 +1458,10 @@ class AgentLoop:
|
|||||||
msg = deferred.pop(0)
|
msg = deferred.pop(0)
|
||||||
if not deferred:
|
if not deferred:
|
||||||
self._deferred_automation_turns.pop(session_key)
|
self._deferred_automation_turns.pop(session_key)
|
||||||
|
session = self.sessions.get_cached(session_key)
|
||||||
|
log_content = session is None or (
|
||||||
|
session.policy.persist and session.policy.log_content
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
await self._dispatch_one(msg, pending)
|
await self._dispatch_one(msg, pending)
|
||||||
except asyncio.CancelledError as exc:
|
except asyncio.CancelledError as exc:
|
||||||
@@ -1465,7 +1469,7 @@ class AgentLoop:
|
|||||||
coordinator.complete(msg, error=exc)
|
coordinator.complete(msg, error=exc)
|
||||||
raise
|
raise
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(
|
logger.opt(exception=log_content).error(
|
||||||
"Session worker failed one message for {}; continuing FIFO",
|
"Session worker failed one message for {}; continuing FIFO",
|
||||||
session_key,
|
session_key,
|
||||||
)
|
)
|
||||||
@@ -1504,6 +1508,12 @@ class AgentLoop:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Process one root message while later inputs remain in its session inbox."""
|
"""Process one root message while later inputs remain in its session inbox."""
|
||||||
session_key = self._effective_session_key(msg)
|
session_key = self._effective_session_key(msg)
|
||||||
|
# The request context is reset before errors reach this boundary, and
|
||||||
|
# discard may evict the session while a turn is still unwinding.
|
||||||
|
session = self.sessions.get_cached(session_key)
|
||||||
|
log_content = session is None or (
|
||||||
|
session.policy.persist and session.policy.log_content
|
||||||
|
)
|
||||||
recovery_task_registered = False
|
recovery_task_registered = False
|
||||||
recovery_admission = self._recovery_admission
|
recovery_admission = self._recovery_admission
|
||||||
current_task: asyncio.Task[Any] | None = None
|
current_task: asyncio.Task[Any] | None = None
|
||||||
@@ -1588,7 +1598,9 @@ class AgentLoop:
|
|||||||
)
|
)
|
||||||
raise
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.exception("Error processing message for session {}", session_key)
|
logger.opt(exception=log_content).error(
|
||||||
|
"Error processing message for session {}", session_key,
|
||||||
|
)
|
||||||
await delivery.fail(
|
await delivery.fail(
|
||||||
publish_completion=not turn_continuation.internal_continuation_pending(
|
publish_completion=not turn_continuation.internal_continuation_pending(
|
||||||
msg.metadata
|
msg.metadata
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ from nanobot.agent.context_governance import (
|
|||||||
TranscriptBuilder,
|
TranscriptBuilder,
|
||||||
)
|
)
|
||||||
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
|
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
|
||||||
|
from nanobot.agent.tools.context import tool_log_content_allowed
|
||||||
from nanobot.agent.tools.execution import execute_tool_calls
|
from nanobot.agent.tools.execution import execute_tool_calls
|
||||||
from nanobot.agent.tools.registry import ToolRegistry
|
from nanobot.agent.tools.registry import ToolRegistry
|
||||||
from nanobot.events import NO_EVENTS, EventSink
|
from nanobot.events import NO_EVENTS, EventSink
|
||||||
@@ -219,7 +220,7 @@ class AgentRunner:
|
|||||||
try:
|
try:
|
||||||
content = callback()
|
content = callback()
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("continuation_callback failed")
|
logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")
|
||||||
return None
|
return None
|
||||||
if content is None or not content.strip():
|
if content is None or not content.strip():
|
||||||
return None
|
return None
|
||||||
@@ -242,7 +243,7 @@ class AgentRunner:
|
|||||||
try:
|
try:
|
||||||
items = await callback()
|
items = await callback()
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("injection_callback failed")
|
logger.opt(exception=tool_log_content_allowed()).error("injection_callback failed")
|
||||||
return []
|
return []
|
||||||
if not items:
|
if not items:
|
||||||
return []
|
return []
|
||||||
@@ -318,7 +319,7 @@ class AgentRunner:
|
|||||||
try:
|
try:
|
||||||
await hook.on_finally(context)
|
await hook.on_finally(context)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(
|
logger.opt(exception=tool_log_content_allowed()).error(
|
||||||
"AgentHook.on_finally error after {}",
|
"AgentHook.on_finally error after {}",
|
||||||
context.stop_reason or "run exception",
|
context.stop_reason or "run exception",
|
||||||
)
|
)
|
||||||
@@ -1181,7 +1182,7 @@ class AgentRunner:
|
|||||||
transcript=messages,
|
transcript=messages,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(
|
logger.opt(exception=tool_log_content_allowed()).error(
|
||||||
"Budget-exhausted finalization failed for {}; using fallback",
|
"Budget-exhausted finalization failed for {}; using fallback",
|
||||||
spec.session_key or "default",
|
spec.session_key or "default",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -213,13 +213,14 @@ def _is_transient_connection_failure(exc: BaseException) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def _log_mcp_connection_failure(name: str, exc: BaseException, hint: str = "") -> None:
|
def _log_mcp_connection_failure(name: str, exc: BaseException, hint: str = "") -> None:
|
||||||
|
exception = exc if tool_log_content_allowed() else False
|
||||||
if _is_transient_connection_failure(exc):
|
if _is_transient_connection_failure(exc):
|
||||||
logger.warning("MCP server '{}': transient connection failure", name)
|
logger.warning("MCP server '{}': transient connection failure", name)
|
||||||
logger.opt(exception=exc).debug(
|
logger.opt(exception=exception).debug(
|
||||||
"MCP server '{}' transient connection failure details", name
|
"MCP server '{}' transient connection failure details", name
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
logger.opt(exception=exc).error("MCP server '{}': failed to connect: {}", name, hint)
|
logger.opt(exception=exception).error("MCP server '{}': failed to connect: {}", name, hint)
|
||||||
|
|
||||||
|
|
||||||
def _is_session_terminated(exc: BaseException) -> bool:
|
def _is_session_terminated(exc: BaseException) -> bool:
|
||||||
|
|||||||
@@ -170,6 +170,41 @@ async def test_direct_transient_run_never_spills_before_cancellation(tmp_path) -
|
|||||||
assert current_request_context() is None
|
assert current_request_context() is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("private", [True, False])
|
||||||
|
@pytest.mark.parametrize("failure", ["runner", "discard", "queue"])
|
||||||
|
async def test_session_worker_errors_keep_private_content_out_of_logs(
|
||||||
|
tmp_path, private, failure, monkeypatch,
|
||||||
|
) -> None:
|
||||||
|
loop = _loop(tmp_path, [])
|
||||||
|
key = "websocket:synthetic-worker-error"
|
||||||
|
if private:
|
||||||
|
loop.sessions.get_or_create_transient(key)
|
||||||
|
else:
|
||||||
|
loop.sessions.get_or_create(key)
|
||||||
|
secret = "synthetic-private-worker-content"
|
||||||
|
if failure == "runner":
|
||||||
|
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(secret))
|
||||||
|
else:
|
||||||
|
async def fail_after_discard(*args, **kwargs):
|
||||||
|
# The privacy snapshot must survive cache eviction during failure.
|
||||||
|
loop.sessions.invalidate(key)
|
||||||
|
raise ValueError(secret)
|
||||||
|
|
||||||
|
target = "_process_message" if failure == "discard" else "_dispatch_one"
|
||||||
|
monkeypatch.setattr(loop, target, fail_after_discard)
|
||||||
|
records = []
|
||||||
|
sink = logger.add(lambda message: records.append(message.record), format="{message}")
|
||||||
|
try:
|
||||||
|
await run_session(loop, _message(key, secret))
|
||||||
|
finally:
|
||||||
|
logger.remove(sink)
|
||||||
|
errors = [r for r in records if r["level"].name == "ERROR"]
|
||||||
|
assert errors
|
||||||
|
assert all(r["exception"] is None for r in errors) is private
|
||||||
|
if private:
|
||||||
|
assert secret not in str([r["message"] for r in records])
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_transient_session_stays_outside_unified_session(tmp_path) -> None:
|
async def test_transient_session_stays_outside_unified_session(tmp_path) -> None:
|
||||||
loop = _loop(tmp_path, ["private answer"], unified_session=True)
|
loop = _loop(tmp_path, ["private answer"], unified_session=True)
|
||||||
|
|||||||
@@ -5,9 +5,11 @@ from unittest.mock import AsyncMock, MagicMock
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from nanobot.agent.loop import AgentLoop
|
from nanobot.agent.loop import AgentLoop
|
||||||
|
from nanobot.agent.tools.context import current_request_context
|
||||||
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
|
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
|
||||||
from nanobot.command.builtin import cmd_user_shell
|
from nanobot.command.builtin import cmd_user_shell
|
||||||
from nanobot.command.router import CommandContext
|
from nanobot.command.router import CommandContext
|
||||||
|
from nanobot.session.manager import Session, SessionPolicy
|
||||||
|
|
||||||
|
|
||||||
def _context(loop: MagicMock, *, trusted: bool, command: str = "pwd") -> CommandContext:
|
def _context(loop: MagicMock, *, trusted: bool, command: str = "pwd") -> CommandContext:
|
||||||
@@ -44,22 +46,36 @@ async def test_user_shell_rejects_untrusted_transport_metadata() -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_user_shell_uses_exec_tool_with_workspace_scope(tmp_path: Path) -> None:
|
@pytest.mark.parametrize("log_content", [True, False])
|
||||||
|
@pytest.mark.parametrize("context_session", [True, False])
|
||||||
|
async def test_user_shell_uses_exec_tool_with_workspace_scope(
|
||||||
|
tmp_path: Path, log_content: bool, context_session: bool,
|
||||||
|
) -> None:
|
||||||
|
async def execute(**kwargs):
|
||||||
|
request = current_request_context()
|
||||||
|
assert request is not None
|
||||||
|
assert request.log_content is log_content
|
||||||
|
assert request.workspace == tmp_path
|
||||||
|
return f"{tmp_path}\n\nExit code: 0"
|
||||||
|
|
||||||
tool = MagicMock()
|
tool = MagicMock()
|
||||||
tool.execute = AsyncMock(return_value=f"{tmp_path}\n\nExit code: 0")
|
tool.execute = AsyncMock(side_effect=execute)
|
||||||
session = SimpleNamespace(metadata={})
|
session = Session(key="websocket:chat", policy=SessionPolicy(log_content=log_content))
|
||||||
scope = SimpleNamespace(project_path=tmp_path)
|
scope = SimpleNamespace(project_path=tmp_path)
|
||||||
loop = MagicMock()
|
loop = MagicMock()
|
||||||
loop.tools.get.return_value = tool
|
loop.tools.get.return_value = tool
|
||||||
loop.sessions.get_or_create.return_value = session
|
loop.sessions.get_or_create.return_value = session
|
||||||
loop.workspace_scopes.for_turn.return_value = scope
|
loop.workspace_scopes.for_turn.return_value = scope
|
||||||
ctx = _context(loop, trusted=True)
|
ctx = _context(loop, trusted=True)
|
||||||
|
if context_session:
|
||||||
|
ctx.session = session
|
||||||
|
|
||||||
response = await AgentLoop.execute_user_shell_command(loop, ctx)
|
response = await AgentLoop.execute_user_shell_command(loop, ctx)
|
||||||
|
|
||||||
tool.execute.assert_awaited_once_with(command="pwd", working_dir=str(tmp_path))
|
tool.execute.assert_awaited_once_with(command="pwd", working_dir=str(tmp_path))
|
||||||
assert response.content.endswith("Exit code: 0")
|
assert response.content.endswith("Exit code: 0")
|
||||||
assert response.metadata["render_as"] == "text"
|
assert response.metadata["render_as"] == "text"
|
||||||
|
assert current_request_context() is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -2,31 +2,112 @@
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import sys
|
import sys
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from agent.runner_helpers import make_run_spec
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
from mcp import types
|
from mcp import types
|
||||||
from mcp.shared.exceptions import McpError
|
from mcp.shared.exceptions import McpError
|
||||||
|
|
||||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||||
|
from nanobot.agent.runner import AgentRunner
|
||||||
from nanobot.agent.tools.context import (
|
from nanobot.agent.tools.context import (
|
||||||
RequestContext,
|
RequestContext,
|
||||||
request_context,
|
request_context,
|
||||||
tool_log_content_allowed,
|
tool_log_content_allowed,
|
||||||
)
|
)
|
||||||
from nanobot.agent.tools.execution import _classify_violation, execute_tool_calls
|
from nanobot.agent.tools.execution import _classify_violation, execute_tool_calls
|
||||||
from nanobot.agent.tools.mcp import MCPPromptWrapper, MCPResourceWrapper, MCPToolWrapper
|
from nanobot.agent.tools.mcp import (
|
||||||
|
MCPPromptWrapper,
|
||||||
|
MCPProvider,
|
||||||
|
MCPResourceWrapper,
|
||||||
|
MCPToolWrapper,
|
||||||
|
)
|
||||||
from nanobot.agent.tools.registry import ToolRegistry
|
from nanobot.agent.tools.registry import ToolRegistry
|
||||||
from nanobot.agent.tools.web import WebFetchTool, WebSearchTool, _redact_url_for_log
|
from nanobot.agent.tools.web import WebFetchTool, WebSearchTool, _redact_url_for_log
|
||||||
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
|
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
|
||||||
from nanobot.config.schema import WebSearchConfig
|
from nanobot.config.schema import MCPServerConfig, WebSearchConfig
|
||||||
from nanobot.providers.base import ToolCallRequest
|
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
|
||||||
|
|
||||||
_SECRET = "synthetic-private-detail"
|
_SECRET = "synthetic-private-detail"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("log_content", [True, False])
|
||||||
|
@pytest.mark.parametrize("transient", [True, False])
|
||||||
|
async def test_mcp_reconnect_failure_obeys_private_log_policy(
|
||||||
|
log_content, transient, monkeypatch, diagnostic_records,
|
||||||
|
):
|
||||||
|
@asynccontextmanager
|
||||||
|
async def broken_stdio(_params):
|
||||||
|
if transient:
|
||||||
|
raise ConnectionResetError(_SECRET)
|
||||||
|
raise RuntimeError(_SECRET)
|
||||||
|
yield # pragma: no cover
|
||||||
|
|
||||||
|
monkeypatch.setattr("mcp.client.stdio.stdio_client", broken_stdio)
|
||||||
|
session = SimpleNamespace(call_tool=AsyncMock(side_effect=RuntimeError("session terminated")))
|
||||||
|
wrapper = MCPToolWrapper(session, "sample", SimpleNamespace(
|
||||||
|
name="search", description="synthetic", inputSchema={},
|
||||||
|
))
|
||||||
|
registry = ToolRegistry()
|
||||||
|
registry.register(wrapper)
|
||||||
|
provider = MCPProvider({"sample": MCPServerConfig(command="synthetic-mcp")}, registry)
|
||||||
|
provider._attach_reconnect_handlers({"sample"})
|
||||||
|
try:
|
||||||
|
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
|
||||||
|
result = await wrapper.execute(query=_SECRET)
|
||||||
|
finally:
|
||||||
|
await provider.aclose()
|
||||||
|
|
||||||
|
assert "failed" in result
|
||||||
|
failures = [
|
||||||
|
r for r in diagnostic_records
|
||||||
|
if "connection failure" in r["message"] or "failed to connect" in r["message"]
|
||||||
|
]
|
||||||
|
assert failures
|
||||||
|
assert any(r["exception"] is not None for r in failures) is log_content
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("log_content", [True, False])
|
||||||
|
@pytest.mark.parametrize("kind", ["injection", "continuation", "finalization", "finally"])
|
||||||
|
async def test_runner_recovery_diagnostics_obey_private_policy(log_content, kind, diagnostic_records):
|
||||||
|
provider = MagicMock(spec=LLMProvider)
|
||||||
|
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
|
||||||
|
spec = make_run_spec(
|
||||||
|
provider, model="test-model", initial_messages=[{"role": "user", "content": _SECRET}],
|
||||||
|
tools=ToolRegistry(), max_iterations=1, max_tool_result_chars=100,
|
||||||
|
)
|
||||||
|
if kind == "injection":
|
||||||
|
spec.injection_callback = AsyncMock(side_effect=ValueError(_SECRET))
|
||||||
|
elif kind == "continuation":
|
||||||
|
spec.continuation_callback = MagicMock(side_effect=ValueError(_SECRET))
|
||||||
|
elif kind == "finalization":
|
||||||
|
spec.max_iterations = 0
|
||||||
|
provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(_SECRET))
|
||||||
|
else:
|
||||||
|
class BrokenFinallyHook(AgentHook):
|
||||||
|
async def before_run(self, context):
|
||||||
|
raise ValueError(_SECRET)
|
||||||
|
|
||||||
|
async def on_finally(self, context):
|
||||||
|
raise RuntimeError("synthetic cleanup failure")
|
||||||
|
|
||||||
|
spec.hook = BrokenFinallyHook()
|
||||||
|
|
||||||
|
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
|
||||||
|
if kind == "finally":
|
||||||
|
with pytest.raises(ValueError, match=_SECRET):
|
||||||
|
await AgentRunner().run(spec)
|
||||||
|
else:
|
||||||
|
await AgentRunner().run(spec)
|
||||||
|
errors = [r for r in diagnostic_records if r["level"].name == "ERROR"]
|
||||||
|
assert errors
|
||||||
|
assert all((r["exception"] is not None) is log_content for r in errors)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def diagnostic_records():
|
def diagnostic_records():
|
||||||
records = []
|
records = []
|
||||||
|
|||||||
Reference in new issue
Block a user