code_skew.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Detect when the gateway is running stale code after a hot ``git pull``.
  2. The gateway's ``sys.modules`` is frozen at boot. If the checkout is updated
  3. underneath it, a first-time lazy import can resolve a freshly-pulled module
  4. against a stale cached dependency -> ImportError. We snapshot the revision at
  5. startup so risky callers (e.g. ``/model`` switching) can refuse with a clear
  6. "restart the gateway" message. If the revision can't be read (non-git install,
  7. IO error) the boot snapshot stays ``None`` and detection no-ops — never a false positive.
  8. """
  9. from __future__ import annotations
  10. from pathlib import Path
  11. _PROJECT_ROOT = Path(__file__).resolve().parent.parent
  12. _boot_fingerprint: str | None = None
  13. def _fingerprint() -> str | None:
  14. """Current checkout fingerprint via the CLI's worktree-aware git-rev reader
  15. (``hermes_cli.main`` is always already imported in a gateway process)."""
  16. try:
  17. from hermes_cli.main import _read_git_revision_fingerprint
  18. return _read_git_revision_fingerprint(_PROJECT_ROOT)
  19. except Exception:
  20. return None
  21. def record_boot_fingerprint() -> None:
  22. """Snapshot the checkout revision at gateway startup (idempotent)."""
  23. global _boot_fingerprint
  24. if _boot_fingerprint is None:
  25. _boot_fingerprint = _fingerprint()
  26. def _short(fingerprint: str) -> str:
  27. """Render a ``git:<ref>:<sha>`` fingerprint as a compact label."""
  28. sha = fingerprint.rsplit(":", 1)[-1]
  29. return sha[:10] if sha and sha != "unresolved" and len(sha) > 10 else (sha or fingerprint)
  30. def current_code_sha() -> str | None:
  31. """Full SHA for the checkout currently on disk, or None when unresolved."""
  32. fingerprint = _fingerprint()
  33. if fingerprint is None:
  34. return None
  35. sha = fingerprint.rsplit(":", 1)[-1]
  36. return sha if sha and sha != "unresolved" else None
  37. def detect_code_skew() -> tuple[str, str] | None:
  38. """``(boot_rev, disk_rev)`` short labels if the checkout drifted since boot, else ``None``."""
  39. current = _fingerprint() if _boot_fingerprint is not None else None
  40. if current is None or current == _boot_fingerprint:
  41. return None
  42. return _short(_boot_fingerprint), _short(current)