The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(plugins): make the sys.modules snapshot self-evident, harden its regression test
NaMinhyeok952d55d2e702
diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.pyindex 39da77c5635..849abc1ae8f 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -155,13 +155,17 @@ def _evict_modules(module_name: str) -> None:"""Drop ``module_name`` and every ``module_name.*`` submodule from ``sys.modules``.``sys.modules`` is process-global, so any concurrent import — another profile's plugin- load, a lazy import on a worker thread — mutates it while this runs. Snapshot the keys- with ``list()`` (one atomic C-level copy) instead of iterating the live mapping, and drop- with ``pop`` so a key another evictor already removed is not a ``KeyError``.+ load, a lazy import on a worker thread — mutates it while this runs. The ``list()`` is+ load-bearing, not a style choice: it is one atomic C-level copy, where iterating the live+ mapping raises ``RuntimeError: dictionary changed size during iteration`` and+ ``PluginLoaderMixin._load_plugin_scoped`` degrades that to a warning that loses the whole+ plugin. ``pop`` (not ``del``) keeps the snapshot-to-delete window tolerant of a key another+ evictor already removed."""prefix = f"{module_name}."- for name in [n for n in list(sys.modules) if n == module_name or n.startswith(prefix)]:- sys.modules.pop(name, None)+ for name in list(sys.modules): # snapshot first — never iterate the live mapping+ if name == module_name or name.startswith(prefix):+ sys.modules.pop(name, None)def _serialized_replacement(method):diff --git a/tests/hermes_cli/test_plugin_loader_module_eviction.py b/tests/hermes_cli/test_plugin_loader_module_eviction.pyindex d97868995ed..5fa3963bf54 100644--- a/tests/hermes_cli/test_plugin_loader_module_eviction.py+++ b/tests/hermes_cli/test_plugin_loader_module_eviction.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport sysimport threadingimport types+from collections.abc import Iteratorimport pytest@@ -23,6 +24,11 @@ def isolated_modules(monkeypatch: pytest.MonkeyPatch) -> dict:A real dict, because the fix rests on ``list(dict)`` being one atomic C-level copy —a Python-level mapping stub would not exercise that property.++ The whole ``sys`` reference is swapped (the real ``sys.modules`` cannot be replaced+ without breaking the process), so only ``_evict_modules`` may be called under this+ fixture: any loader path that reaches ``sys.path``/``sys.executable`` would fail with+ ``AttributeError`` on the stand-in."""modules: dict[str, object] = {f"unrelated_{i}": types.ModuleType(f"unrelated_{i}") for i in range(_MODULE_COUNT)@@ -31,6 +37,22 @@ def isolated_modules(monkeypatch: pytest.MonkeyPatch) -> dict:return modules+def fast_thread_switching() -> Iterator[None]:+ """Force frequent GIL handoffs so the eviction/import interleaving actually happens.++ The switch interval is process-global, but CI runs one pytest subprocess per test file+ (``run_tests_parallel.py``), so the blast radius is this file. Restored via the fixture+ rather than an inline ``finally`` so a failure mid-setup cannot leak it.+ """+ previous = sys.getswitchinterval()+ sys.setswitchinterval(1e-6)+ try:+ yield+ finally:+ sys.setswitchinterval(previous)++def test_evict_modules_drops_module_and_submodules(isolated_modules: dict) -> None:for name in ("hermes_plugins.aop", "hermes_plugins.aop.client", "hermes_plugins.aop_other"):isolated_modules[name] = types.ModuleType(name)@@ -43,7 +65,9 @@ def test_evict_modules_drops_module_and_submodules(isolated_modules: dict) -> Noassert "hermes_plugins.aop_other" in isolated_modules-def test_evict_modules_tolerates_concurrent_imports(isolated_modules: dict) -> None:+def test_evict_modules_tolerates_concurrent_imports(+ isolated_modules: dict, fast_thread_switching: None,+) -> None:"""A concurrent import must not abort the plugin load.Iterating the live mapping raised ``RuntimeError: dictionary changed size during@@ -53,16 +77,17 @@ def test_evict_modules_tolerates_concurrent_imports(isolated_modules: dict) -> N"""stop = threading.Event()failures: list[BaseException] = []+ churn_rounds = 0def churn() -> None:- i = 0+ nonlocal churn_roundswhile not stop.is_set():- batch = [f"late_import_{i}_{j}" for j in range(_CHURN_BATCH)]+ batch = [f"late_import_{churn_rounds}_{j}" for j in range(_CHURN_BATCH)]for key in batch:isolated_modules[key] = Nonefor key in batch:isolated_modules.pop(key, None)- i += 1+ churn_rounds += 1def evict() -> None:try:@@ -74,8 +99,6 @@ def test_evict_modules_tolerates_concurrent_imports(isolated_modules: dict) -> Nexcept BaseException as exc: # noqa: BLE001 - recorded for the assertion belowfailures.append(exc)- previous_interval = sys.getswitchinterval()- sys.setswitchinterval(1e-6) # force frequent handoffs so the race is deterministicchurner = threading.Thread(target=churn, daemon=True)churner.start()try:@@ -86,6 +109,11 @@ def test_evict_modules_tolerates_concurrent_imports(isolated_modules: dict) -> Nfinally:stop.set()churner.join(timeout=10)- sys.setswitchinterval(previous_interval)assert not failures, f"eviction raised under concurrent import: {failures[0]!r}"+ # Without these two, the test passes vacuously: a churner that never got scheduled leaves+ # the eviction running against a mapping it has to itself, which is the case the fix is+ # not about. A silent pass here would mean the regression stopped being covered at all.+ assert churn_rounds > 0, "churn thread never ran — the race window was never opened"+ leftover = [name for name in isolated_modules if name.startswith("hermes_plugins.victim_")]+ assert not leftover, f"eviction left entries behind: {leftover[:5]}"