Skip to content

The agent that grows with you

fix(sessions): the low-disk prompt never makes startup wait on state.db

Teknium1e565a92f8d8
diff --git a/hermes_cli/prune_advisor.py b/hermes_cli/prune_advisor.py
index b2030f2c485..c7697066f5c 100644
--- a/hermes_cli/prune_advisor.py
+++ b/hermes_cli/prune_advisor.py
@@ -32,6 +32,13 @@ LOW_FREE_PERCENT = 10.0
LOW_FREE_HEADROOM = 20 * GIB
SNOOZE_SECONDS = 7 * 86400
_SNOOZE_FILE = ".auto_prune_prompt.json"
+# The all-rows byte total is a full scan of ``messages`` (seconds, up to tens on a cold multi-GB
+# store), so one measurement is reused for a week, scaled by how much state.db has grown since.
+# The prunable share is read fresh each time through the session index.
+_ESTIMATE_FILE = ".auto_prune_estimate.json"
+TOTAL_BYTES_TTL = 7 * 86400
+# The classic CLI asks from a stored estimate only: it never reads the store at startup.
+CLI_ADVICE_TTL = 86400
@dataclass(frozen=True)
@@ -173,16 +180,81 @@ def advise(home: Optional[Path] = None) -> Optional[Advice]:
prunable_bytes = (db._read_one(
f"SELECT COALESCE(SUM({row_bytes}), 0) FROM messages m WHERE m.session_id IN "
f"(SELECT s.id FROM sessions s WHERE {where})", params) or (0,))[0]
- total_bytes = (db._read_one(
- f"SELECT COALESCE(SUM({row_bytes}), 0) FROM messages m", []) or (0,))[0]
+ total_bytes = _cached_total_bytes(home, snap.db_bytes)
+ if total_bytes is None:
+ total_bytes = (db._read_one(
+ f"SELECT COALESCE(SUM({row_bytes}), 0) FROM messages m", []) or (0,))[0]
+ _store_estimate(home, total_bytes=total_bytes, total_at_db_bytes=snap.db_bytes)
+ total_bytes = max(total_bytes, prunable_bytes) # a stale scaled total never under-counts
finally:
db.close()
except (sqlite3.Error, OSError, RuntimeError, ValueError) as exc: # a busy/damaged store: no estimate
logger.debug("auto-prune advice: reclaim estimate unavailable: %s", exc)
estimate_ok = False
reclaim = int(snap.db_bytes * prunable_bytes / total_bytes) if total_bytes else 0
- return Advice(snap, retention, int(prunable), int(total), reclaim, estimate_ok,
- bool(sessions.get("vacuum_after_prune", True)))
+ advice = Advice(snap, retention, int(prunable), int(total), reclaim, estimate_ok,
+ bool(sessions.get("vacuum_after_prune", True)))
+ if estimate_ok:
+ _store_estimate(home, advice={"retention_days": retention, "prunable": advice.prunable_sessions,
+ "total": advice.total_sessions, "db_bytes": snap.db_bytes,
+ "reclaim_bytes": reclaim})
+ return advice
+
+
+def _read_estimate(home: Optional[Path]) -> dict:
+ try:
+ data = json.loads((_home(home) / _ESTIMATE_FILE).read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _store_estimate(home: Optional[Path], **fields) -> None:
+ """Merge *fields* (each stamped with the time) into the estimate sidecar; a full disk that
+ cannot take the write just means the next estimate measures again."""
+ from utils import atomic_json_write
+ data = _read_estimate(home)
+ now = time.time()
+ for key, value in fields.items():
+ data[key] = value
+ data[f"{key}_at"] = now
+ try:
+ atomic_json_write(_home(home) / _ESTIMATE_FILE, data)
+ except OSError as exc:
+ logger.debug("auto-prune advice: estimate not cached: %s", exc)
+
+
+def _cached_total_bytes(home: Optional[Path], db_bytes: int) -> Optional[int]:
+ """The week-old all-rows byte total scaled to the current file size, or None to re-measure."""
+ data = _read_estimate(home)
+ try:
+ total, at, base = int(data["total_bytes"]), float(data["total_bytes_at"]), int(data["total_at_db_bytes"])
+ except (KeyError, TypeError, ValueError):
+ return None
+ if time.time() - at > TOTAL_BYTES_TTL or base <= 0 or total <= 0:
+ return None
+ return int(total * db_bytes / base)
+
+
+def cached_advice(home: Optional[Path] = None) -> Optional[Advice]:
+ """:func:`advise` from the last stored estimate (under :data:`CLI_ADVICE_TTL` old, same
+ retention), with the live disk snapshot; None when it must be measured first. No DB read."""
+ snap = should_ask(home)
+ if snap is None:
+ return None
+ sessions = _effective_sessions(home) or {}
+ retention = _retention_days(sessions)
+ stored = _read_estimate(home)
+ est = stored.get("advice")
+ try:
+ fresh = time.time() - float(stored["advice_at"]) <= CLI_ADVICE_TTL
+ if not (fresh and isinstance(est, dict) and int(est["retention_days"]) == retention):
+ return None
+ reclaim = int(est["reclaim_bytes"]) * snap.db_bytes // max(int(est["db_bytes"]), 1)
+ return Advice(snap, retention, int(est["prunable"]), int(est["total"]), min(reclaim, snap.db_bytes),
+ True, bool(sessions.get("vacuum_after_prune", True)))
+ except (KeyError, TypeError, ValueError):
+ return None
def _row_bytes_sql(db) -> str:
@@ -323,12 +395,14 @@ def offer_interactive(*, cprint, ask=input) -> Optional[bool]:
or the user chose later."""
if should_ask() is None:
return None
- # The byte estimate reads every message row: seconds on a cold multi-GB store. Say so.
- cprint("\n☤ Low disk space: checking how much session history pruning could free…")
- advice = advise()
+ advice = cached_advice()
if advice is None:
+ # Never read the store on the startup path: measure in the background and ask next launch.
+ from agent.memory_provider import spawn_context_thread
+ spawn_context_thread(advise, name="auto-prune-estimate").start()
return None
- cprint(" " + advice_lines(advice)[0])
+ cprint("")
+ cprint("☤ " + advice_lines(advice)[0])
for line in advice_lines(advice)[1:-1]:
cprint(f" {line}")
try:
diff --git a/tests/hermes_cli/test_prune_advisor.py b/tests/hermes_cli/test_prune_advisor.py
index 39f27821058..45d0be8e7b6 100644
--- a/tests/hermes_cli/test_prune_advisor.py
+++ b/tests/hermes_cli/test_prune_advisor.py
@@ -176,3 +176,44 @@ def test_estimate_weights_by_stored_bytes_not_message_count(tmp_path, monkeypatc
assert advice.reclaim_bytes < before * 0.25
assert abs(advice.reclaim_bytes - shrink) < max(shrink, 64 * 1024) * 1.0
assert "hermes sessions optimize" in "\n".join(prune_advisor.advice_lines(advice))
+
+
+def test_cli_startup_never_reads_the_store_and_asks_from_the_stored_estimate(home, monkeypatch):
+ """The classic CLI asks only from a stored estimate: the first low-disk launch measures in the
+ background and asks nothing; the next launch asks at once from that measurement."""
+ import agent.memory_provider as mp
+ _disk(monkeypatch, free_gb=1)
+ started = []
+ monkeypatch.setattr(mp, "spawn_context_thread", lambda target, **kw: type(
+ "T", (), {"start": lambda self: started.append(target)})())
+ real_advise = prune_advisor.advise
+ def must_not_read(*_a, **_k):
+ raise AssertionError("startup read state.db")
+ monkeypatch.setattr(prune_advisor, "advise", must_not_read)
+ asked = []
+ assert prune_advisor.offer_interactive(cprint=lambda *_: None, ask=lambda q: asked.append(q) or "") is None
+ assert asked == [] and started == [must_not_read] # measured off-thread, nothing asked
+ real_advise(home) # what that background thread does
+ out = []
+ prune_advisor.offer_interactive(cprint=out.append, ask=lambda q: asked.append(q) or "")
+ assert len(asked) == 1 and any("Low disk space" in line for line in out)
+
+
+def test_full_scan_total_is_measured_once_and_reused(home, monkeypatch):
+ """The all-rows byte sum (a full scan) is cached; later estimates reuse it, scaled to the file."""
+ import sqlite3
+ _disk(monkeypatch, free_gb=1)
+ old = time.time() - 200 * 86400
+ with sqlite3.connect(home / "state.db") as conn:
+ conn.execute("UPDATE sessions SET started_at=?, ended_at=?, last_activity_at=?", (old, old, old))
+ conn.execute("UPDATE messages SET timestamp=?", (old,))
+ first = prune_advisor.advise(home)
+ measured = prune_advisor._read_estimate(home)
+ assert measured["total_bytes"] > 0
+ second = prune_advisor.advise(home)
+ assert prune_advisor._read_estimate(home)["total_bytes_at"] == measured["total_bytes_at"] # no rescan
+ assert second.reclaim_bytes == first.reclaim_bytes
+ stale = dict(measured, total_bytes_at=time.time() - prune_advisor.TOTAL_BYTES_TTL - 1)
+ (home / prune_advisor._ESTIMATE_FILE).write_text(__import__("json").dumps(stale), encoding="utf-8")
+ prune_advisor.advise(home)
+ assert prune_advisor._read_estimate(home)["total_bytes_at"] > stale["total_bytes_at"] # a week on: re-measured
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 8189bbb7195..995ab0d2597 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -1141,7 +1141,7 @@ Key tables in `state.db`:
- Gateway conversations persist across inactivity; use `/new` or `/reset` for an explicit boundary
- Before reset, the agent saves memories and skills from the expiring session
- Auto-pruning (**off by default**; opt in): when `sessions.auto_prune` is `true`, ended sessions inactive for `sessions.retention_days` (default 90) are pruned at CLI/gateway/cron startup
-- **Low-disk prompt.** While your `config.yaml` has no `sessions.auto_prune` key, Hermes checks the disk holding `state.db` at session start (two filesystem calls, no measurable cost). When that disk is low (under 2 GB free, or under 10% free with less than 20 GB left) it asks once: the classic CLI asks at startup, the TUI and Desktop show a notice, and a gateway posts the question to its home channel. The prompt estimates how much history a prune would delete (weighted by stored bytes, so many small old messages don't overstate it) and says plainly when pruning will *not* fix the disk (no session older than `retention_days`, or the history is a small share of the full disk). Deleted history frees space inside `state.db`; the automatic `VACUUM` below rarely triggers after a single prune, so run `hermes sessions optimize` to give the space back to the disk. Answer with `/autoprune on`, `/autoprune off` (keep everything; never asked again) or `/autoprune later` (reminded in a week); `/autoprune` alone shows the current state
+- **Low-disk prompt.** While your `config.yaml` has no `sessions.auto_prune` key, Hermes checks the disk holding `state.db` at session start (two filesystem calls, no measurable cost). When that disk is low (under 2 GB free, or under 10% free with less than 20 GB left) it asks once: the classic CLI asks at startup (the first low-disk launch only measures, in the background, and the question appears from the next launch on, so startup never waits on the database), the TUI and Desktop show a notice, and a gateway posts the question to its home channel. The prompt estimates how much history a prune would delete (weighted by stored bytes, so many small old messages don't overstate it) and says plainly when pruning will *not* fix the disk (no session older than `retention_days`, or the history is a small share of the full disk). Deleted history frees space inside `state.db`; the automatic `VACUUM` below rarely triggers after a single prune, so run `hermes sessions optimize` to give the space back to the disk. Answer with `/autoprune on`, `/autoprune off` (keep everything; never asked again) or `/autoprune later` (reminded in a week); `/autoprune` alone shows the current state
- `sessions.retention_days` must be a whole number of days `>= 0`. A negative value (or a missing one) is rejected: startup maintenance logs a warning naming the allowed range and skips the sweep instead of treating the future cutoff as "everything" — `sessions.auto_prune: false` is the switch that disables pruning
- After a prune that actually removed rows, `state.db` is `VACUUM`ed to reclaim disk space only when **both** gates pass: at least `sessions.min_vacuum_interval_days` (default 30) have elapsed since the last successful `VACUUM`, **and** more than 25% of the file's pages are reclaimable (`PRAGMA freelist_count / page_count`). A dense database never pays for a full rewrite to reclaim a few MB (SQLite does not shrink the file on plain DELETE)
- Pruning runs at most once per `sessions.min_interval_hours` (default 24); the last-run timestamp is tracked inside `state.db` itself so it's shared across every Hermes process in the same `HERMES_HOME`