cli_auto_maintenance.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """Startup auto-maintenance for the classic CLI: state-db pack/vacuum and checkpoint pruning run off the prompt thread.
  2. Split out of ``cli.py``; ``cli`` re-exports every public name and moved bodies late-bind
  3. cli-level names through ``from cli import ...`` at call time so facade monkeypatch seams hold.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import sqlite3
  8. import threading
  9. # Log-record parity with the origin module.
  10. logger = logging.getLogger("cli")
  11. def _run_state_db_auto_maintenance(session_db) -> None:
  12. """One-time repairs + auto-archive/prune/vacuum per the ``sessions:`` config. Never raises."""
  13. if session_db is None:
  14. return
  15. try:
  16. from hermes_cli.config import load_config as _load_full_config
  17. from hermes_constants import get_hermes_home as _get_hermes_home # lazy: tests patch it
  18. _hermes_home_maint = _get_hermes_home()
  19. # One-time repairs, each latched in state_meta once it has run.
  20. for meta_key, repair, done_msg, skip_msg in (
  21. (
  22. "ghost_session_prune_v1",
  23. lambda: session_db.prune_empty_ghost_sessions(sessions_dir=_hermes_home_maint / "sessions"),
  24. "Pruned %d empty TUI ghost sessions", "Ghost session prune skipped: %s",
  25. ),
  26. (
  27. "orphaned_compression_finalize_v1",
  28. session_db.finalize_orphaned_compression_sessions,
  29. "Finalized %d orphaned compression sessions", "Orphan compression finalize skipped: %s",
  30. ),
  31. ):
  32. if session_db.get_meta(meta_key):
  33. continue
  34. try:
  35. count = repair()
  36. # Every SessionDB refusal: sqlite/IO, RuntimeStoreError (ValueError), and the
  37. # hermes_state_errors busy/replaced family (RuntimeError).
  38. except (sqlite3.Error, OSError, ValueError, RuntimeError) as _exc:
  39. # Latched below regardless: a repair this store refuses (live ledger work,
  40. # locked file) must surface once, not retry silently on every start.
  41. logger.warning(skip_msg, _exc)
  42. count = 0
  43. session_db.set_meta(meta_key, "1")
  44. if count:
  45. logger.info(done_msg, count)
  46. cfg = (_load_full_config().get("sessions") or {})
  47. # Auto-archive is independent of auto_prune: run it before prune's early return.
  48. if cfg.get("auto_archive", False):
  49. session_db.maybe_auto_archive(
  50. idle_days=float(cfg.get("auto_archive_days", 3)),
  51. min_interval_hours=int(cfg.get("min_interval_hours", 24)),
  52. )
  53. if not cfg.get("auto_prune", False):
  54. return
  55. session_db.maybe_auto_prune_and_vacuum(
  56. retention_days=int(cfg.get("retention_days", 90)),
  57. min_interval_hours=int(cfg.get("min_interval_hours", 24)),
  58. min_vacuum_interval_days=int(cfg.get("min_vacuum_interval_days", 30)),
  59. vacuum=bool(cfg.get("vacuum_after_prune", True)),
  60. sessions_dir=_hermes_home_maint / "sessions",
  61. )
  62. except Exception as exc:
  63. logger.debug("state.db auto-maintenance skipped: %s", exc)
  64. def _run_checkpoint_auto_maintenance() -> None:
  65. """Checkpoint store retention on a daemon thread: its ``git gc`` can block for tens of seconds
  66. on a large store, which used to stall the prompt once a day. ``auto_prune_from_config`` owns the
  67. config gate and the 24h marker and never raises."""
  68. from tools.checkpoint_maintenance import auto_prune_from_config
  69. threading.Thread(target=auto_prune_from_config, name="checkpoint-auto-prune", daemon=True).start()