fix(update): gateway auto-restart no longer dies on stale cached modules after the pull
`hermes update` runs in the pre-pull interpreter. The auto-restart phase imports freshly-pulled gateway source, which resolves sibling imports against the OLD sys.modules cache — so any update where an already-cached module gained a new export ImportErrored the whole phase and left the gateway serving pre-update code (2026-08-20 field failure: new gateway.py needs cli_output.line_input, cached cli_output predates it). Class fix replacing the per-symptom _UPDATE_RUNTIME_RELOAD_MODULES approach: _purge_stale_hermes_modules() evicts every cached module under the Hermes package prefixes (hermes_cli/gateway/tools/tui_gateway/agent) right before the restart phase, so later lazy imports rebuild a self-consistent module graph from the updated checkout. The updater's own executing modules are exempt (purging them buys nothing; reload-in-place is the unsafe op, and we never reload). Root-segment check spares prefix-lookalike packages. Best-effort, never raises. 5 new tests incl. an end-to-end repro of the field failure shape (stale module missing symbol -> ImportError -> purge -> import resolves).
This commit is contained in:
@@ -4880,6 +4880,7 @@ _LAZY_COMMAND_EXPORTS = {
|
||||
"_format_time_ago",
|
||||
"_handoff_reapable_backend_pids",
|
||||
"_ledger_reapable_backend_pids",
|
||||
"_purge_stale_hermes_modules",
|
||||
"_format_venv_python_holders_message",
|
||||
"_gateway_prompt",
|
||||
"_get_origin_url",
|
||||
|
||||
@@ -61,6 +61,82 @@ _UPDATE_RUNTIME_RELOAD_MODULES = (
|
||||
"tools.lazy_deps",
|
||||
)
|
||||
|
||||
#: Package prefixes whose cached modules become stale the moment the checkout
|
||||
#: changes under this process. Purged (not reloaded) by
|
||||
#: ``_purge_stale_hermes_modules`` so any LATER import chain resolves against
|
||||
#: fresh on-disk source only.
|
||||
_STALE_PURGE_PREFIXES = (
|
||||
"hermes_cli",
|
||||
"gateway",
|
||||
"tools",
|
||||
"tui_gateway",
|
||||
"agent",
|
||||
)
|
||||
|
||||
#: Modules that must survive the purge: they are (or are referenced by) the
|
||||
#: code currently EXECUTING the update, so evicting them buys nothing — the
|
||||
#: running frames keep their module objects alive regardless — and reloading
|
||||
#: them mid-flight is the one genuinely unsafe move.
|
||||
_STALE_PURGE_PROTECTED = frozenset(
|
||||
{
|
||||
"hermes_cli",
|
||||
"hermes_cli.main",
|
||||
"hermes_cli.update_cmd",
|
||||
"hermes_cli.hermes_logging",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _purge_stale_hermes_modules() -> None:
|
||||
"""Evict every cached Hermes module after the checkout changed in-place.
|
||||
|
||||
``hermes update`` keeps running in the pre-pull Python process. The
|
||||
gateway auto-restart phase that follows does function-level
|
||||
``from hermes_cli.gateway import ...`` — executing NEW source inside an
|
||||
OLD ``sys.modules`` world. The moment new source references a symbol
|
||||
that was added to an already-cached module, the import dies (2026-08-20
|
||||
field failure: freshly-pulled ``hermes_cli.gateway`` does
|
||||
``from hermes_cli.cli_output import line_input``, but ``cli_output`` was
|
||||
cached from before d0132b582 which introduced ``line_input`` → the whole
|
||||
restart phase aborted and the gateway kept serving pre-update code).
|
||||
|
||||
``_UPDATE_RUNTIME_RELOAD_MODULES`` handled this per-symptom — three
|
||||
hardcoded module names, re-fixed every time a new module grew a new
|
||||
export. This is the class fix: drop EVERY cached module under the Hermes
|
||||
package prefixes so subsequent lazy imports rebuild a self-consistent,
|
||||
all-new module graph from the updated checkout. Old module objects
|
||||
referenced by the running updater frames stay alive and functional (a
|
||||
purge only removes the ``sys.modules`` cache entry); only genuinely
|
||||
executing modules are exempted, because reloading-in-place — not purging
|
||||
— is the operation that can pull code out from under a running frame.
|
||||
|
||||
Best-effort: never raises.
|
||||
"""
|
||||
try:
|
||||
import importlib
|
||||
|
||||
importlib.invalidate_caches()
|
||||
purged = []
|
||||
for name in list(_m().sys.modules):
|
||||
if name in _STALE_PURGE_PROTECTED:
|
||||
continue
|
||||
if not name.startswith(_STALE_PURGE_PREFIXES):
|
||||
continue
|
||||
root = name.split(".", 1)[0]
|
||||
if root not in _STALE_PURGE_PREFIXES:
|
||||
# Prefix-string match caught an unrelated package
|
||||
# (e.g. ``gateway_foo``) — leave it alone.
|
||||
continue
|
||||
if _m().sys.modules.pop(name, None) is not None:
|
||||
purged.append(name)
|
||||
if purged:
|
||||
logger.debug(
|
||||
"Purged %d stale Hermes module(s) after checkout update", len(purged)
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug("Could not purge stale Hermes modules: %s", exc)
|
||||
|
||||
|
||||
def _reload_updated_runtime_modules() -> None:
|
||||
"""Reload update-sensitive modules after the checkout changes in-place.
|
||||
|
||||
@@ -6261,6 +6337,14 @@ def _cmd_update_impl(args, gateway_mode: bool):
|
||||
# Auto-restart ALL gateways after update.
|
||||
# The code update (git pull) is shared across all profiles, so every
|
||||
# running gateway needs restarting to pick up the new code.
|
||||
#
|
||||
# Purge stale cached Hermes modules FIRST: the import below pulls
|
||||
# freshly-updated gateway source into this pre-update interpreter,
|
||||
# and any already-cached sibling module (cli_output, status, ...)
|
||||
# that the new source expects a new symbol from would otherwise
|
||||
# ImportError and abort this whole phase (2026-08-20 field failure:
|
||||
# new gateway.py ← stale cli_output missing line_input).
|
||||
_m()._purge_stale_hermes_modules()
|
||||
try:
|
||||
from hermes_cli.gateway import (
|
||||
is_macos,
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Tests for _purge_stale_hermes_modules — the class fix for stale
|
||||
sys.modules breaking the gateway auto-restart after `hermes update`.
|
||||
|
||||
Field failure (2026-08-20, Teknium's Linux box): `hermes update` pulled a
|
||||
checkout where hermes_cli/gateway.py newly imports `line_input` from
|
||||
hermes_cli.cli_output, but the updater process had cli_output cached from
|
||||
before that symbol existed. The function-level `from hermes_cli.gateway
|
||||
import ...` in the restart phase raised ImportError, the whole phase
|
||||
aborted, and the running gateway kept serving pre-update code.
|
||||
|
||||
The old mitigation (_UPDATE_RUNTIME_RELOAD_MODULES) reloaded 3 hardcoded
|
||||
modules — re-fixed per symptom. The purge evicts EVERY cached module under
|
||||
the Hermes package prefixes so later imports rebuild a self-consistent
|
||||
module graph from the updated checkout.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli import main as cli_main
|
||||
from hermes_cli import update_cmd
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _restore_sys_modules():
|
||||
"""Snapshot & restore sys.modules around each test.
|
||||
|
||||
The purge under test evicts real Hermes modules from the cache; later
|
||||
tests in the same process may hold references to the evicted module
|
||||
objects (e.g. `patch.object` targets), so put the originals back.
|
||||
"""
|
||||
snapshot = dict(sys.modules)
|
||||
yield
|
||||
for name, mod in snapshot.items():
|
||||
sys.modules[name] = mod
|
||||
for name in list(sys.modules):
|
||||
if name not in snapshot:
|
||||
del sys.modules[name]
|
||||
|
||||
|
||||
def _fake_module(name: str) -> types.ModuleType:
|
||||
mod = types.ModuleType(name)
|
||||
mod.__stale_sentinel__ = True
|
||||
return mod
|
||||
|
||||
|
||||
def test_purge_evicts_hermes_prefixed_modules():
|
||||
victims = [
|
||||
"hermes_cli.cli_output",
|
||||
"hermes_cli.gateway",
|
||||
"gateway.status",
|
||||
"tools.ansi_strip",
|
||||
"tui_gateway.server",
|
||||
"agent.memory_store",
|
||||
]
|
||||
added = []
|
||||
for name in victims:
|
||||
if name not in sys.modules:
|
||||
sys.modules[name] = _fake_module(name)
|
||||
added.append(name)
|
||||
try:
|
||||
cli_main._purge_stale_hermes_modules()
|
||||
for name in victims:
|
||||
mod = sys.modules.get(name)
|
||||
assert mod is None or not getattr(mod, "__stale_sentinel__", False), (
|
||||
f"{name} survived the purge"
|
||||
)
|
||||
finally:
|
||||
for name in added:
|
||||
sys.modules.pop(name, None)
|
||||
|
||||
|
||||
def test_purge_protects_executing_modules():
|
||||
# The updater's own modules must survive — they're running this code.
|
||||
cli_main._purge_stale_hermes_modules()
|
||||
assert sys.modules.get("hermes_cli.update_cmd") is update_cmd
|
||||
assert sys.modules.get("hermes_cli.main") is cli_main
|
||||
assert "hermes_cli" in sys.modules
|
||||
|
||||
|
||||
def test_purge_leaves_prefix_lookalikes_alone():
|
||||
# `gateway_foo` starts with the string prefix "gateway" but is NOT the
|
||||
# gateway package — the root-segment check must spare it.
|
||||
lookalikes = ["gatewayd", "toolshed", "agents_external"]
|
||||
added = []
|
||||
for name in lookalikes:
|
||||
if name not in sys.modules:
|
||||
sys.modules[name] = _fake_module(name)
|
||||
added.append(name)
|
||||
try:
|
||||
cli_main._purge_stale_hermes_modules()
|
||||
for name in lookalikes:
|
||||
assert name in sys.modules, f"{name} was wrongly purged"
|
||||
finally:
|
||||
for name in added:
|
||||
sys.modules.pop(name, None)
|
||||
|
||||
|
||||
def test_purge_never_raises_on_weird_sys_modules():
|
||||
# Entries with None values (import machinery quirk) must not break it.
|
||||
sys.modules["hermes_cli._purge_test_none"] = None # type: ignore[assignment]
|
||||
try:
|
||||
cli_main._purge_stale_hermes_modules()
|
||||
finally:
|
||||
sys.modules.pop("hermes_cli._purge_test_none", None)
|
||||
|
||||
|
||||
def test_stale_symbol_scenario_end_to_end():
|
||||
"""Reproduce the field failure shape: a cached module missing a symbol
|
||||
that freshly-imported code needs — purge, then re-import resolves it."""
|
||||
name = "hermes_cli.cli_output"
|
||||
real = sys.modules.get(name)
|
||||
# Install a stale stand-in WITHOUT line_input (pre-d0132b582 world).
|
||||
stale = types.ModuleType(name)
|
||||
sys.modules[name] = stale
|
||||
try:
|
||||
# The failure mode: importing the symbol from the stale cache dies.
|
||||
try:
|
||||
from hermes_cli.cli_output import line_input # noqa: F401
|
||||
raised = False
|
||||
except ImportError:
|
||||
raised = True
|
||||
assert raised, "precondition: stale module must lack line_input"
|
||||
|
||||
cli_main._purge_stale_hermes_modules()
|
||||
|
||||
# Post-purge, the import resolves against real on-disk source.
|
||||
from hermes_cli.cli_output import line_input # noqa: F401
|
||||
finally:
|
||||
sys.modules.pop(name, None)
|
||||
if real is not None:
|
||||
sys.modules[name] = real
|
||||
Reference in New Issue
Block a user