The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): report an identically failing hook callback once, not on every call
teknium18beeb661c945
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex be0d1c3a28b..b3b0df18f7f 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -1181,6 +1181,8 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):self._hook_timeout_suppressed_until: Dict[tuple, float] = {}self._hook_timeout_lock = threading.Lock()self._hook_timeout_suppression_seconds = _HOOK_TIMEOUT_SUPPRESSION_SECONDS+ # (hook_name, id(cb), repr(exc)) already reported at WARNING; identical repeats go to DEBUG.+ self._hook_failures_reported: set = set()# Ledger per plugin (ownership) plus global order (reverse teardown across plugins). Process-# global registries are shared across profiles while several managers coexist, so the ledger# is keyed per (hermes_home, plugin_id) and every inverse is identity-conditional — onediff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.pyindex d10b449893f..bb456f2a815 100644--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@ -216,10 +216,27 @@ class PluginDispatchMixin:if ret is not None:results.append(ret)except Exception as exc:- logger.warning(- "Hook '%s' callback %s raised: %s", hook_name, getattr(cb, "__name__", repr(cb)), exc)+ self._report_hook_failure(hook_name, cb, kwargs, exc)return results+ def _report_hook_failure(self, hook_name: str, cb: Callable, kwargs: Dict[str, Any], exc: Exception) -> None:+ """One WARNING per distinct (hook, callback, error); identical repeats at DEBUG.++ A callback whose signature names a parameter the hook never sends (``tool_data`` instead+ of ``tool_name``/``args``) fails identically on every tool call — ~1700 WARNING lines an+ hour that bury real signals (#111922). The first report names the fields the hook does+ provide so the plugin author can fix the signature.+ """+ callback_name = getattr(cb, "__name__", repr(cb))+ key = (hook_name, id(cb), repr(exc))+ if key in self._hook_failures_reported:+ logger.debug("Hook '%s' callback %s raised again: %s", hook_name, callback_name, exc)+ return+ self._hook_failures_reported.add(key)+ logger.warning(+ "Hook '%s' callback %s raised: %s (hook provides: %s; identical failures are logged at DEBUG from now on)",+ hook_name, callback_name, exc, ", ".join(sorted(kwargs)) or "no fields")+def _run_hook_callback_bounded(self, hook_name: str, cb: Callable, kwargs: Dict[str, Any], timeout: float) -> Any:diff --git a/tests/hermes_cli/test_plugin_hook_failure_reporting.py b/tests/hermes_cli/test_plugin_hook_failure_reporting.pynew file mode 100644index 00000000000..768611eead7--- /dev/null+++ b/tests/hermes_cli/test_plugin_hook_failure_reporting.py@@ -0,0 +1,53 @@+"""A plugin hook that fails identically on every call is reported once, not once per call.++A callback whose signature names a parameter the hook never sends (``tool_data`` instead of+``tool_name``/``args``) raises the same ``TypeError`` on every tool call; before the fix core+logged a WARNING each time — ~1700 lines an hour in the report that motivated this (#111922).+"""++import logging++import pytest++from hermes_cli.plugins import PluginManager+++def manager(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes_home"))+ return PluginManager()+++def test_identical_hook_failure_warns_once_then_debug(manager, caplog):+ def on_pre_tool(tool_data): # core sends tool_name/args, never tool_data+ return None++ manager._hooks.setdefault("pre_tool_call", []).append(on_pre_tool)+ with caplog.at_level(logging.DEBUG, logger="hermes_cli.plugins"):+ for i in range(5):+ manager.invoke_hook("pre_tool_call", tool_name="read_file", args={"path": f"/p{i}"})++ warnings = [r for r in caplog.records if r.levelno == logging.WARNING and "on_pre_tool" in r.getMessage()]+ debugs = [r for r in caplog.records if r.levelno == logging.DEBUG and "on_pre_tool" in r.getMessage()]+ assert len(warnings) == 1+ assert len(debugs) == 4+ # The one warning tells the author what the hook actually provides.+ assert "tool_data" in warnings[0].getMessage()+ assert "tool_name" in warnings[0].getMessage()+++def test_distinct_hook_failures_each_warn(manager, caplog):+ """Deduplication is per distinct error: a callback failing in a new way still warns."""+ calls = []++ def flaky(**kwargs):+ calls.append(1)+ raise RuntimeError(f"failure #{len(calls)}")++ manager._hooks.setdefault("post_tool_call", []).append(flaky)+ with caplog.at_level(logging.DEBUG, logger="hermes_cli.plugins"):+ for _ in range(3):+ manager.invoke_hook("post_tool_call", tool_name="x", args={}, result="ok")++ warnings = [r for r in caplog.records if r.levelno == logging.WARNING and "flaky" in r.getMessage()]+ assert len(warnings) == 3diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 6d9ac48a474..a93f9947055 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -382,7 +382,7 @@ def register(ctx):**General rules for all hooks:**- Callbacks receive **keyword arguments**. Always accept `**kwargs` for forward compatibility.-- Callback exceptions are logged and skipped; later callbacks continue.+- Callback exceptions are logged and skipped; later callbacks continue. A callback that fails the same way on every call (typically a signature naming a field the hook does not send, e.g. `tool_data` instead of `tool_name`/`args`) is reported **once** at WARNING — the message lists the fields the hook provides — and identical repeats go to DEBUG, so a mis-declared plugin cannot flood the log.- If a Python plugin callback on a **timeout-bounded** hook (hot-path observers such as `post_tool_call` / `pre_llm_call`, plus the policy hook `pre_tool_call`) **blocks** longer than `plugins.hook_callback_timeout` (default 30s, set `0` to disable, max 600), it is abandoned without joining the worker so the agent loop continues. Timed-out or still-running `pre_tool_call` callbacks **fail closed** (block the tool); other bounded hooks fail open (skip). Hooks with a documented caller-thread contract (`subagent_stop`) are never moved onto a timeout worker. Shell hooks keep their own per-entry `timeout`.- The catalog below is descriptive: **observers** ignore returns, **transforms** accept the first valid string replacement, and **directive/control** hooks consume documented return shapes. Plugin middleware is a separate registry and surface, not another hook category.- Correlation fields such as `turn_id`, `api_request_id`, `task_id`, `session_id`, and `api_call_count` are hook-specific and may be absent. Treat IDs as opaque.