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)
|
||||
if not deferred:
|
||||
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:
|
||||
await self._dispatch_one(msg, pending)
|
||||
except asyncio.CancelledError as exc:
|
||||
@@ -1465,7 +1469,7 @@ class AgentLoop:
|
||||
coordinator.complete(msg, error=exc)
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(
|
||||
logger.opt(exception=log_content).error(
|
||||
"Session worker failed one message for {}; continuing FIFO",
|
||||
session_key,
|
||||
)
|
||||
@@ -1504,6 +1508,12 @@ class AgentLoop:
|
||||
) -> None:
|
||||
"""Process one root message while later inputs remain in its session inbox."""
|
||||
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_admission = self._recovery_admission
|
||||
current_task: asyncio.Task[Any] | None = None
|
||||
@@ -1588,7 +1598,9 @@ class AgentLoop:
|
||||
)
|
||||
raise
|
||||
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(
|
||||
publish_completion=not turn_continuation.internal_continuation_pending(
|
||||
msg.metadata
|
||||
|
||||
@@ -23,6 +23,7 @@ from nanobot.agent.context_governance import (
|
||||
TranscriptBuilder,
|
||||
)
|
||||
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.registry import ToolRegistry
|
||||
from nanobot.events import NO_EVENTS, EventSink
|
||||
@@ -219,7 +220,7 @@ class AgentRunner:
|
||||
try:
|
||||
content = callback()
|
||||
except Exception:
|
||||
logger.exception("continuation_callback failed")
|
||||
logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")
|
||||
return None
|
||||
if content is None or not content.strip():
|
||||
return None
|
||||
@@ -242,7 +243,7 @@ class AgentRunner:
|
||||
try:
|
||||
items = await callback()
|
||||
except Exception:
|
||||
logger.exception("injection_callback failed")
|
||||
logger.opt(exception=tool_log_content_allowed()).error("injection_callback failed")
|
||||
return []
|
||||
if not items:
|
||||
return []
|
||||
@@ -318,7 +319,7 @@ class AgentRunner:
|
||||
try:
|
||||
await hook.on_finally(context)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"AgentHook.on_finally error after {}",
|
||||
context.stop_reason or "run exception",
|
||||
)
|
||||
@@ -1181,7 +1182,7 @@ class AgentRunner:
|
||||
transcript=messages,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
logger.opt(exception=tool_log_content_allowed()).error(
|
||||
"Budget-exhausted finalization failed for {}; using fallback",
|
||||
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:
|
||||
exception = exc if tool_log_content_allowed() else False
|
||||
if _is_transient_connection_failure(exc):
|
||||
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
|
||||
)
|
||||
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:
|
||||
|
||||
@@ -170,6 +170,41 @@ async def test_direct_transient_run_never_spills_before_cancellation(tmp_path) -
|
||||
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
|
||||
async def test_transient_session_stays_outside_unified_session(tmp_path) -> None:
|
||||
loop = _loop(tmp_path, ["private answer"], unified_session=True)
|
||||
|
||||
@@ -5,9 +5,11 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
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.command.builtin import cmd_user_shell
|
||||
from nanobot.command.router import CommandContext
|
||||
from nanobot.session.manager import Session, SessionPolicy
|
||||
|
||||
|
||||
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
|
||||
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.execute = AsyncMock(return_value=f"{tmp_path}\n\nExit code: 0")
|
||||
session = SimpleNamespace(metadata={})
|
||||
tool.execute = AsyncMock(side_effect=execute)
|
||||
session = Session(key="websocket:chat", policy=SessionPolicy(log_content=log_content))
|
||||
scope = SimpleNamespace(project_path=tmp_path)
|
||||
loop = MagicMock()
|
||||
loop.tools.get.return_value = tool
|
||||
loop.sessions.get_or_create.return_value = session
|
||||
loop.workspace_scopes.for_turn.return_value = scope
|
||||
ctx = _context(loop, trusted=True)
|
||||
if context_session:
|
||||
ctx.session = session
|
||||
|
||||
response = await AgentLoop.execute_user_shell_command(loop, ctx)
|
||||
|
||||
tool.execute.assert_awaited_once_with(command="pwd", working_dir=str(tmp_path))
|
||||
assert response.content.endswith("Exit code: 0")
|
||||
assert response.metadata["render_as"] == "text"
|
||||
assert current_request_context() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -2,31 +2,112 @@
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from loguru import logger
|
||||
from mcp import types
|
||||
from mcp.shared.exceptions import McpError
|
||||
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.agent.tools.context import (
|
||||
RequestContext,
|
||||
request_context,
|
||||
tool_log_content_allowed,
|
||||
)
|
||||
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.web import WebFetchTool, WebSearchTool, _redact_url_for_log
|
||||
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
|
||||
from nanobot.config.schema import WebSearchConfig
|
||||
from nanobot.providers.base import ToolCallRequest
|
||||
from nanobot.config.schema import MCPServerConfig, WebSearchConfig
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
|
||||
|
||||
_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
|
||||
def diagnostic_records():
|
||||
records = []
|
||||
|
||||
Reference in new issue
Block a user