Skip to content

The agent that grows with you

fix(sessions): the low-disk prompt's reclaim estimate tracks stored bytes

Tekniume7e839a5f429
diff --git a/hermes_cli/prune_advisor.py b/hermes_cli/prune_advisor.py
index 87a1a4cd68c..b2030f2c485 100644
--- a/hermes_cli/prune_advisor.py
+++ b/hermes_cli/prune_advisor.py
@@ -55,7 +55,7 @@ class Advice:
retention_days: int
prunable_sessions: int
total_sessions: int
- reclaim_bytes: int # estimate: the prunable share of messages times the file size
+ reclaim_bytes: int # estimate: the prunable share of stored message bytes times the file size
estimate_ok: bool = True # False when state.db could not be read (counts are unknown, not zero)
vacuum_after_prune: bool = True
@@ -156,27 +156,43 @@ def advise(home: Optional[Path] = None) -> Optional[Advice]:
# profile without entering its scope. Only an explicit key differs from the defaults here.
sessions = _effective_sessions(home) or {}
retention = _retention_days(sessions)
- prunable = total = prunable_msgs = total_msgs = 0
+ prunable = total = prunable_bytes = total_bytes = 0
estimate_ok = True
try:
from hermes_state import SessionDB
db = SessionDB(db_path=_home(home) / "state.db", read_only=True)
try:
where, params = db._prune_where(retention, None, {}, whole_lineages=True)
- prunable, prunable_msgs = tuple(db._read_one(
- f"SELECT COUNT(*), COALESCE(SUM(s.message_count), 0) FROM sessions s WHERE {where}", params) or (0, 0))
- total, total_msgs = tuple(db._read_one(
- "SELECT COUNT(*), COALESCE(SUM(message_count), 0) FROM sessions", []) or (0, 0))
+ prunable, total = tuple(db._read_one(
+ f"SELECT (SELECT COUNT(*) FROM sessions s WHERE {where}), (SELECT COUNT(*) FROM sessions)",
+ params) or (0, 0))
+ if prunable:
+ # Weight by stored bytes, not message_count: old messages are far smaller than recent
+ # ones, and message_count skips the soft-archived rows a prune also deletes.
+ row_bytes = _row_bytes_sql(db)
+ 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]
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_msgs / total_msgs) if total_msgs else 0
+ 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)))
+def _row_bytes_sql(db) -> str:
+ """Stored size of one ``messages`` row: the byte length of every text/blob column (read from
+ the live schema, so a column added later is counted without touching this)."""
+ cols = [r[1] for r in db._read_all("PRAGMA table_info(messages)", [])
+ if str(r[2]).upper() in {"TEXT", "BLOB", ""}]
+ return " + ".join(f'COALESCE(LENGTH(CAST(m."{c}" AS BLOB)), 0)' for c in cols) or "0"
+
+
def _gb(n: int) -> str:
"""Human size: GB at or above 1 GiB, MB below (a 26 MB store must not read "0.0 GB")."""
return f"{n / GIB:.1f} GB" if n >= GIB else f"{max(n, 0) / 1024 ** 2:.0f} MB"
@@ -208,9 +224,10 @@ def advice_lines(advice: Advice, *, command_prefix: str = "/") -> list[str]:
lines.append(f"Pruning would remove about {_gb(advice.reclaim_bytes)} of history "
f"({advice.prunable_sessions} of {_sessions(advice.total_sessions)}).")
if advice.estimate_ok and advice.prunable_sessions:
- lines.append("The file shrinks when state.db is next compacted (VACUUM), which needs other Hermes "
- "windows closed." if advice.vacuum_after_prune else
- "sessions.vacuum_after_prune is off, so state.db keeps its size until you run a VACUUM.")
+ # Automatic compaction runs only past a free-page threshold most prunes never reach, so the
+ # disk gets the space back reliably only from an explicit VACUUM.
+ lines.append("Deleted history frees space inside state.db; to give it back to the disk, run "
+ "`hermes sessions optimize` with other Hermes windows closed.")
p = command_prefix
lines.append(f"{p}autoprune on to enable, {p}autoprune off to keep everything (never asked again), "
f"{p}autoprune later to be reminded in a week.")
@@ -304,11 +321,14 @@ def run_command(args: str, home: Optional[Path] = None) -> str:
def offer_interactive(*, cprint, ask=input) -> Optional[bool]:
"""Classic-CLI startup offer (TTY only). Returns the decision, or None when nothing was asked
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()
if advice is None:
return None
- cprint("")
- cprint("☤ " + advice_lines(advice)[0])
+ 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 56cc1a45436..39f27821058 100644
--- a/tests/hermes_cli/test_prune_advisor.py
+++ b/tests/hermes_cli/test_prune_advisor.py
@@ -136,3 +136,43 @@ def test_local_notice_is_neither_re_asked_after_an_answer_nor_spent_on_nobody(ho
monkeypatch.setattr(prune_advisor, "advise", advise_then_answer)
asyncio.run(rhd.publish_local_auto_prune_notice(authority, ref))
assert events.sequence == 1 # nothing re-asked
+
+
+def test_estimate_weights_by_stored_bytes_not_message_count(tmp_path, monkeypatch):
+ """Old sessions hold many small messages, recent ones few large ones: a message-count share
+ overstates what pruning frees (and flips "will not fix this disk"). The estimate must track
+ the bytes a real prune + VACUUM gives back."""
+ import sqlite3
+ from hermes_state import SessionDB
+ h = tmp_path / "skewed"
+ h.mkdir()
+ db = SessionDB(db_path=h / "state.db")
+ old = time.time() - 200 * 86400
+ for i in range(40): # old: 40 x 20 tiny messages
+ db.create_session(f"old{i}", source="cli")
+ for _ in range(20):
+ db.append_message(f"old{i}", role="user", content="ok")
+ db.end_session(f"old{i}", "user_exit")
+ for i in range(4): # recent: 4 x 5 large messages
+ db.create_session(f"new{i}", source="cli")
+ for _ in range(5):
+ db.append_message(f"new{i}", role="assistant", content="x" * 40_000)
+ db.end_session(f"new{i}", "user_exit")
+ db.close()
+ with sqlite3.connect(h / "state.db") as conn:
+ conn.execute("UPDATE sessions SET started_at=?, ended_at=?, last_activity_at=? WHERE id LIKE 'old%'",
+ (old, old, old))
+ conn.execute("UPDATE messages SET timestamp=? WHERE session_id LIKE 'old%'", (old,))
+ _disk(monkeypatch, free_gb=1)
+ advice = prune_advisor.advise(h)
+ assert advice.prunable_sessions == 40
+ before = (h / "state.db").stat().st_size
+ db = SessionDB(db_path=h / "state.db")
+ db.prune_sessions(older_than_days=90)
+ db.vacuum()
+ db.close()
+ shrink = before - (h / "state.db").stat().st_size
+ # message share says ~89% of the file; the bytes really freed are a small fraction of it
+ 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))
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 3d7bce5f2d1..8189bbb7195 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 what a prune would free 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). 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 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`