Files
hermes-agent/tests/tools/test_mcp_transport_group_reconnect.py
T
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

116 lines
4.0 KiB
Python

"""Regression tests for issue #66092.
Streamable-HTTP / SSE MCP transports run their stream pump inside an anyio
TaskGroup. A transient stream drop (idle timeout, brief backend blip) surfaces
as a ``BaseExceptionGroup`` escaping the transport context manager. Before the
fix that group reached ``run()``'s error path, which applied exponential
backoff and eventually parked the server for 300s and deregistered its tools —
a multi-minute tool outage for a sub-second glitch.
``_run_http`` now converts such a transport TaskGroup failure into a clean
``"reconnect"`` (immediate rebuild, no backoff/park), while still propagating
real shutdown/cancellation and genuine connect/handshake failures.
"""
from __future__ import annotations
import asyncio
import pytest
from tools.mcp_tool import MCPServerTask
def _group(*excs) -> BaseExceptionGroup:
return BaseExceptionGroup("transport drop", list(excs))
# ── Unit coverage for the decision helper ────────────────────────────────────
class TestReconnectOrReraiseGroup:
def test_live_session_transient_drop_reconnects(self):
task = MCPServerTask("t")
task._ready.set() # a live session was established this attempt
assert task._reconnect_or_reraise_group(
_group(ConnectionError("sse stream dropped"))
) == "reconnect"
def test_no_live_session_reraises_for_backoff(self):
task = MCPServerTask("t")
# _ready NOT set: a connect/handshake failure, not a transient drop —
# let run()'s backoff handle it instead of hot-looping.
with pytest.raises(BaseExceptionGroup):
task._reconnect_or_reraise_group(_group(ConnectionError("handshake")))
# ── Integration coverage: real _run_http new-HTTP branch ─────────────────────
class _RaisingTransportCM:
"""Fake streamable-HTTP transport whose __aexit__ raises a group, mimicking
the SDK's anyio TaskGroup tearing down on a stream drop."""
def __init__(self, exc):
self._exc = exc
async def __aenter__(self):
return (object(), object(), lambda: "session-id")
async def __aexit__(self, *exc_info):
raise self._exc
class _FakeSession:
async def initialize(self):
return object()
class _FakeSessionCM:
async def __aenter__(self):
return _FakeSession()
async def __aexit__(self, *exc_info):
return False
def _make_http_task(monkeypatch, transport_exc):
task = MCPServerTask("http-drop")
monkeypatch.setattr("tools.mcp_tool._MCP_HTTP_AVAILABLE", True, raising=False)
monkeypatch.setattr("tools.mcp_tool._MCP_NEW_HTTP", True, raising=False)
monkeypatch.setattr(
"tools.mcp_tool.streamable_http_client",
lambda url, http_client=None: _RaisingTransportCM(transport_exc),
raising=False,
)
monkeypatch.setattr(
"tools.mcp_tool.ClientSession",
lambda *a, **k: _FakeSessionCM(),
raising=False,
)
async def _no_discover(self):
return None
async def _reconnect_lifecycle(self):
return "reconnect"
monkeypatch.setattr(MCPServerTask, "_discover_tools", _no_discover)
monkeypatch.setattr(MCPServerTask, "_wait_for_lifecycle_event", _reconnect_lifecycle)
return task
def test_run_http_transport_group_returns_reconnect(monkeypatch):
task = _make_http_task(monkeypatch, _group(ConnectionError("stream dropped")))
reason = asyncio.run(task._run_http({"url": "http://127.0.0.1:9/mcp"}))
assert reason == "reconnect"
# We had a live session; readiness stays set for run() to clear on re-entry.
assert task._ready.is_set()
def test_run_http_transport_group_reraises_on_shutdown(monkeypatch):
task = _make_http_task(monkeypatch, _group(ConnectionError("stream dropped")))
task._shutdown_event.set()
with pytest.raises(BaseExceptionGroup):
asyncio.run(task._run_http({"url": "http://127.0.0.1:9/mcp"}))