hermes-agent/tests/tools/test_mcp_failure_classification.py
Teknium 39975613b1
test: prune wave 2 + speed fixes — 28,106 → 19,757 test functions, suite wall 315s → 294s
Second, deeper pass over tools/gateway/hermes_cli plus first pass over
the trees wave 1 missed (acp, acp_adapter, skills, computer_use, docker,
dashboard, conformance, monitoring, secret_sources, hermes_state,
providers). Same rubric as wave 1 (AGENTS.md test policy); security,
alternation/caching invariants, issue-number regressions, and E2E kept.

Real test-quality fixes found and rooted out along the way:
- tests/tools/test_command_guards.py made real auxiliary-LLM HTTPS calls
  (DEFAULT_CONFIG smart-approval leaked in) — pinned approval
  mode=manual via autouse fixture: 17.4s → 0.4s.
- test_model_switch_custom_providers.py / test_user_providers_model_switch.py
  silently probed live provider catalogs (~2s/test) — stubbed
  cached_provider_model_ids/provider_model_ids/fetch_api_models.
- test_telegram_noise_filter.py: 15-platform copy-paste matrix over
  shared gateway.run logic → 3 representative platforms (55s → 3.9s).
- test_gateway_shutdown.py: stop()'s 5s interrupt-deadline loop spun on
  MagicMock agents — interrupt.side_effect now clears _running_agents
  (22s → 1.0s).
- test_gateway_inactivity_timeout.py poll-harness timings shrunk 3-5x
  (24s → 1.1s); test_mcp_stability.py backoff/SIGTERM-grace sleeps
  patched (15.4s → 2.5s); test_async_delegation.py negative-drain wait
  5s → 0.5s.
- test_telegram_init_deadline.py: loop-block margin restored to 1.0s
  with rationale comment — the watchdog-dump assertion needs the loop
  blocked well past deadline+grace under parallel load (flaked once in
  the 40-worker verification run at a 0.2s margin).

Verification: full hermetic suite via scripts/run_tests.sh —
2,438 files, 21,718 tests passed, 0 failed, 293.9s wall.
Suite totals vs original baseline: 46,820 → 19,757 test functions
(−57.8%), wall 583.5s → 293.9s (−50%), subprocess CPU 13,564s → 11,623s.
2026-07-29 13:39:40 -07:00

169 lines
5.8 KiB
Python

