stale_modules.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Heal mixed ``sys.modules`` after an in-place checkout update.
  2. Pre-reexec updaters (Hermes ≤ v2026.9.14) purged only package prefixes
  3. (``hermes_cli``, ``gateway``, ``tools``, ``tui_gateway``, ``agent``) and left
  4. root modules like ``utils`` cached in the updater process. The post-pull
  5. gateway-restart phase then imports new ``hermes_cli.gateway`` /
  6. ``hermes_cli.config`` into that process; those need symbols the stale
  7. ``utils`` lacks (``file_signature``), and ``hermes update`` exits 1 with
  8. ``gateway auto-restart failed: cannot import name 'file_signature' from
  9. 'utils'``.
  10. Post-swap hand-off (``hermes_cli.update_handoff``) makes this class dead for
  11. updaters that already include it. This module is the bridge for the one
  12. upgrade from a pre-handoff release onto a tree that needs new root symbols:
  13. freshly imported ``hermes_cli`` code drops the incomplete cache before
  14. importing ``utils``.
  15. """
  16. from __future__ import annotations
  17. import sys
  18. from typing import Mapping, Sequence
  19. # Root modules the narrow purge left behind, keyed by attributes that must
  20. # exist on the on-disk copy after this release. Extend when a new root-level
  21. # symbol would otherwise break the pre-handoff upgrade path.
  22. _ROOT_MODULE_REQUIRED_ATTRS: dict[str, tuple[str, ...]] = {
  23. "utils": ("file_signature", "file_cache_version"),
  24. }
  25. def drop_stale_root_modules(
  26. required: Mapping[str, Sequence[str]] | None = None,
  27. ) -> list[str]:
  28. """Drop cached root modules missing required attrs. Returns dropped names."""
  29. checks = _ROOT_MODULE_REQUIRED_ATTRS if required is None else required
  30. dropped: list[str] = []
  31. for name, attrs in checks.items():
  32. mod = sys.modules.get(name)
  33. if mod is None:
  34. continue
  35. if any(not hasattr(mod, attr) for attr in attrs):
  36. sys.modules.pop(name, None)
  37. dropped.append(name)
  38. return dropped