The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): drop the stale submodule attribute in the post-pull purge
djsanchezsuarez5a942f95fcf2
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex 9401a8b5904..ad2f4ec7e84 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -108,6 +108,24 @@ def _stale_purge_prefixes() -> frozenset:return frozenset(names) - {"tests"}+def _evict_module(name: str) -> bool:+ """Drop *name* from ``sys.modules`` AND the stale attribute its parent package still holds.++ Returns True when a ``sys.modules`` entry was removed. The attribute matters: ``from hermes_cli+ import main_dashboard`` is resolved by ``_handle_fromlist``, which is satisfied by the ATTRIBUTE+ the import system left on the parent package — so a purged submodule keeps being handed to+ call-time imports unless the attribute goes too. The parent (``hermes_cli``) is protected and+ survives the purge, which is how a pre-pull ``main_dashboard`` outlived it and crashed the+ dashboard cleanup (#111689).+ """+ dropped = sys.modules.pop(name, None) is not None+ parent_name, _, child = name.rpartition(".")+ parent = sys.modules.get(parent_name)+ if parent is not None and getattr(vars(parent).get(child), "__name__", None) == name:+ del vars(parent)[child]+ return dropped++def _purge_stale_hermes_modules() -> None:"""Evict every cached Hermes module after the checkout changed in-place. Never raises.@@ -127,7 +145,7 @@ def _purge_stale_hermes_modules() -> None:and not name.startswith(_STALE_PURGE_PROTECTED_PREFIX)# Root-package check: startswith() alone also matches unrelated ``gateway_foo``.and name.split(".", 1)[0] in prefixes- and modules.pop(name, None) is not None+ and _evict_module(name)]if purged:logger.debug("Purged %d stale Hermes module(s) after checkout update", len(purged))@@ -334,6 +352,12 @@ def _reload_process_scan_modules() -> None:bounded_probe_run``. If the update added a new symbol to ``_subprocess_compat`` (as #87134 did with``bounded_probe_run``), the cached OLD module object doesn't have it and the cleanup step crashes withImportError — after the code update itself already succeeded.++ The helpers it imports from ``hermes_cli.main_dashboard`` / ``main_install_repair`` are NOT+ refreshed here: ``hermes_cli.main`` imports those eagerly at CLI start, so reloading would+ rewrite the module dict the running update still holds bindings into. The+ ``_purge_stale_hermes_modules`` eviction, which runs earlier in the update, is what makes the+ call-time ``from hermes_cli import main_dashboard`` re-read the pulled source (#111689)."""_reload_modules(("hermes_cli._subprocess_compat", "hermes_cli.dashboard_procs"),diff --git a/tests/hermes_cli/test_update_stale_module_purge.py b/tests/hermes_cli/test_update_stale_module_purge.pyindex 876ed880768..9051dba147e 100644--- a/tests/hermes_cli/test_update_stale_module_purge.py+++ b/tests/hermes_cli/test_update_stale_module_purge.py@@ -21,6 +21,7 @@ import importlibimport jsonimport sysimport types+from unittest.mock import patchimport pytest@@ -35,14 +36,37 @@ def _restore_sys_modules():The purge under test evicts real Hermes modules from the cache; latertests in the same process may hold references to the evicted moduleobjects (e.g. `patch.object` targets), so put the originals back.++ The eviction also drops the stale submodule attribute a purged module left on its PARENT+ package (see `_evict_module`), which `sys.modules` alone does not cover: after the test,+ `hermes_cli.X` could hold a freshly imported copy while the cache holds the original, and a+ later `patch("hermes_cli.X.fn")` would miss the module the code under test resolves. Restore+ the checkout-owned package namespaces too."""+ from hermes_cli.update_cmd_maint import _stale_purge_prefixes+snapshot = dict(sys.modules)+ owned = _stale_purge_prefixes()+ namespaces = {+ name: (mod, dict(vars(mod)))+ for name, mod in snapshot.items()+ if mod is not None+ and name.split(".", 1)[0] in owned+ and getattr(mod, "__path__", None) is not None # packages only: they carry submodules+ }yieldfor name, mod in snapshot.items():sys.modules[name] = modfor name in list(sys.modules):if name not in snapshot:del sys.modules[name]+ for name, (mod, attrs) in namespaces.items():+ if sys.modules.get(name) is not mod:+ continue+ current = vars(mod)+ for key in [key for key in current if key not in attrs]:+ del current[key]+ current.update(attrs)def _fake_module(name: str) -> types.ModuleType:@@ -212,3 +236,73 @@ def test_purge_protects_hermes_logging():sys.modules.pop("hermes_logging", None)if real is not None:sys.modules["hermes_logging"] = real+++def test_purge_drops_stale_package_attribute_so_from_import_rereads_source():+ """2026-09-16 field failure (#111689): `hermes_cli.main` imports `main_dashboard` at CLI+ start, so the updater process holds it as an ATTRIBUTE of the (protected) `hermes_cli`+ package. Evicting only the sys.modules entry left `from hermes_cli import main_dashboard`+ handing the PRE-pull module to the dashboard cleanup, which then died on a symbol the pull+ had added (`AttributeError ... has no attribute '_loaded_launchd_backend_jobs'`).+ """+ import hermes_cli++ name = "hermes_cli.main_dashboard"+ real = sys.modules.get(name)+ stale = types.ModuleType(name) # pre-pull stand-in: lacks the symbol the cleanup needs+ stale.__file__ = getattr(real, "__file__", "<stale>")+ stale.__stale_sentinel__ = True+ sys.modules[name] = stale+ setattr(hermes_cli, "main_dashboard", stale)+ try:+ cli_main._purge_stale_hermes_modules()++ assert not hasattr(stale, "_loaded_launchd_backend_jobs")+ from hermes_cli import main_dashboard as pulled++ assert pulled is not stale, "call-time import was handed the pre-pull module"+ assert getattr(pulled, "__stale_sentinel__", False) is False+ assert hasattr(pulled, "_loaded_launchd_backend_jobs")+ finally:+ sys.modules.pop(name, None)+ if real is not None:+ sys.modules[name] = real+ setattr(hermes_cli, "main_dashboard", real)+++def test_dashboard_cleanup_survives_a_pre_pull_main_dashboard():+ """End-to-end shape of the 2026-09-16 field failure: the post-update dashboard cleanup runs+ after the purge, and `_kill_stale_dashboard_processes` resolves its helpers then. With the+ pre-pull `main_dashboard` still reachable, the cleanup aborted on+ `AttributeError: module 'hermes_cli.main_dashboard' has no attribute+ '_loaded_launchd_backend_jobs'` — after the code update had already succeeded.+ """+ import hermes_cli+ from hermes_cli import dashboard_procs++ name = "hermes_cli.main_dashboard"+ real = sys.modules.get(name)+ stale = types.ModuleType(name)+ stale.__file__ = getattr(real, "__file__", "<stale>")+ stale.__stale_sentinel__ = True+ # The pre-pull module DOES scan processes; it only lacks the launchd symbol the pull added,+ # so the cleanup reaches the launchd snapshot line and dies there (the reported traceback).+ stale._find_stale_dashboard_pids = lambda **_kw: [999999]+ sys.modules[name] = stale+ setattr(hermes_cli, "main_dashboard", stale)+ try:+ cli_main._purge_stale_hermes_modules()++ # The scan/kill pass must not touch real processes: the fresh module's pid scan is host+ # dependent (a dashboard may or may not be running), so only the kill step is stubbed.+ with patch.object(dashboard_procs, "_kill_pids_posix", side_effect=lambda pids, k, f: None):+ result = dashboard_procs._kill_stale_dashboard_processes("regression")++ assert isinstance(result, dict), "cleanup aborted instead of returning its result"+ assert hasattr(sys.modules["hermes_cli.main_dashboard"], "_loaded_launchd_backend_jobs"), \+ "cleanup resolved the pre-pull module"+ finally:+ sys.modules.pop(name, None)+ if real is not None:+ sys.modules[name] = real+ setattr(hermes_cli, "main_dashboard", real)