"""Tests for exception-group unwrapping and failure classification in
``tools/mcp_tool.py`` (#65673, #66092).
The MCP SDK's anyio TaskGroups wrap real errors in ``BaseExceptionGroup``,
whose ``str()`` is "unhandled errors in a TaskGroup (N sub-exceptions)"
useless in logs. ``_unwrap_exception_group`` digs out the root cause;
``_classify_mcp_failure`` decides whether a failure is worth retrying.
"""
import asyncio
import errno
import logging
import pytest
from tools.mcp_tool import (
InvalidMcpUrlError,
MCPServerTask,
NonMcpEndpointError,
_classify_mcp_failure,
_unwrap_exception_group,
)
def _group(*excs, msg="unhandled errors in a TaskGroup") -> BaseExceptionGroup:
return BaseExceptionGroup(msg, list(excs))
# ── _unwrap_exception_group ──────────────────────────────────────────────────
class TestUnwrapExceptionGroup:
def test_plain_exception_passes_through(self):
exc = ConnectionError("boom")
assert _unwrap_exception_group(exc) is exc
def test_single_level_group(self):
inner = BrokenPipeError()
assert _unwrap_exception_group(_group(inner)) is inner
def test_system_exit_reraises(self):
with pytest.raises(SystemExit):
_unwrap_exception_group(_group(SystemExit(2)))
# ── _classify_mcp_failure ────────────────────────────────────────────────────
class TestClassifyMcpFailure:
@pytest.mark.parametrize("exc", [
ConnectionError("connection refused"),
ConnectionResetError("reset by peer"),
BrokenPipeError(),
EOFError(),
TimeoutError("read timeout"),
OSError(errno.ECONNRESET, "reset"),
RuntimeError("something odd"),
])
def test_transient_failures(self, exc):
assert _classify_mcp_failure(exc) == "transient"
def test_closed_resource_transient(self):
anyio = pytest.importorskip("anyio")
assert _classify_mcp_failure(anyio.ClosedResourceError()) == "transient"
def test_permanent_inside_taskgroup(self):
# Classification must apply to the UNWRAPPED root cause.
g = _group(_group(FileNotFoundError("cmd not found")))
assert _classify_mcp_failure(g) == "permanent"
# ── Keepalive failure log surfaces the root cause ────────────────────────────
@pytest.mark.no_isolate
def test_keepalive_failure_logs_root_cause(monkeypatch, tmp_path, caplog):
"""A keepalive that dies with a TaskGroup-wrapped BrokenPipeError (empty
str) must log 'BrokenPipeError', not 'unhandled errors in a TaskGroup'."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
from tools import mcp_tool
class _Task(MCPServerTask):
async def _keepalive_probe(self):
raise _group(BrokenPipeError())
task = _Task("pipey")
task._config = {"keepalive_interval": 0.01}
task.session = object()
monkeypatch.setattr(mcp_tool, "_MIN_KEEPALIVE_INTERVAL", 0.01)
async def _scenario():
with caplog.at_level(logging.WARNING, logger="tools.mcp_tool"):
reason = await task._wait_for_lifecycle_event()
assert reason == "reconnect"
asyncio.run(_scenario())
keepalive_logs = [
r.getMessage() for r in caplog.records if "keepalive failed" in r.getMessage()
]
assert keepalive_logs, "keepalive failure was not logged"
assert any("BrokenPipeError" in m for m in keepalive_logs), keepalive_logs
assert not any("unhandled errors in a TaskGroup" in m for m in keepalive_logs)
# ── run() parks permanent failures immediately ───────────────────────────────
@pytest.mark.no_isolate
def test_permanent_failure_parks_without_retry_ladder(monkeypatch, tmp_path, caplog):
"""A stdio command that doesn't exist (FileNotFoundError) must park after
ONE attempt — not burn _MAX_INITIAL_CONNECT_RETRIES identical warnings."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
from tools import mcp_tool
_real_sleep = asyncio.sleep
async def _fast_sleep(_delay, *a, **kw):
await _real_sleep(0)
monkeypatch.setattr(mcp_tool.asyncio, "sleep", _fast_sleep)
state = {"transport_calls": 0, "parked": False}
async def _scenario():
class _Task(MCPServerTask):
def _is_http(self):
return False
def _deregister_tools(self):
state["parked"] = True
self._registered_tool_names = []
async def _run_stdio(self, config):
state["transport_calls"] += 1
raise FileNotFoundError("nonexistent-mcp-command")
task = _Task("missing-cmd")
with caplog.at_level(logging.DEBUG, logger="tools.mcp_tool"):
run_task = asyncio.ensure_future(task.run({"command": "nope"}))
for _ in range(500):
await _real_sleep(0)
if state["parked"]:
break
assert state["parked"], "permanent failure never parked"
assert state["transport_calls"] == 1, (
f"permanent failure burned {state['transport_calls']} attempts — "
"should park immediately"
)
task._shutdown_event.set()
task._reconnect_event.set()
try:
await asyncio.wait_for(run_task, timeout=15)
except (asyncio.TimeoutError, asyncio.CancelledError, Exception):
run_task.cancel()
asyncio.run(_scenario())
park_warnings = [
r for r in caplog.records
if r.levelno == logging.WARNING and "permanent error" in r.getMessage()
]
assert len(park_warnings) == 1
assert "FileNotFoundError" in park_warnings[0].getMessage()