cpu_profile.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """``hermes --cpu-profile PATH``: process-wide cProfile, written when the process exits.
  2. Enabled once after argument parsing and written from ``atexit``, so short commands and
  3. long-running ones (``gateway run``) are covered without wrapping every handler. The one-shot
  4. (``-z``) exit skips ``atexit`` on purpose (``main._exit_after_oneshot``) and calls
  5. :func:`write_cpu_profile` itself. A relative PATH lands in the active profile's
  6. ``logs/profiles/``. Profiles cover THIS process only: under ``--tui`` that is the launcher,
  7. while the agent runs in the TUI's own backend process.
  8. """
  9. from __future__ import annotations
  10. import atexit
  11. import logging
  12. import os
  13. import sys
  14. from pathlib import Path
  15. logger = logging.getLogger(__name__)
  16. _profiler = None
  17. _profile_path: Path | None = None
  18. def resolve_profile_path(path: str | os.PathLike[str]) -> Path:
  19. """Absolute (or ``~``) paths as given; relative ones under ``<hermes home>/logs/profiles``."""
  20. target = Path(path).expanduser()
  21. if not target.is_absolute():
  22. from hermes_constants import get_hermes_home
  23. target = get_hermes_home() / "logs" / "profiles" / target
  24. return target.resolve()
  25. def enable_cpu_profile(path: str | os.PathLike[str] | None) -> Path | None:
  26. """Start profiling to ``path``; idempotent so the fast-path → full-parser handoff can't
  27. register a second writer. Returns the resolved path, or None when ``path`` is empty."""
  28. global _profiler, _profile_path
  29. if not path:
  30. return None
  31. if _profiler is not None:
  32. return _profile_path
  33. import cProfile
  34. target = resolve_profile_path(path)
  35. target.parent.mkdir(parents=True, exist_ok=True)
  36. _profiler, _profile_path = cProfile.Profile(), target
  37. _profiler.enable()
  38. atexit.register(write_cpu_profile)
  39. return target
  40. def enable_cpu_profile_from_args(args) -> None:
  41. """Honour ``--cpu-profile`` on a parsed CLI namespace and say where the profile goes."""
  42. enabled = enable_cpu_profile(getattr(args, "cpu_profile", None))
  43. if enabled is not None:
  44. print(f"CPU profiling enabled: {enabled}", file=sys.stderr)
  45. def write_cpu_profile() -> None:
  46. """Stop profiling and write ``PATH`` (pstats) plus ``PATH.txt`` (top 80 by cumulative time)."""
  47. global _profiler
  48. profiler, target = _profiler, _profile_path
  49. if profiler is None or target is None:
  50. return
  51. _profiler = None
  52. profiler.disable()
  53. import pstats
  54. try:
  55. target.parent.mkdir(parents=True, exist_ok=True)
  56. profiler.dump_stats(str(target))
  57. with target.with_suffix(target.suffix + ".txt").open("w", encoding="utf-8") as fh:
  58. pstats.Stats(profiler, stream=fh).sort_stats("cumulative").print_stats(80)
  59. except OSError:
  60. logger.exception("Failed to write CPU profile: %s", target)